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/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/BasicAuth.java b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/BasicAuth.java index 5e40bf043..0d69b0f87 100644 --- a/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/BasicAuth.java +++ b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/BasicAuth.java @@ -1,104 +1,105 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.resteasy.interceptor; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.fedoraproject.candlepin.auth.Principal; import org.fedoraproject.candlepin.auth.Role; import org.fedoraproject.candlepin.auth.SystemPrincipal; import org.fedoraproject.candlepin.auth.UserPrincipal; import org.fedoraproject.candlepin.exceptions.NotFoundException; import org.fedoraproject.candlepin.model.Owner; import org.fedoraproject.candlepin.model.OwnerCurator; import org.fedoraproject.candlepin.service.UserServiceAdapter; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; import com.google.inject.Inject; /** * BasicAuth */ class BasicAuth { private Logger log = Logger.getLogger(BasicAuth.class); private UserServiceAdapter userServiceAdapter; private OwnerCurator ownerCurator; @Inject BasicAuth(UserServiceAdapter userServiceAdapter, OwnerCurator ownerCurator) { this.userServiceAdapter = userServiceAdapter; this.ownerCurator = ownerCurator; } Principal getPrincipal(HttpRequest request) throws Exception { List<String> header = request.getHttpHeaders().getRequestHeader("Authorization"); String auth = null; if (null != header && header.size() > 0) { auth = header.get(0); } if (auth != null && auth.toUpperCase().startsWith("BASIC ")) { String userpassEncoded = auth.substring(6); String[] userpass = new String(Base64.decodeBase64(userpassEncoded)) .split(":"); String username = userpass[0]; String password = userpass[1]; - log.debug("check for: " + username + " - " + password); + log.debug("check for: " + username + " - password of length #" + + password.length() + " = <omitted>"); if (userServiceAdapter.validateUser(username, password)) { Principal principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } return principal; } } return null; } private Principal createPrincipal(String username) { Owner owner = this.userServiceAdapter.getOwner(username); owner = lookupOwner(owner); List<Role> roles = this.userServiceAdapter.getRoles(username); return new UserPrincipal(username, owner, roles); } private Owner lookupOwner(Owner owner) { Owner o = this.ownerCurator.lookupByKey(owner.getKey()); if (o == null) { if (owner.getKey() == null) { throw new NotFoundException("An owner does not exist for a null org id"); } Principal systemPrincipal = new SystemPrincipal(); ResteasyProviderFactory.pushContext(Principal.class, systemPrincipal); o = this.ownerCurator.create(owner); ResteasyProviderFactory.popContextData(Principal.class); } return o; } }
true
true
Principal getPrincipal(HttpRequest request) throws Exception { List<String> header = request.getHttpHeaders().getRequestHeader("Authorization"); String auth = null; if (null != header && header.size() > 0) { auth = header.get(0); } if (auth != null && auth.toUpperCase().startsWith("BASIC ")) { String userpassEncoded = auth.substring(6); String[] userpass = new String(Base64.decodeBase64(userpassEncoded)) .split(":"); String username = userpass[0]; String password = userpass[1]; log.debug("check for: " + username + " - " + password); if (userServiceAdapter.validateUser(username, password)) { Principal principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } return principal; } } return null; }
Principal getPrincipal(HttpRequest request) throws Exception { List<String> header = request.getHttpHeaders().getRequestHeader("Authorization"); String auth = null; if (null != header && header.size() > 0) { auth = header.get(0); } if (auth != null && auth.toUpperCase().startsWith("BASIC ")) { String userpassEncoded = auth.substring(6); String[] userpass = new String(Base64.decodeBase64(userpassEncoded)) .split(":"); String username = userpass[0]; String password = userpass[1]; log.debug("check for: " + username + " - password of length #" + password.length() + " = <omitted>"); if (userServiceAdapter.validateUser(username, password)) { Principal principal = createPrincipal(username); if (log.isDebugEnabled()) { log.debug("principal created for owner '" + principal.getOwner().getDisplayName() + "' with username '" + username + "'"); } return principal; } } return null; }
diff --git a/src/Issue.java b/src/Issue.java index cc53e98..d6d1e32 100644 --- a/src/Issue.java +++ b/src/Issue.java @@ -1,183 +1,183 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import com.google.gson.Gson; import core.event.Join; import core.event.Kick; import core.event.Message; import core.event.Quit; import core.helpers.IRCException; import core.plugin.PluginTemp; import core.utils.Details; import core.utils.IRC; /** * Allows admin users to create a new bug on github's issue tracker. * @author Tom Leaman (tom@tomleaman.co.uk) */ public class Issue implements PluginTemp { private static final String AUTH_TOKEN_FILE = "auth_token"; private static final String GITHUB_URL = "https://api.github.com"; private static final String REPO_OWNER = "XeTK"; private static final String REPO_NAME = "JavaBot"; private Details details = Details.getInstance(); private IRC irc = IRC.getInstance(); private String authToken; private boolean loaded = false; public Issue() { try { authToken = loadAuthToken(AUTH_TOKEN_FILE); } catch (FileNotFoundException e) { System.err.println("No auth token file found in " + AUTH_TOKEN_FILE); System.err.println("Issue plugin failed to load"); } if (!authToken.equals(new String())) loaded = true; } private String loadAuthToken(String filename) throws FileNotFoundException { File f = new File(filename); BufferedReader in = new BufferedReader(new FileReader(f)); String line = new String(); try { line = in.readLine(); in.close(); } catch (IOException e) { // tin foil hats a-plenty loaded = false; line = new String(); e.printStackTrace(); } return line; } @Override public void onMessage(Message message) throws Exception { if (!loaded) return; if (message.getMessage().startsWith(".bug") && details.isAdmin(message.getUser())) createIssue(message); } @Override public String getHelpString() { return "ISSUE: .bug <one_line_bug_report>"; } private void createIssue(Message message) throws IssueException { String issueTitle = message.getMessage().substring(5); String issueBody = "This message was generated automatically by " + message.getUser() + " in " + message.getChannel() + - ". Once confirmed, please remove `unconfirmed` tag."; + ". Once confirmed, please remove `unconfirmed` tag. :octocat:"; String jsonContent = "{\"title\":\"" + issueTitle + "\"" + ",\"body\":\"" + issueBody + "\"" + ",\"labels\":[\"bug\", \"unconfirmed\"]}"; try { URL endpoint = new URL( GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues"); HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "token " + authToken); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.getOutputStream().write(jsonContent.getBytes("UTF-8")); int responseCode = conn.getResponseCode(); if (responseCode >= 400) { throw new IssueException( "Failed to create issue (" + responseCode + ")."); } StringBuffer response = new StringBuffer(); String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = in.readLine()) != null) { response.append(line); } in.close(); // send issue url to user Gson parser = new Gson(); IssueResponse responseData = (IssueResponse)parser.fromJson(response.toString(), IssueResponse.class); irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " + "Issue #" + responseData.getNumber() + " created: " + responseData.getHtmlUrl()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IRCException e) { e.printStackTrace(); } } @Override public void rawInput(String input) { } @Override public void onCreate(String create) { } @Override public void onTime() throws Exception { } @Override public void onJoin(Join join) throws Exception { } @Override public void onQuit(Quit quit) throws Exception { } @Override public void onKick(Kick kick) throws Exception { } @Override public String name() { return this.toString(); } @Override public String toString() { return "Issue"; } private class IssueException extends Exception { public IssueException(String msg) { super(msg); } } }
true
true
private void createIssue(Message message) throws IssueException { String issueTitle = message.getMessage().substring(5); String issueBody = "This message was generated automatically by " + message.getUser() + " in " + message.getChannel() + ". Once confirmed, please remove `unconfirmed` tag."; String jsonContent = "{\"title\":\"" + issueTitle + "\"" + ",\"body\":\"" + issueBody + "\"" + ",\"labels\":[\"bug\", \"unconfirmed\"]}"; try { URL endpoint = new URL( GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues"); HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "token " + authToken); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.getOutputStream().write(jsonContent.getBytes("UTF-8")); int responseCode = conn.getResponseCode(); if (responseCode >= 400) { throw new IssueException( "Failed to create issue (" + responseCode + ")."); } StringBuffer response = new StringBuffer(); String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = in.readLine()) != null) { response.append(line); } in.close(); // send issue url to user Gson parser = new Gson(); IssueResponse responseData = (IssueResponse)parser.fromJson(response.toString(), IssueResponse.class); irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " + "Issue #" + responseData.getNumber() + " created: " + responseData.getHtmlUrl()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IRCException e) { e.printStackTrace(); } }
private void createIssue(Message message) throws IssueException { String issueTitle = message.getMessage().substring(5); String issueBody = "This message was generated automatically by " + message.getUser() + " in " + message.getChannel() + ". Once confirmed, please remove `unconfirmed` tag. :octocat:"; String jsonContent = "{\"title\":\"" + issueTitle + "\"" + ",\"body\":\"" + issueBody + "\"" + ",\"labels\":[\"bug\", \"unconfirmed\"]}"; try { URL endpoint = new URL( GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues"); HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "token " + authToken); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.getOutputStream().write(jsonContent.getBytes("UTF-8")); int responseCode = conn.getResponseCode(); if (responseCode >= 400) { throw new IssueException( "Failed to create issue (" + responseCode + ")."); } StringBuffer response = new StringBuffer(); String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); while ((line = in.readLine()) != null) { response.append(line); } in.close(); // send issue url to user Gson parser = new Gson(); IssueResponse responseData = (IssueResponse)parser.fromJson(response.toString(), IssueResponse.class); irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " + "Issue #" + responseData.getNumber() + " created: " + responseData.getHtmlUrl()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IRCException e) { e.printStackTrace(); } }
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java index b15120e8a..af7f0a587 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/engine/ProfileMetadataRepositoryTest.java @@ -1,166 +1,173 @@ /******************************************************************************* * Copyright (c) 2007, 2009 IBM Corporation 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.p2.tests.engine; import java.io.File; import org.eclipse.core.runtime.IStatus; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.engine.IProfile; import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.internal.provisional.p2.query.Collector; import org.eclipse.equinox.internal.provisional.spi.p2.artifact.repository.SimpleArtifactRepositoryFactory; import org.eclipse.equinox.p2.tests.AbstractProvisioningTest; import org.eclipse.equinox.p2.tests.TestActivator; /** * Simple test of the engine API. */ public class ProfileMetadataRepositoryTest extends AbstractProvisioningTest { public ProfileMetadataRepositoryTest() { super(""); } public ProfileMetadataRepositoryTest(String name) { super(name); } public void testCreate() { ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); try { assertNull(factory.create(getTempFolder().toURI(), "", "", null)); } catch (ProvisionException e) { fail(); } } public void testValidate() { File testData = getTestData("0.1", "testData/sdkpatchingtest/p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); File simpleProfileFolder = new File(tempFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); IStatus status = factory.validate(simpleProfileFolder.toURI(), getMonitor()); assertTrue(status.isOK()); status = factory.validate(tempFolder.toURI(), getMonitor()); assertFalse(status.isOK()); } public void testLoad() { File testData = getTestData("0.1", "testData/sdkpatchingtest/p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); SimpleProfileRegistry registry = new SimpleProfileRegistry(tempFolder, null, false); IProfile profile = registry.getProfile("SDKProfile"); assertNotNull(profile); Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(profileCollector.isEmpty()); File simpleProfileFolder = new File(tempFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); ProfileMetadataRepository repo = null; try { repo = (ProfileMetadataRepository) factory.load(simpleProfileFolder.toURI(), 0, getMonitor()); } catch (ProvisionException e1) { fail(); } Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(repoCollector.isEmpty()); assertTrue(repoCollector.toCollection().containsAll(profileCollector.toCollection())); } public void testLoadTimestampedProfile() { File testData = getTestData("0.1", "testData/sdkpatchingtest/p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); SimpleProfileRegistry registry = new SimpleProfileRegistry(tempFolder, null, false); IProfile profile = registry.getProfile("SDKProfile"); assertNotNull(profile); Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(profileCollector.isEmpty()); File simpleProfileFolder = new File(tempFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); File timeStampedProfile = new File(simpleProfileFolder, "" + profile.getTimestamp() + ".profile"); assertTrue(timeStampedProfile.exists()); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); ProfileMetadataRepository repo = null; try { repo = (ProfileMetadataRepository) factory.load(timeStampedProfile.toURI(), 0, getMonitor()); } catch (ProvisionException e1) { fail(); } Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(repoCollector.isEmpty()); assertTrue(repoCollector.toCollection().containsAll(profileCollector.toCollection())); } - public void testDefaultAgentRepoAndBundlePoolFromProfileRepo() { + public void testDefaultAgentRepoAndBundlePoolFromProfileRepo() throws InterruptedException { File testData = getTestData("0.1", "testData/sdkpatchingtest"); // /p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); new SimpleArtifactRepositoryFactory().create(tempFolder.toURI(), "", "", null); File defaultAgenRepositoryDirectory = new File(tempFolder, "p2/org.eclipse.equinox.p2.core"); new SimpleArtifactRepositoryFactory().create(defaultAgenRepositoryDirectory.toURI(), "", "", null); File profileRegistryFolder = new File(tempFolder, "p2/org.eclipse.equinox.p2.engine/profileRegistry"); SimpleProfileRegistry registry = new SimpleProfileRegistry(profileRegistryFolder, null, false); IProfile profile = registry.getProfile("SDKProfile"); assertNotNull(profile); Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(profileCollector.isEmpty()); File simpleProfileFolder = new File(profileRegistryFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); File timeStampedProfile = new File(simpleProfileFolder, "" + profile.getTimestamp() + ".profile"); assertTrue(timeStampedProfile.exists()); IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); assertNotNull(manager); assertFalse(manager.contains(tempFolder.toURI())); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); ProfileMetadataRepository repo = null; try { repo = (ProfileMetadataRepository) factory.load(timeStampedProfile.toURI(), 0, getMonitor()); } catch (ProvisionException e1) { fail(); } Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(repoCollector.isEmpty()); assertTrue(repoCollector.toCollection().containsAll(profileCollector.toCollection())); - assertTrue(manager.contains(tempFolder.toURI())); - assertTrue(manager.contains(defaultAgenRepositoryDirectory.toURI())); + int maxTries = 20; + int current = 0; + while (true) { + if (manager.contains(tempFolder.toURI()) && manager.contains(defaultAgenRepositoryDirectory.toURI())) + break; + if (++current == maxTries) + fail("profile artifact repos not added"); + Thread.sleep(100); + } } }
false
true
public void testDefaultAgentRepoAndBundlePoolFromProfileRepo() { File testData = getTestData("0.1", "testData/sdkpatchingtest"); // /p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); new SimpleArtifactRepositoryFactory().create(tempFolder.toURI(), "", "", null); File defaultAgenRepositoryDirectory = new File(tempFolder, "p2/org.eclipse.equinox.p2.core"); new SimpleArtifactRepositoryFactory().create(defaultAgenRepositoryDirectory.toURI(), "", "", null); File profileRegistryFolder = new File(tempFolder, "p2/org.eclipse.equinox.p2.engine/profileRegistry"); SimpleProfileRegistry registry = new SimpleProfileRegistry(profileRegistryFolder, null, false); IProfile profile = registry.getProfile("SDKProfile"); assertNotNull(profile); Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(profileCollector.isEmpty()); File simpleProfileFolder = new File(profileRegistryFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); File timeStampedProfile = new File(simpleProfileFolder, "" + profile.getTimestamp() + ".profile"); assertTrue(timeStampedProfile.exists()); IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); assertNotNull(manager); assertFalse(manager.contains(tempFolder.toURI())); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); ProfileMetadataRepository repo = null; try { repo = (ProfileMetadataRepository) factory.load(timeStampedProfile.toURI(), 0, getMonitor()); } catch (ProvisionException e1) { fail(); } Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(repoCollector.isEmpty()); assertTrue(repoCollector.toCollection().containsAll(profileCollector.toCollection())); assertTrue(manager.contains(tempFolder.toURI())); assertTrue(manager.contains(defaultAgenRepositoryDirectory.toURI())); }
public void testDefaultAgentRepoAndBundlePoolFromProfileRepo() throws InterruptedException { File testData = getTestData("0.1", "testData/sdkpatchingtest"); // /p2/org.eclipse.equinox.p2.engine/profileRegistry"); File tempFolder = getTempFolder(); copy("0.2", testData, tempFolder); new SimpleArtifactRepositoryFactory().create(tempFolder.toURI(), "", "", null); File defaultAgenRepositoryDirectory = new File(tempFolder, "p2/org.eclipse.equinox.p2.core"); new SimpleArtifactRepositoryFactory().create(defaultAgenRepositoryDirectory.toURI(), "", "", null); File profileRegistryFolder = new File(tempFolder, "p2/org.eclipse.equinox.p2.engine/profileRegistry"); SimpleProfileRegistry registry = new SimpleProfileRegistry(profileRegistryFolder, null, false); IProfile profile = registry.getProfile("SDKProfile"); assertNotNull(profile); Collector profileCollector = profile.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(profileCollector.isEmpty()); File simpleProfileFolder = new File(profileRegistryFolder, "SDKProfile.profile"); assertTrue(simpleProfileFolder.exists()); File timeStampedProfile = new File(simpleProfileFolder, "" + profile.getTimestamp() + ".profile"); assertTrue(timeStampedProfile.exists()); IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(TestActivator.context, IArtifactRepositoryManager.class.getName()); assertNotNull(manager); assertFalse(manager.contains(tempFolder.toURI())); ProfileMetadataRepositoryFactory factory = new ProfileMetadataRepositoryFactory(); ProfileMetadataRepository repo = null; try { repo = (ProfileMetadataRepository) factory.load(timeStampedProfile.toURI(), 0, getMonitor()); } catch (ProvisionException e1) { fail(); } Collector repoCollector = repo.query(InstallableUnitQuery.ANY, new Collector(), getMonitor()); assertFalse(repoCollector.isEmpty()); assertTrue(repoCollector.toCollection().containsAll(profileCollector.toCollection())); int maxTries = 20; int current = 0; while (true) { if (manager.contains(tempFolder.toURI()) && manager.contains(defaultAgenRepositoryDirectory.toURI())) break; if (++current == maxTries) fail("profile artifact repos not added"); Thread.sleep(100); } }
diff --git a/com/buglabs/bug/module/lcd/accelerometer/LCDAccelerometerSampleInputStream.java b/com/buglabs/bug/module/lcd/accelerometer/LCDAccelerometerSampleInputStream.java index bad8707..9bcf872 100644 --- a/com/buglabs/bug/module/lcd/accelerometer/LCDAccelerometerSampleInputStream.java +++ b/com/buglabs/bug/module/lcd/accelerometer/LCDAccelerometerSampleInputStream.java @@ -1,45 +1,47 @@ package com.buglabs.bug.module.lcd.accelerometer; import java.io.IOException; import java.io.InputStream; import com.buglabs.bug.accelerometer.pub.AccelerometerSample; import com.buglabs.bug.accelerometer.pub.AccelerometerSampleStream; public class LCDAccelerometerSampleInputStream extends AccelerometerSampleStream { private static final int SIGN_MASK = 0x2000; public LCDAccelerometerSampleInputStream(InputStream is) { super(is); } public AccelerometerSample readSample() throws IOException { byte data[] = new byte[6]; short sample[] = null; int result = read(data); if(result == data.length) { sample = new short[3]; for(int i = 0; i < sample.length; ++i) { sample[i] = (short)((short)(data[i*2] << 8) + (short)data[i*2 + 1]); } + } else { + throw new IOException("Unable to read sample from accelerometer\n Read length = " + result); } return new AccelerometerSample(convertToGs(sample[2]), convertToGs(sample[1]), convertToGs(sample[0])); } private float convertToGs(short s) { if((SIGN_MASK & s) != 0) { return -1 * (~s) / 1024.0f; } return s / 1024.0f; } }
true
true
public AccelerometerSample readSample() throws IOException { byte data[] = new byte[6]; short sample[] = null; int result = read(data); if(result == data.length) { sample = new short[3]; for(int i = 0; i < sample.length; ++i) { sample[i] = (short)((short)(data[i*2] << 8) + (short)data[i*2 + 1]); } } return new AccelerometerSample(convertToGs(sample[2]), convertToGs(sample[1]), convertToGs(sample[0])); }
public AccelerometerSample readSample() throws IOException { byte data[] = new byte[6]; short sample[] = null; int result = read(data); if(result == data.length) { sample = new short[3]; for(int i = 0; i < sample.length; ++i) { sample[i] = (short)((short)(data[i*2] << 8) + (short)data[i*2 + 1]); } } else { throw new IOException("Unable to read sample from accelerometer\n Read length = " + result); } return new AccelerometerSample(convertToGs(sample[2]), convertToGs(sample[1]), convertToGs(sample[0])); }
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java index 925b41334..e3a37217e 100644 --- a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java +++ b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java @@ -1,139 +1,139 @@ /* * Copyright 2011 Jeanfrancois Arcand * * 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.atmosphere.container; import org.atmosphere.cpr.Action; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AsynchronousProcessor; import org.atmosphere.cpr.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResponse; import org.atmosphere.util.Utils; import org.atmosphere.websocket.WebSocket; import org.atmosphere.websocket.WebSocketProcessor; import org.eclipse.jetty.websocket.WebSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR; public class JettyWebSocketUtil { private static final Logger logger = LoggerFactory.getLogger(JettyWebSocketUtil.class); public final static Action doService(AsynchronousProcessor cometSupport, AtmosphereRequest req, AtmosphereResponse res, WebSocketFactory webSocketFactory) throws IOException, ServletException { Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED); if (b == null) b = Boolean.FALSE; if (!Utils.webSocketEnabled(req) && req.getAttribute(WebSocket.WEBSOCKET_ACCEPT_DONE) == null) { if (req.resource() != null && req.resource().transport() == AtmosphereResource.TRANSPORT.WEBSOCKET) { logger.trace("Invalid WebSocket Specification {}", req); res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported"); res.sendError(501, "Websocket protocol not supported"); return Action.CANCELLED; } else { return null; } } else { if (webSocketFactory != null && !b) { req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true); try { webSocketFactory.acceptWebSocket(req, res); } catch (IllegalStateException ex) { logger.trace("Invalid WebSocket Specification {}", req); logger.trace("", ex); res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported"); res.sendError(501, "Websocket protocol not supported"); return Action.CANCELLED; } req.setAttribute(WebSocket.WEBSOCKET_ACCEPT_DONE, true); return new Action(); } Action action = cometSupport.suspended(req, res); if (action.type() == Action.TYPE.SUSPEND) { } else if (action.type() == Action.TYPE.RESUME) { req.setAttribute(WebSocket.WEBSOCKET_RESUME, true); } return action; } } public final static WebSocketFactory getFactory(final AtmosphereConfig config, final WebSocketProcessor webSocketProcessor) { WebSocketFactory webSocketFactory = new WebSocketFactory(new WebSocketFactory.Acceptor() { public boolean checkOrigin(HttpServletRequest request, String origin) { // Allow all origins logger.trace("WebSocket-checkOrigin request {} with origin {}", request.getRequestURI(), origin); return true; } public org.eclipse.jetty.websocket.WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { logger.trace("WebSocket-connect request {} with protocol {}", request.getRequestURI(), protocol); boolean isDestroyable = false; String s = config.getInitParameter(ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE); if (s != null && Boolean.valueOf(s)) { isDestroyable = true; } return new JettyWebSocketHandler(AtmosphereRequest.cloneRequest(request, false, config.isSupportSession(), isDestroyable), config.framework(), webSocketProcessor); } }); int bufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE) != null) { bufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE)); } - logger.debug("WebSocket Buffer side {}", bufferSize); + logger.debug("WebSocket Buffer size {}", bufferSize); webSocketFactory.setBufferSize(bufferSize); int timeOut = 5 * 60000; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME) != null) { timeOut = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME)); } logger.debug("WebSocket idle timeout {}", timeOut); webSocketFactory.setMaxIdleTime(timeOut); int maxTextBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE) != null) { maxTextBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE)); } logger.debug("WebSocket maxTextBufferSize {}", maxTextBufferSize); webSocketFactory.setMaxTextMessageSize(maxTextBufferSize); int maxBinaryBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE) != null) { maxBinaryBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE)); } logger.debug("WebSocket maxBinaryBufferSize {}", maxBinaryBufferSize); webSocketFactory.setMaxBinaryMessageSize(maxBinaryBufferSize); return webSocketFactory; } }
true
true
public final static WebSocketFactory getFactory(final AtmosphereConfig config, final WebSocketProcessor webSocketProcessor) { WebSocketFactory webSocketFactory = new WebSocketFactory(new WebSocketFactory.Acceptor() { public boolean checkOrigin(HttpServletRequest request, String origin) { // Allow all origins logger.trace("WebSocket-checkOrigin request {} with origin {}", request.getRequestURI(), origin); return true; } public org.eclipse.jetty.websocket.WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { logger.trace("WebSocket-connect request {} with protocol {}", request.getRequestURI(), protocol); boolean isDestroyable = false; String s = config.getInitParameter(ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE); if (s != null && Boolean.valueOf(s)) { isDestroyable = true; } return new JettyWebSocketHandler(AtmosphereRequest.cloneRequest(request, false, config.isSupportSession(), isDestroyable), config.framework(), webSocketProcessor); } }); int bufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE) != null) { bufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE)); } logger.debug("WebSocket Buffer side {}", bufferSize); webSocketFactory.setBufferSize(bufferSize); int timeOut = 5 * 60000; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME) != null) { timeOut = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME)); } logger.debug("WebSocket idle timeout {}", timeOut); webSocketFactory.setMaxIdleTime(timeOut); int maxTextBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE) != null) { maxTextBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE)); } logger.debug("WebSocket maxTextBufferSize {}", maxTextBufferSize); webSocketFactory.setMaxTextMessageSize(maxTextBufferSize); int maxBinaryBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE) != null) { maxBinaryBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE)); } logger.debug("WebSocket maxBinaryBufferSize {}", maxBinaryBufferSize); webSocketFactory.setMaxBinaryMessageSize(maxBinaryBufferSize); return webSocketFactory; }
public final static WebSocketFactory getFactory(final AtmosphereConfig config, final WebSocketProcessor webSocketProcessor) { WebSocketFactory webSocketFactory = new WebSocketFactory(new WebSocketFactory.Acceptor() { public boolean checkOrigin(HttpServletRequest request, String origin) { // Allow all origins logger.trace("WebSocket-checkOrigin request {} with origin {}", request.getRequestURI(), origin); return true; } public org.eclipse.jetty.websocket.WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { logger.trace("WebSocket-connect request {} with protocol {}", request.getRequestURI(), protocol); boolean isDestroyable = false; String s = config.getInitParameter(ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE); if (s != null && Boolean.valueOf(s)) { isDestroyable = true; } return new JettyWebSocketHandler(AtmosphereRequest.cloneRequest(request, false, config.isSupportSession(), isDestroyable), config.framework(), webSocketProcessor); } }); int bufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE) != null) { bufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE)); } logger.debug("WebSocket Buffer size {}", bufferSize); webSocketFactory.setBufferSize(bufferSize); int timeOut = 5 * 60000; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME) != null) { timeOut = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME)); } logger.debug("WebSocket idle timeout {}", timeOut); webSocketFactory.setMaxIdleTime(timeOut); int maxTextBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE) != null) { maxTextBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE)); } logger.debug("WebSocket maxTextBufferSize {}", maxTextBufferSize); webSocketFactory.setMaxTextMessageSize(maxTextBufferSize); int maxBinaryBufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE) != null) { maxBinaryBufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE)); } logger.debug("WebSocket maxBinaryBufferSize {}", maxBinaryBufferSize); webSocketFactory.setMaxBinaryMessageSize(maxBinaryBufferSize); return webSocketFactory; }
diff --git a/src/org/encog/solve/anneal/SimulatedAnnealing.java b/src/org/encog/solve/anneal/SimulatedAnnealing.java index 09567aae7..23d7e8851 100644 --- a/src/org/encog/solve/anneal/SimulatedAnnealing.java +++ b/src/org/encog/solve/anneal/SimulatedAnnealing.java @@ -1,242 +1,242 @@ /* * Encog Artificial Intelligence Framework v2.x * Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * * Copyright 2008-2009, Heaton Research Inc., and individual contributors. * See the copyright.txt in the distribution for a full listing of * individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.encog.solve.anneal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simulated annealing is a common training method. This class implements a * simulated annealing algorithm that can be used both for neural networks, as * well as more general cases. This class is abstract, so a more specialized * simulated annealing subclass will need to be created for each intended use. * This book demonstrates how to use the simulated annealing algorithm to train * feedforward neural networks, as well as find a solution to the traveling * salesman problem. * * The name and inspiration come from annealing in metallurgy, a technique * involving heating and controlled cooling of a material to increase the size * of its crystals and reduce their defects. The heat causes the atoms to become * unstuck from their initial positions (a local minimum of the internal energy) * and wander randomly through states of higher energy; the slow cooling gives * them more chances of finding configurations with lower internal energy than * the initial one. * * @param <UNIT_TYPE> * What type of data makes up the solution. */ public abstract class SimulatedAnnealing<UNIT_TYPE> { /** * The starting temperature. */ private double startTemperature; /** * The ending temperature. */ private double stopTemperature; /** * The number of cycles that will be used. */ private int cycles; /** * The current score. */ private double score; /** * The current temperature. */ private double temperature; private boolean shouldMinimize = true; /** * The logging object. */ @SuppressWarnings("unused") private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * Subclasses should provide a method that evaluates the score for the * current solution. Those solutions with a lower score are better. * * @return Return the score. */ public abstract double calculateScore(); /** * Subclasses must provide access to an array that makes up the solution. * * @return An array that makes up the solution. */ public abstract UNIT_TYPE[] getArray(); /** * Get a copy of the array. * * @return A copy of the array. */ public abstract UNIT_TYPE[] getArrayCopy(); /** * @return the cycles */ public int getCycles() { return this.cycles; } /** * @return the globalScore */ public double getScore() { return this.score; } /** * @return the startTemperature */ public double getStartTemperature() { return this.startTemperature; } /** * @return the stopTemperature */ public double getStopTemperature() { return this.stopTemperature; } /** * @return the temperature */ public double getTemperature() { return this.temperature; } /** * Called to perform one cycle of the annealing process. */ public void iteration() { UNIT_TYPE[] bestArray; setScore(calculateScore()); bestArray = this.getArrayCopy(); this.temperature = this.getStartTemperature(); for (int i = 0; i < this.cycles; i++) { double curScore; randomize(); curScore = calculateScore(); - if (this.shouldMinimize) { + if (!this.shouldMinimize) { if (curScore < getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } else { if (curScore > getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } this.putArray(bestArray); final double ratio = Math.exp(Math.log(getStopTemperature() / getStartTemperature()) / (getCycles() - 1)); this.temperature *= ratio; } } /** * Store the array. * * @param array * The array to be stored. */ public abstract void putArray(UNIT_TYPE[] array); /** * Randomize the weight matrix. */ public abstract void randomize(); /** * @param cycles * the cycles to set */ public void setCycles(final int cycles) { this.cycles = cycles; } /** * Set the score. * * @param score * The score to set. */ public void setScore(final double score) { this.score = score; } /** * @param startTemperature * the startTemperature to set */ public void setStartTemperature(final double startTemperature) { this.startTemperature = startTemperature; } /** * @param stopTemperature * the stopTemperature to set */ public void setStopTemperature(final double stopTemperature) { this.stopTemperature = stopTemperature; } /** * @param temperature * the temperature to set */ public void setTemperature(final double temperature) { this.temperature = temperature; } public boolean isShouldMinimize() { return shouldMinimize; } public void setShouldMinimize(boolean shouldMinimize) { this.shouldMinimize = shouldMinimize; } }
true
true
public void iteration() { UNIT_TYPE[] bestArray; setScore(calculateScore()); bestArray = this.getArrayCopy(); this.temperature = this.getStartTemperature(); for (int i = 0; i < this.cycles; i++) { double curScore; randomize(); curScore = calculateScore(); if (this.shouldMinimize) { if (curScore < getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } else { if (curScore > getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } this.putArray(bestArray); final double ratio = Math.exp(Math.log(getStopTemperature() / getStartTemperature()) / (getCycles() - 1)); this.temperature *= ratio; } }
public void iteration() { UNIT_TYPE[] bestArray; setScore(calculateScore()); bestArray = this.getArrayCopy(); this.temperature = this.getStartTemperature(); for (int i = 0; i < this.cycles; i++) { double curScore; randomize(); curScore = calculateScore(); if (!this.shouldMinimize) { if (curScore < getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } else { if (curScore > getScore()) { bestArray = this.getArrayCopy(); setScore(curScore); } } this.putArray(bestArray); final double ratio = Math.exp(Math.log(getStopTemperature() / getStartTemperature()) / (getCycles() - 1)); this.temperature *= ratio; } }
diff --git a/src/edu/umn/se/trap/db/GrantDBWrapper.java b/src/edu/umn/se/trap/db/GrantDBWrapper.java index 448c885..ecbd39c 100644 --- a/src/edu/umn/se/trap/db/GrantDBWrapper.java +++ b/src/edu/umn/se/trap/db/GrantDBWrapper.java @@ -1,70 +1,70 @@ /***************************************************************************************** * Copyright (c) 2012 Dylan Bettermann, Andrew Helgeson, Brian Maurer, Ethan Waytas * * 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 edu.umn.se.trap.db; import java.util.List; /** * @author andrewh * */ public class GrantDBWrapper { private static GrantDB grantDB; public static List<Object> getGrantInfo(String accountName) throws KeyNotFoundException { return grantDB.getGrantInfo(accountName); } public static Double getGrantBalance(String accountName) throws KeyNotFoundException { List<Object> grantInfo = getGrantInfo(accountName); return (Double) grantInfo.get(GrantDB.GRANT_FIELDS.ACCOUNT_BALANCE.ordinal()); } public static String getGrantType(String accountName) throws KeyNotFoundException { List<Object> grantInfo = getGrantInfo(accountName); return (String) grantInfo.get(GrantDB.GRANT_FIELDS.ACCOUNT_TYPE.ordinal()); } public static void updateAccountBalance(String accountName, Double newBalance) throws KeyNotFoundException { grantDB.updateAccountBalance(accountName, newBalance); } public static void setGrantDB(GrantDB db) { grantDB = db; } // Testing a boolean method // TODO Add some printing/logging in here - public static boolean isValidGrant(String accountName) throws KeyNotFoundException + public static boolean isValidGrant(String accountName) { try { grantDB.getGrantInfo(accountName); return true; } catch (KeyNotFoundException e) { return false; } } }
true
true
public static boolean isValidGrant(String accountName) throws KeyNotFoundException { try { grantDB.getGrantInfo(accountName); return true; } catch (KeyNotFoundException e) { return false; } }
public static boolean isValidGrant(String accountName) { try { grantDB.getGrantInfo(accountName); return true; } catch (KeyNotFoundException e) { return false; } }
diff --git a/src/com/mistphizzle/donationpoints/plugin/SignListener.java b/src/com/mistphizzle/donationpoints/plugin/SignListener.java index 5afb88a..12a5918 100644 --- a/src/com/mistphizzle/donationpoints/plugin/SignListener.java +++ b/src/com/mistphizzle/donationpoints/plugin/SignListener.java @@ -1,154 +1,155 @@ package com.mistphizzle.donationpoints.plugin; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Hanging; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.block.Sign; public class SignListener implements Listener { public static String SignMessage; public static DonationPoints plugin; public SignListener(DonationPoints instance) { plugin = instance; } @EventHandler public void HangingEvent(HangingBreakByEntityEvent e) { Hanging broken = e.getEntity(); Entity remover = e.getRemover(); if (remover instanceof Player) { Player player = (Player) remover; if (broken instanceof ItemFrame) { Double x = broken.getLocation().getX(); Double y = broken.getLocation().getY(); Double z = broken.getLocation().getZ(); String world = broken.getWorld().getName(); if (PlayerListener.links.containsKey(player.getName())) { String packName = PlayerListener.links.get(player.getName()); if (Methods.isFrameLinked(x, y, z, world)) { player.sendMessage(Commands.Prefix + "�cThis item frame is already linked."); + PlayerListener.links.remove(player.getName()); e.setCancelled(true); return; } Methods.linkFrame(packName, x, y, z, world); player.sendMessage(Commands.Prefix + "�cSuccessfully linked �3" + packName + "�3."); PlayerListener.links.remove(player.getName()); e.setCancelled(true); } else if (!PlayerListener.links.containsKey(player.getName())) { if (Methods.isFrameLinked(x, y, z, world)) { if (player.isSneaking()) { if (!DonationPoints.permission.has(player, "donationpoints.sign.break")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } if (DonationPoints.permission.has(player, "donationpoints.sign.break")) { Methods.unlinkFrame(x, y, z, world); player.sendMessage(Commands.Prefix + "�cItem Frame unlinked."); e.setCancelled(false); return; } } e.setCancelled(true); String packName = Methods.getLinkedPackage(x, y, z, world); Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String packDesc = plugin.getConfig().getString("packages." + packName + ".description"); if (!DonationPoints.permission.has(player, "donationpoints.sign.use")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); return; } if (DonationPoints.permission.has(player, "donationpoints.free")) { price = 0.0; } if (plugin.getConfig().getBoolean("General.SpecificPermissions", true)) { if (!DonationPoints.permission.has(player, "donationpoints.sign.use." + packName)) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); } if (!plugin.getConfig().getBoolean("General.SpecificPermissions")) { player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); return; } } } } } } @EventHandler public void onBlockBreak(BlockBreakEvent e) { Player player = e.getPlayer(); Block block = e.getBlock(); if (block.getState() instanceof Sign) { Sign s = (Sign) block.getState(); String signline1 = s.getLine(0); if (signline1.equalsIgnoreCase("[" + SignMessage + "]") && DonationPoints.permission.has(player, "donationpoints.sign.break")) { if (player.getGameMode() == GameMode.CREATIVE) { if (!player.isSneaking()) { player.sendMessage(Commands.Prefix + "�cYou must sneak to break DonationPoints signs while in Creative."); e.setCancelled(true); } } } if (!DonationPoints.permission.has(player, "donationpoints.sign.break")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); } } } @EventHandler public void onSignChance(SignChangeEvent e) { if (e.isCancelled()) return; if (e.getPlayer() == null) return; Player p = e.getPlayer(); String line1 = e.getLine(0); Block block = e.getBlock(); String pack = e.getLine(1); // Permissions if (line1.equalsIgnoreCase("[" + SignMessage + "]") && !DonationPoints.permission.has(p, "donationpoints.sign.create")) { e.setCancelled(true); block.breakNaturally(); p.sendMessage(Commands.Prefix + Commands.noPermissionMessage); } else if (DonationPoints.permission.has(p, "donationpoints.sign.create") && line1.equalsIgnoreCase("[" + SignMessage + "]")) { if (block.getType() == Material.SIGN_POST) { p.sendMessage(Commands.Prefix + "�cDonationPoints signs must be placed on a wall."); block.breakNaturally(); e.setCancelled(true); } if (plugin.getConfig().getString("packages." + pack) == null) { e.setCancelled(true); p.sendMessage(Commands.Prefix + Commands.InvalidPackage); block.breakNaturally(); } if (e.getLine(1).isEmpty()) { e.setCancelled(true); p.sendMessage(Commands.Prefix + Commands.InvalidPackage); block.breakNaturally(); } else { if (plugin.getConfig().getBoolean("General.AutoFillSigns", true)) { Double price = plugin.getConfig().getDouble("packages." + pack + ".price"); e.setLine(2, (price + " Points")); } p.sendMessage(Commands.Prefix + "�cYou have created a DonationPoints sign."); } } } }
true
true
public void HangingEvent(HangingBreakByEntityEvent e) { Hanging broken = e.getEntity(); Entity remover = e.getRemover(); if (remover instanceof Player) { Player player = (Player) remover; if (broken instanceof ItemFrame) { Double x = broken.getLocation().getX(); Double y = broken.getLocation().getY(); Double z = broken.getLocation().getZ(); String world = broken.getWorld().getName(); if (PlayerListener.links.containsKey(player.getName())) { String packName = PlayerListener.links.get(player.getName()); if (Methods.isFrameLinked(x, y, z, world)) { player.sendMessage(Commands.Prefix + "�cThis item frame is already linked."); e.setCancelled(true); return; } Methods.linkFrame(packName, x, y, z, world); player.sendMessage(Commands.Prefix + "�cSuccessfully linked �3" + packName + "�3."); PlayerListener.links.remove(player.getName()); e.setCancelled(true); } else if (!PlayerListener.links.containsKey(player.getName())) { if (Methods.isFrameLinked(x, y, z, world)) { if (player.isSneaking()) { if (!DonationPoints.permission.has(player, "donationpoints.sign.break")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } if (DonationPoints.permission.has(player, "donationpoints.sign.break")) { Methods.unlinkFrame(x, y, z, world); player.sendMessage(Commands.Prefix + "�cItem Frame unlinked."); e.setCancelled(false); return; } } e.setCancelled(true); String packName = Methods.getLinkedPackage(x, y, z, world); Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String packDesc = plugin.getConfig().getString("packages." + packName + ".description"); if (!DonationPoints.permission.has(player, "donationpoints.sign.use")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); return; } if (DonationPoints.permission.has(player, "donationpoints.free")) { price = 0.0; } if (plugin.getConfig().getBoolean("General.SpecificPermissions", true)) { if (!DonationPoints.permission.has(player, "donationpoints.sign.use." + packName)) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); } if (!plugin.getConfig().getBoolean("General.SpecificPermissions")) { player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); return; } } } } } }
public void HangingEvent(HangingBreakByEntityEvent e) { Hanging broken = e.getEntity(); Entity remover = e.getRemover(); if (remover instanceof Player) { Player player = (Player) remover; if (broken instanceof ItemFrame) { Double x = broken.getLocation().getX(); Double y = broken.getLocation().getY(); Double z = broken.getLocation().getZ(); String world = broken.getWorld().getName(); if (PlayerListener.links.containsKey(player.getName())) { String packName = PlayerListener.links.get(player.getName()); if (Methods.isFrameLinked(x, y, z, world)) { player.sendMessage(Commands.Prefix + "�cThis item frame is already linked."); PlayerListener.links.remove(player.getName()); e.setCancelled(true); return; } Methods.linkFrame(packName, x, y, z, world); player.sendMessage(Commands.Prefix + "�cSuccessfully linked �3" + packName + "�3."); PlayerListener.links.remove(player.getName()); e.setCancelled(true); } else if (!PlayerListener.links.containsKey(player.getName())) { if (Methods.isFrameLinked(x, y, z, world)) { if (player.isSneaking()) { if (!DonationPoints.permission.has(player, "donationpoints.sign.break")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } if (DonationPoints.permission.has(player, "donationpoints.sign.break")) { Methods.unlinkFrame(x, y, z, world); player.sendMessage(Commands.Prefix + "�cItem Frame unlinked."); e.setCancelled(false); return; } } e.setCancelled(true); String packName = Methods.getLinkedPackage(x, y, z, world); Double price = plugin.getConfig().getDouble("packages." + packName + ".price"); String packDesc = plugin.getConfig().getString("packages." + packName + ".description"); if (!DonationPoints.permission.has(player, "donationpoints.sign.use")) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); return; } if (DonationPoints.permission.has(player, "donationpoints.free")) { price = 0.0; } if (plugin.getConfig().getBoolean("General.SpecificPermissions", true)) { if (!DonationPoints.permission.has(player, "donationpoints.sign.use." + packName)) { player.sendMessage(Commands.Prefix + Commands.noPermissionMessage); e.setCancelled(true); return; } player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); } if (!plugin.getConfig().getBoolean("General.SpecificPermissions")) { player.sendMessage(Commands.Prefix + "�cRight Clicking this sign will allow you to purchase �3" + packName + "�c for �3" + price + "�c."); player.sendMessage(Commands.Prefix + "�cDescription: �3" + packDesc); return; } } } } } }
diff --git a/src/java/com/tracker/backend/webinterface/TorrentUpload.java b/src/java/com/tracker/backend/webinterface/TorrentUpload.java index 21ba455..ac48237 100644 --- a/src/java/com/tracker/backend/webinterface/TorrentUpload.java +++ b/src/java/com/tracker/backend/webinterface/TorrentUpload.java @@ -1,422 +1,422 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.tracker.backend.webinterface; import com.tracker.backend.Bencode; import com.tracker.backend.StringUtils; import com.tracker.backend.entity.Torrent; import com.tracker.backend.webinterface.entity.TorrentContent; import com.tracker.backend.webinterface.entity.TorrentData; import com.tracker.backend.webinterface.entity.TorrentFile; import java.io.InputStream; import java.security.MessageDigest; import java.util.Calendar; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; /** * Responsible for adding torrents. * <p>May have to rewrite the torrentfile to accommodate for things like wrong * announce or the private flag being set. In these cases, the user should be * told to redownload the torrentfile before {s,}he starts seeding.</p> * <p>This class does not do any thorough validation of the torrentfile, beyond * some simple checks to see if some of the necessary data is there.</p> * <p>This class requires the Apache Commons FileUpload package.</p> * @author bo */ public class TorrentUpload { static Logger log = Logger.getLogger(TorrentUpload.class.getName()); static EntityManagerFactory emf = Persistence.createEntityManagerFactory("TorrentTrackerPU"); /** * A simple convenience class to make it easier to parse the Servlet request. */ public class UnparsedTorrentData { public String name; public String description; public InputStream stream; } /** * A convenience method to separate out the interesting information from * a HttpServletRequest. * @param request the HttpServletRequest to parse the information from. * The information sought is "torrentName", "torrentDescription" and the * torrent file itself. * @return a UnparsedTorrentData object containing the information parsed * from the given request. * @throws java.lang.Exception if the request is not a multipart request. */ public UnparsedTorrentData getDataFromRequest(HttpServletRequest request) throws Exception { if(!ServletFileUpload.isMultipartContent(request)) { log.log(Level.SEVERE, "Request received by getDataFromRequest() not a multi-part request?"); throw new Exception("Request not multi-part?"); } UnparsedTorrentData data = new UnparsedTorrentData(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator itr = upload.getItemIterator(request); // set the maximum size of the torrentfile, avoid loading hundreds of // megs into memory. A size limit of 10MB seems decent enough (the // biggest .torrent files I could find through some quick searching were // just below 2MB. // TODO: read from config? upload.setFileSizeMax(10485760L); while(itr.hasNext()) { FileItemStream item = itr.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); // is it the name or description? if(item.isFormField()) { if(name.equalsIgnoreCase("torrentName")) { // grab content of field data.name = Streams.asString(stream); } else if(name.equalsIgnoreCase("torrentDescription")) { data.description = Streams.asString(stream); } // some weird data? else { log.log(Level.INFO, "Unknown field (" + name + ") in upload request?"); } } // file field else { data.stream = stream; } } return data; } /** * Reads a torrent given in the request, makes changes if necessary, then * adds it to the database of tracked torrents. * @param torrent the input stream to read the torrent from. * @param torrentDescription the torrent description to persist in the database. * @param torrentName the torrent name to persist in the database. * @param contextPath the context path of the running servlet. Used for * checking the announce keys in the torrent file. * @return a TreeMap populated with the result of the operation, plus * eventual warnings or error messages. * <p>The keys this may contain is: * <ul> * <li><b>"warning reason"</b>: a human readable string describing a warning * encountered while adding the torrentfile (wrong announce for example). * This is left empty if there is no warning given.</li> * <li><b>"error reason"</b>: a human readable description of why this torrent * could not be added to the database. This is left empty if there is no * errors.</li> * <li><b>"redownload"</b>: equals to "true" if the client needs to redownload * the torrentfile before {s,}he can begin seeding the torrent (for example * if the torrentfile had an incorrect announce URL, and was changed). * Equals to "false" if there is no reason to redownload the torrentfile.</li> * </ul> * @throws java.lang.Exception if there is some problem with the given * torrentfile or the persisting operation. */ public static TreeMap<String,String> addTorrent(InputStream torrent, String torrentName, String torrentDescription, String contextPath) throws Exception { Long torrentLength = new Long(0L); Torrent t; TorrentData tData; TorrentFile tFile; // list of files and their lengths Vector<TorrentContent> torrentFiles = new Vector<TorrentContent>(); // the URL of this trackers announce, used for comparison with the // URL given in the torrentfile. String ourAnnounce = contextPath + "/Announce"; TreeMap<String,String> response = new TreeMap<String,String>(); // set some default replies response.put("warning reason", ""); response.put("error reason", ""); response.put("redownload", "false"); Map decodedTorrent; // set as null to avoid some nonsense when persisting, will be set // by the decoded torrent Map infoDictionary = null; // for generating the info_hash MessageDigest md = MessageDigest.getInstance("SHA-1"); // process the input stream try { /* * The torrent file layout is roughly like this: * Mandatory: * String announce (the URL of the tracker) * Dictionary info (describes the files of the torrent) * Mandatory: * Integer piece length (number of bytes in each piece) * String pieces (the SHA1 hashes of all the pieces) * * Optional: * Integer private (determines if the torrent is private) * * If this is a single-file torrent: * Mandatory: * String name (filename of the file) * Integer length (length of the file in bytes) * Optional: * String md5sum (MD5 sum of the file) * * If this is a multiple-file torrent: * Mandatory: * String name (the name of the directory to store the files in) * List of Dictionaries files (one for each file) * Mandatory: * Integer length (length of the file in bytes) * List path (a list of strings giving the path of the file) * Optional: * String md5sum (MD5 sum of the file) * end of files * end of info * Optional: * List announce-list (list of list of trackers) * Integer creation date (the creation time of the torrent) * String comment (a comment to the torrent) * String created-by (gives the program used to create the torrent) * * The info hash used when tracking is the SHA1 hash of the * _value_ of the info key, in other words, a bencoded * dictionary. * * see: http://wiki.theory.org/BitTorrentSpecification * for more information and links on optional keys like the * announce-list. */ decodedTorrent = (Map) Bencode.decode(torrent).get(0); String announceURL; // make sure that the torrentfile contains a bare minimum // of data. if(!decodedTorrent.containsKey("announce") || !decodedTorrent.containsKey("info")) { log.log(Level.WARNING, "Malformed torrentfile received." + "Missing 'announce' or 'info' keys."); throw new Exception("The Torrentfile given in upload is malformed."); } // make sure that we are the ones that track this torrent. announceURL = (String) decodedTorrent.get((String)"announce"); if(!announceURL.equalsIgnoreCase(ourAnnounce) || decodedTorrent.containsKey("announce-list")) { // check for the optional announce-list, if we are not // given there either, or if this is not set, issue a // warning and change the torrentfile. if(!decodedTorrent.containsKey("announce-list")) { // rewrite the standard announce key log.log(Level.WARNING, "Uploaded torrent does not have" + "our announce (given was: " + announceURL + ")."); decodedTorrent.put("announce", ourAnnounce); // TODO: apply i10n here - response.put("warning reason", "The torrentfile did" + - "not contain the correct announce URL, this" + + response.put("warning reason", "The torrentfile did " + + "not contain the correct announce URL, this " + "has been changed.\n"); response.put("redownload", "true"); } // announce-list found. Makes the "announce" key // irrelevant. See this for more info: // http://home.elp.rr.com/tur/multitracker-spec.txt else { // does it contain our announce string? boolean valid = false; // grab the announce-list and check every element // for our announce URL. Vector<Vector<String> > announceList = (Vector<Vector<String> >) decodedTorrent.get("announce-list"); Iterator announceListItr = announceList.iterator(); while(announceListItr.hasNext()) { Vector<String> innerList = (Vector<String>) announceListItr.next(); Iterator innerItr = innerList.iterator(); while(innerItr.hasNext()) { String announce = (String) innerItr.next(); if(announce.equalsIgnoreCase(ourAnnounce)) { valid = true; break; } } if(valid) break; } if(!valid) { - log.log(Level.WARNING, "Uploaded torrent does not" + - "have our announce in announce-list (given" + + log.log(Level.WARNING, "Uploaded torrent does not " + + "have our announce in announce-list (given " + "was: " + announceList.toString() +")."); // add our announce URL to the top of the list Vector<String> prependedAnnounce = new Vector<String>(); prependedAnnounce.add(ourAnnounce); announceList.add(0, prependedAnnounce); // TODO: apply i10n - response.put("warning reason", "The torrentfile" + - "did not contain the correct announce URL" + + response.put("warning reason", "The torrentfile " + + "did not contain the correct announce URL " + "in it's announce list. This has been changed.\n"); response.put("redownload", "true"); } } } // if wrong announce or announce-list // check for the private setting infoDictionary = (Map) decodedTorrent.get("info"); if(infoDictionary.containsKey("private")) { Long privateField = (Long) infoDictionary.get("private"); // is private enabled? if(privateField == 1) { // remove the private key and set appropriate warnings infoDictionary.remove("private"); log.log(Level.WARNING, "Torrent uploaded with private" + "key enabled."); String warningReason = response.get("warning reason"); warningReason += "The torrentfile was set as private, " + "this has been removed."; response.put("warning reason", warningReason); response.put("redownload", "true"); } } // set the torrentlength // this is different if this is a single-file torrent or a // multi-file torrent. Test for both. // multi-file torrent - see diagram above if(infoDictionary.containsKey("files")) { Vector<Map> files = (Vector<Map>) infoDictionary.get((String)"files"); Iterator fileItr = files.iterator(); while(fileItr.hasNext()) { Map f = (Map) fileItr.next(); // grab length Long length = (Long) f.get((String)"length"); torrentLength += length; // grab path Vector<String> filePath = (Vector<String>) f.get((String)"path"); Iterator pathItr = filePath.iterator(); String path = (String) infoDictionary.get((String)"name"); // build up the path while(pathItr.hasNext()) { path += "/"; path += pathItr.next(); } TorrentContent c = new TorrentContent(); c.setFileName(path); c.setFileSize(length); // populate the list torrentFiles.add(c); } } // single file torrent - see diagram above else { String name = (String) infoDictionary.get((String)"name"); Long length = (Long) infoDictionary.get((String)"length"); torrentLength = length; TorrentContent c = new TorrentContent(); c.setFileName(name); c.setFileSize(length); // populate the list torrentFiles.add(c); } } catch(Exception ex) { log.log(Level.WARNING, "Error when decoding given torrent.", ex); throw new Exception("Error when decoding torrent given in upload", ex); } // persist! // add the torrent to the database. EntityManager em = emf.createEntityManager(); try { t = new Torrent(); tData = new TorrentData(); tFile = new TorrentFile(); // grab the SHA1 hash of the (bencoded) info dictionary. // the simplest way is to simply encode the info dictionary again // (things may have changed), then do a SHA1-hash of the result. String info = Bencode.encode(infoDictionary); byte[] rawInfo = new byte[info.length()]; byte[] rawInfoHash = new byte[20]; for (int i = 0; i < rawInfo.length; i++) { rawInfo[i] = (byte) info.charAt(i); } md.update(rawInfo); rawInfoHash = md.digest(); // set the info hash. t.setInfoHash(StringUtils.getHexString(rawInfoHash)); // num seeders and all that is set by the Torrent constructor. tData.setName(torrentName); tData.setDescription(torrentDescription); tData.setAdded(Calendar.getInstance().getTime()); tData.setTorrentSize(torrentLength); tData.setTorrentContent(torrentFiles); t.setTorrentData(tData); // set the torrentfile String bencodedTorrent = Bencode.encode(decodedTorrent); tFile.setTorrentFile(bencodedTorrent); t.setTorrentFile(tFile); // persist this em.getTransaction().begin(); em.persist(t); // torrentData, torrentFile and torrentContent is automatically // persisted through the Cascade operations specified in the // entity classes. em.getTransaction().commit(); } catch(Exception ex) { if(em.getTransaction().isActive()) { em.getTransaction().rollback(); } log.log(Level.WARNING, "Error when persisting the uploaded torrent.", ex); throw new Exception("Error when persising torrent given in upload", ex); } finally { em.close(); } return response; } }
false
true
public static TreeMap<String,String> addTorrent(InputStream torrent, String torrentName, String torrentDescription, String contextPath) throws Exception { Long torrentLength = new Long(0L); Torrent t; TorrentData tData; TorrentFile tFile; // list of files and their lengths Vector<TorrentContent> torrentFiles = new Vector<TorrentContent>(); // the URL of this trackers announce, used for comparison with the // URL given in the torrentfile. String ourAnnounce = contextPath + "/Announce"; TreeMap<String,String> response = new TreeMap<String,String>(); // set some default replies response.put("warning reason", ""); response.put("error reason", ""); response.put("redownload", "false"); Map decodedTorrent; // set as null to avoid some nonsense when persisting, will be set // by the decoded torrent Map infoDictionary = null; // for generating the info_hash MessageDigest md = MessageDigest.getInstance("SHA-1"); // process the input stream try { /* * The torrent file layout is roughly like this: * Mandatory: * String announce (the URL of the tracker) * Dictionary info (describes the files of the torrent) * Mandatory: * Integer piece length (number of bytes in each piece) * String pieces (the SHA1 hashes of all the pieces) * * Optional: * Integer private (determines if the torrent is private) * * If this is a single-file torrent: * Mandatory: * String name (filename of the file) * Integer length (length of the file in bytes) * Optional: * String md5sum (MD5 sum of the file) * * If this is a multiple-file torrent: * Mandatory: * String name (the name of the directory to store the files in) * List of Dictionaries files (one for each file) * Mandatory: * Integer length (length of the file in bytes) * List path (a list of strings giving the path of the file) * Optional: * String md5sum (MD5 sum of the file) * end of files * end of info * Optional: * List announce-list (list of list of trackers) * Integer creation date (the creation time of the torrent) * String comment (a comment to the torrent) * String created-by (gives the program used to create the torrent) * * The info hash used when tracking is the SHA1 hash of the * _value_ of the info key, in other words, a bencoded * dictionary. * * see: http://wiki.theory.org/BitTorrentSpecification * for more information and links on optional keys like the * announce-list. */ decodedTorrent = (Map) Bencode.decode(torrent).get(0); String announceURL; // make sure that the torrentfile contains a bare minimum // of data. if(!decodedTorrent.containsKey("announce") || !decodedTorrent.containsKey("info")) { log.log(Level.WARNING, "Malformed torrentfile received." + "Missing 'announce' or 'info' keys."); throw new Exception("The Torrentfile given in upload is malformed."); } // make sure that we are the ones that track this torrent. announceURL = (String) decodedTorrent.get((String)"announce"); if(!announceURL.equalsIgnoreCase(ourAnnounce) || decodedTorrent.containsKey("announce-list")) { // check for the optional announce-list, if we are not // given there either, or if this is not set, issue a // warning and change the torrentfile. if(!decodedTorrent.containsKey("announce-list")) { // rewrite the standard announce key log.log(Level.WARNING, "Uploaded torrent does not have" + "our announce (given was: " + announceURL + ")."); decodedTorrent.put("announce", ourAnnounce); // TODO: apply i10n here response.put("warning reason", "The torrentfile did" + "not contain the correct announce URL, this" + "has been changed.\n"); response.put("redownload", "true"); } // announce-list found. Makes the "announce" key // irrelevant. See this for more info: // http://home.elp.rr.com/tur/multitracker-spec.txt else { // does it contain our announce string? boolean valid = false; // grab the announce-list and check every element // for our announce URL. Vector<Vector<String> > announceList = (Vector<Vector<String> >) decodedTorrent.get("announce-list"); Iterator announceListItr = announceList.iterator(); while(announceListItr.hasNext()) { Vector<String> innerList = (Vector<String>) announceListItr.next(); Iterator innerItr = innerList.iterator(); while(innerItr.hasNext()) { String announce = (String) innerItr.next(); if(announce.equalsIgnoreCase(ourAnnounce)) { valid = true; break; } } if(valid) break; } if(!valid) { log.log(Level.WARNING, "Uploaded torrent does not" + "have our announce in announce-list (given" + "was: " + announceList.toString() +")."); // add our announce URL to the top of the list Vector<String> prependedAnnounce = new Vector<String>(); prependedAnnounce.add(ourAnnounce); announceList.add(0, prependedAnnounce); // TODO: apply i10n response.put("warning reason", "The torrentfile" + "did not contain the correct announce URL" + "in it's announce list. This has been changed.\n"); response.put("redownload", "true"); } } } // if wrong announce or announce-list // check for the private setting infoDictionary = (Map) decodedTorrent.get("info"); if(infoDictionary.containsKey("private")) { Long privateField = (Long) infoDictionary.get("private"); // is private enabled? if(privateField == 1) { // remove the private key and set appropriate warnings infoDictionary.remove("private"); log.log(Level.WARNING, "Torrent uploaded with private" + "key enabled."); String warningReason = response.get("warning reason"); warningReason += "The torrentfile was set as private, " + "this has been removed."; response.put("warning reason", warningReason); response.put("redownload", "true"); } } // set the torrentlength // this is different if this is a single-file torrent or a // multi-file torrent. Test for both. // multi-file torrent - see diagram above if(infoDictionary.containsKey("files")) { Vector<Map> files = (Vector<Map>) infoDictionary.get((String)"files"); Iterator fileItr = files.iterator(); while(fileItr.hasNext()) { Map f = (Map) fileItr.next(); // grab length Long length = (Long) f.get((String)"length"); torrentLength += length; // grab path Vector<String> filePath = (Vector<String>) f.get((String)"path"); Iterator pathItr = filePath.iterator(); String path = (String) infoDictionary.get((String)"name"); // build up the path while(pathItr.hasNext()) { path += "/"; path += pathItr.next(); } TorrentContent c = new TorrentContent(); c.setFileName(path); c.setFileSize(length); // populate the list torrentFiles.add(c); } } // single file torrent - see diagram above else { String name = (String) infoDictionary.get((String)"name"); Long length = (Long) infoDictionary.get((String)"length"); torrentLength = length; TorrentContent c = new TorrentContent(); c.setFileName(name); c.setFileSize(length); // populate the list torrentFiles.add(c); } } catch(Exception ex) { log.log(Level.WARNING, "Error when decoding given torrent.", ex); throw new Exception("Error when decoding torrent given in upload", ex); } // persist! // add the torrent to the database. EntityManager em = emf.createEntityManager(); try { t = new Torrent(); tData = new TorrentData(); tFile = new TorrentFile(); // grab the SHA1 hash of the (bencoded) info dictionary. // the simplest way is to simply encode the info dictionary again // (things may have changed), then do a SHA1-hash of the result. String info = Bencode.encode(infoDictionary); byte[] rawInfo = new byte[info.length()]; byte[] rawInfoHash = new byte[20]; for (int i = 0; i < rawInfo.length; i++) { rawInfo[i] = (byte) info.charAt(i); } md.update(rawInfo); rawInfoHash = md.digest(); // set the info hash. t.setInfoHash(StringUtils.getHexString(rawInfoHash)); // num seeders and all that is set by the Torrent constructor. tData.setName(torrentName); tData.setDescription(torrentDescription); tData.setAdded(Calendar.getInstance().getTime()); tData.setTorrentSize(torrentLength); tData.setTorrentContent(torrentFiles); t.setTorrentData(tData); // set the torrentfile String bencodedTorrent = Bencode.encode(decodedTorrent); tFile.setTorrentFile(bencodedTorrent); t.setTorrentFile(tFile); // persist this em.getTransaction().begin(); em.persist(t); // torrentData, torrentFile and torrentContent is automatically // persisted through the Cascade operations specified in the // entity classes. em.getTransaction().commit(); } catch(Exception ex) { if(em.getTransaction().isActive()) { em.getTransaction().rollback(); } log.log(Level.WARNING, "Error when persisting the uploaded torrent.", ex); throw new Exception("Error when persising torrent given in upload", ex); } finally { em.close(); } return response; }
public static TreeMap<String,String> addTorrent(InputStream torrent, String torrentName, String torrentDescription, String contextPath) throws Exception { Long torrentLength = new Long(0L); Torrent t; TorrentData tData; TorrentFile tFile; // list of files and their lengths Vector<TorrentContent> torrentFiles = new Vector<TorrentContent>(); // the URL of this trackers announce, used for comparison with the // URL given in the torrentfile. String ourAnnounce = contextPath + "/Announce"; TreeMap<String,String> response = new TreeMap<String,String>(); // set some default replies response.put("warning reason", ""); response.put("error reason", ""); response.put("redownload", "false"); Map decodedTorrent; // set as null to avoid some nonsense when persisting, will be set // by the decoded torrent Map infoDictionary = null; // for generating the info_hash MessageDigest md = MessageDigest.getInstance("SHA-1"); // process the input stream try { /* * The torrent file layout is roughly like this: * Mandatory: * String announce (the URL of the tracker) * Dictionary info (describes the files of the torrent) * Mandatory: * Integer piece length (number of bytes in each piece) * String pieces (the SHA1 hashes of all the pieces) * * Optional: * Integer private (determines if the torrent is private) * * If this is a single-file torrent: * Mandatory: * String name (filename of the file) * Integer length (length of the file in bytes) * Optional: * String md5sum (MD5 sum of the file) * * If this is a multiple-file torrent: * Mandatory: * String name (the name of the directory to store the files in) * List of Dictionaries files (one for each file) * Mandatory: * Integer length (length of the file in bytes) * List path (a list of strings giving the path of the file) * Optional: * String md5sum (MD5 sum of the file) * end of files * end of info * Optional: * List announce-list (list of list of trackers) * Integer creation date (the creation time of the torrent) * String comment (a comment to the torrent) * String created-by (gives the program used to create the torrent) * * The info hash used when tracking is the SHA1 hash of the * _value_ of the info key, in other words, a bencoded * dictionary. * * see: http://wiki.theory.org/BitTorrentSpecification * for more information and links on optional keys like the * announce-list. */ decodedTorrent = (Map) Bencode.decode(torrent).get(0); String announceURL; // make sure that the torrentfile contains a bare minimum // of data. if(!decodedTorrent.containsKey("announce") || !decodedTorrent.containsKey("info")) { log.log(Level.WARNING, "Malformed torrentfile received." + "Missing 'announce' or 'info' keys."); throw new Exception("The Torrentfile given in upload is malformed."); } // make sure that we are the ones that track this torrent. announceURL = (String) decodedTorrent.get((String)"announce"); if(!announceURL.equalsIgnoreCase(ourAnnounce) || decodedTorrent.containsKey("announce-list")) { // check for the optional announce-list, if we are not // given there either, or if this is not set, issue a // warning and change the torrentfile. if(!decodedTorrent.containsKey("announce-list")) { // rewrite the standard announce key log.log(Level.WARNING, "Uploaded torrent does not have" + "our announce (given was: " + announceURL + ")."); decodedTorrent.put("announce", ourAnnounce); // TODO: apply i10n here response.put("warning reason", "The torrentfile did " + "not contain the correct announce URL, this " + "has been changed.\n"); response.put("redownload", "true"); } // announce-list found. Makes the "announce" key // irrelevant. See this for more info: // http://home.elp.rr.com/tur/multitracker-spec.txt else { // does it contain our announce string? boolean valid = false; // grab the announce-list and check every element // for our announce URL. Vector<Vector<String> > announceList = (Vector<Vector<String> >) decodedTorrent.get("announce-list"); Iterator announceListItr = announceList.iterator(); while(announceListItr.hasNext()) { Vector<String> innerList = (Vector<String>) announceListItr.next(); Iterator innerItr = innerList.iterator(); while(innerItr.hasNext()) { String announce = (String) innerItr.next(); if(announce.equalsIgnoreCase(ourAnnounce)) { valid = true; break; } } if(valid) break; } if(!valid) { log.log(Level.WARNING, "Uploaded torrent does not " + "have our announce in announce-list (given " + "was: " + announceList.toString() +")."); // add our announce URL to the top of the list Vector<String> prependedAnnounce = new Vector<String>(); prependedAnnounce.add(ourAnnounce); announceList.add(0, prependedAnnounce); // TODO: apply i10n response.put("warning reason", "The torrentfile " + "did not contain the correct announce URL " + "in it's announce list. This has been changed.\n"); response.put("redownload", "true"); } } } // if wrong announce or announce-list // check for the private setting infoDictionary = (Map) decodedTorrent.get("info"); if(infoDictionary.containsKey("private")) { Long privateField = (Long) infoDictionary.get("private"); // is private enabled? if(privateField == 1) { // remove the private key and set appropriate warnings infoDictionary.remove("private"); log.log(Level.WARNING, "Torrent uploaded with private" + "key enabled."); String warningReason = response.get("warning reason"); warningReason += "The torrentfile was set as private, " + "this has been removed."; response.put("warning reason", warningReason); response.put("redownload", "true"); } } // set the torrentlength // this is different if this is a single-file torrent or a // multi-file torrent. Test for both. // multi-file torrent - see diagram above if(infoDictionary.containsKey("files")) { Vector<Map> files = (Vector<Map>) infoDictionary.get((String)"files"); Iterator fileItr = files.iterator(); while(fileItr.hasNext()) { Map f = (Map) fileItr.next(); // grab length Long length = (Long) f.get((String)"length"); torrentLength += length; // grab path Vector<String> filePath = (Vector<String>) f.get((String)"path"); Iterator pathItr = filePath.iterator(); String path = (String) infoDictionary.get((String)"name"); // build up the path while(pathItr.hasNext()) { path += "/"; path += pathItr.next(); } TorrentContent c = new TorrentContent(); c.setFileName(path); c.setFileSize(length); // populate the list torrentFiles.add(c); } } // single file torrent - see diagram above else { String name = (String) infoDictionary.get((String)"name"); Long length = (Long) infoDictionary.get((String)"length"); torrentLength = length; TorrentContent c = new TorrentContent(); c.setFileName(name); c.setFileSize(length); // populate the list torrentFiles.add(c); } } catch(Exception ex) { log.log(Level.WARNING, "Error when decoding given torrent.", ex); throw new Exception("Error when decoding torrent given in upload", ex); } // persist! // add the torrent to the database. EntityManager em = emf.createEntityManager(); try { t = new Torrent(); tData = new TorrentData(); tFile = new TorrentFile(); // grab the SHA1 hash of the (bencoded) info dictionary. // the simplest way is to simply encode the info dictionary again // (things may have changed), then do a SHA1-hash of the result. String info = Bencode.encode(infoDictionary); byte[] rawInfo = new byte[info.length()]; byte[] rawInfoHash = new byte[20]; for (int i = 0; i < rawInfo.length; i++) { rawInfo[i] = (byte) info.charAt(i); } md.update(rawInfo); rawInfoHash = md.digest(); // set the info hash. t.setInfoHash(StringUtils.getHexString(rawInfoHash)); // num seeders and all that is set by the Torrent constructor. tData.setName(torrentName); tData.setDescription(torrentDescription); tData.setAdded(Calendar.getInstance().getTime()); tData.setTorrentSize(torrentLength); tData.setTorrentContent(torrentFiles); t.setTorrentData(tData); // set the torrentfile String bencodedTorrent = Bencode.encode(decodedTorrent); tFile.setTorrentFile(bencodedTorrent); t.setTorrentFile(tFile); // persist this em.getTransaction().begin(); em.persist(t); // torrentData, torrentFile and torrentContent is automatically // persisted through the Cascade operations specified in the // entity classes. em.getTransaction().commit(); } catch(Exception ex) { if(em.getTransaction().isActive()) { em.getTransaction().rollback(); } log.log(Level.WARNING, "Error when persisting the uploaded torrent.", ex); throw new Exception("Error when persising torrent given in upload", ex); } finally { em.close(); } return response; }
diff --git a/xwiki-rendering-syntaxes/xwiki-rendering-syntax-markdown/src/main/java/org/xwiki/rendering/internal/parser/markdown/AbstractLinkAndImagePegdownVisitor.java b/xwiki-rendering-syntaxes/xwiki-rendering-syntax-markdown/src/main/java/org/xwiki/rendering/internal/parser/markdown/AbstractLinkAndImagePegdownVisitor.java index 9cb5702a1..7cf762fc0 100644 --- a/xwiki-rendering-syntaxes/xwiki-rendering-syntax-markdown/src/main/java/org/xwiki/rendering/internal/parser/markdown/AbstractLinkAndImagePegdownVisitor.java +++ b/xwiki-rendering-syntaxes/xwiki-rendering-syntax-markdown/src/main/java/org/xwiki/rendering/internal/parser/markdown/AbstractLinkAndImagePegdownVisitor.java @@ -1,221 +1,227 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.internal.parser.markdown; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.lang3.StringUtils; import org.pegdown.ast.AutoLinkNode; import org.pegdown.ast.ExpImageNode; import org.pegdown.ast.ExpLinkNode; import org.pegdown.ast.MailLinkNode; import org.pegdown.ast.RefImageNode; import org.pegdown.ast.RefLinkNode; import org.pegdown.ast.ReferenceNode; import org.pegdown.ast.WikiLinkNode; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.rendering.listener.reference.ResourceReference; import org.xwiki.rendering.parser.ResourceReferenceParser; import org.xwiki.rendering.renderer.reference.link.URILabelGenerator; /** * Implements Pegdown Visitor's link and image events. * * @version $Id$ * @since 4.5M1 */ public abstract class AbstractLinkAndImagePegdownVisitor extends AbstractHTMLPegdownVisitor { /** * HTML title attribute. */ private static final String TITLE_ATTRIBUTE = "title"; /** * We parse link references with the default reference parser (i.e. the same one used by XWiki Syntax 2.1). */ @Inject @Named("link") private ResourceReferenceParser linkResourceReferenceParser; /** * We parse image references with the default reference parser (i.e. the same one used by XWiki Syntax 2.1). */ @Inject @Named("image") private ResourceReferenceParser imageResourceReferenceParser; /** * Used to find out at runtime a link label generator matching the link reference type. */ @Inject private ComponentManager componentManager; /** * Link References. * @see #visit(org.pegdown.ast.ReferenceNode) */ private Map<String, ReferenceNode> references = new HashMap<String, ReferenceNode>(); @Override public void visit(AutoLinkNode autoLinkNode) { ResourceReference reference = this.linkResourceReferenceParser.parse(autoLinkNode.getText()); getListener().beginLink(reference, true, Collections.EMPTY_MAP); getListener().endLink(reference, true, Collections.EMPTY_MAP); } @Override public void visit(ExpImageNode expImageNode) { ResourceReference reference = this.imageResourceReferenceParser.parse(expImageNode.url); Map<String, String> parameters = new HashMap<String, String>(); // Handle alt text. Note that in order to have the same behavior as the XWiki Syntax 2.0+ we don't add the alt // parameter if its content is the same as the one that would be automatically generated by the XHTML Renderer. String computedAltValue = computeAltAttributeValue(reference); String extractedAltValue = extractText(expImageNode); if (StringUtils.isNotEmpty(extractedAltValue) && !extractedAltValue.equals(computedAltValue)) { parameters.put("alt", extractedAltValue); } // Handle optional title addTitle(parameters, expImageNode.title); getListener().onImage(reference, false, parameters); } /** * @param reference the reference for which to compute the alt attribute value * @return the alt attribute value that would get generated if not specified by the user */ private String computeAltAttributeValue(ResourceReference reference) { String label; try { URILabelGenerator uriLabelGenerator = this.componentManager.getInstance(URILabelGenerator.class, reference.getType().getScheme()); label = uriLabelGenerator.generateLabel(reference); } catch (ComponentLookupException e) { label = reference.getReference(); } return label; } @Override public void visit(ExpLinkNode expLinkNode) { ResourceReference reference = this.linkResourceReferenceParser.parse(expLinkNode.url); Map<String, String> parameters = new HashMap<String, String>(); // Handle optional title addTitle(parameters, expLinkNode.title); getListener().beginLink(reference, false, parameters); visitChildren(expLinkNode); getListener().endLink(reference, false, parameters); } /** * Add a title parameter. * * @param parameters the map to which to add the title parameter * @param title the title parameter value to add */ private void addTitle(Map<String, String> parameters, String title) { if (StringUtils.isNotEmpty(title)) { parameters.put(TITLE_ATTRIBUTE, title); } } @Override public void visit(MailLinkNode mailLinkNode) { ResourceReference reference = this.linkResourceReferenceParser.parse( "mailto:" + mailLinkNode.getText()); getListener().beginLink(reference, true, Collections.EMPTY_MAP); getListener().endLink(reference, true, Collections.EMPTY_MAP); } @Override public void visit(ReferenceNode referenceNode) { // Since XWiki doesn't support reference links, we store reference definitions and memory and when a reference // is used we generate a standard link. this.references.put(extractText(referenceNode), referenceNode); } @Override public void visit(RefImageNode refImageNode) { // Since XWiki doesn't support reference images, we generate a standard image instead String label = extractText(refImageNode.referenceKey); ReferenceNode referenceNode = this.references.get(label); if (referenceNode != null) { ResourceReference reference = this.imageResourceReferenceParser.parse(referenceNode.getUrl()); // Handle an optional link title Map<String, String> parameters = Collections.EMPTY_MAP; if (StringUtils.isNotEmpty(referenceNode.getTitle())) { parameters = Collections.singletonMap(TITLE_ATTRIBUTE, referenceNode.getTitle()); } getListener().onImage(reference, false, parameters); } } @Override public void visit(RefLinkNode refLinkNode) { // Since XWiki doesn't support reference links, we generate a standard link instead - String label = extractText(refLinkNode.referenceKey); + // If the reference key is null then the node content is considered to be the key! + String label; + if (refLinkNode.referenceKey == null) { + label = extractText(refLinkNode); + } else { + label = extractText(refLinkNode.referenceKey); + } ReferenceNode referenceNode = this.references.get(label); if (referenceNode != null) { ResourceReference reference = this.linkResourceReferenceParser.parse(referenceNode.getUrl()); // Handle an optional link title Map<String, String> parameters = Collections.EMPTY_MAP; if (StringUtils.isNotEmpty(referenceNode.getTitle())) { parameters = Collections.singletonMap(TITLE_ATTRIBUTE, referenceNode.getTitle()); } getListener().beginLink(reference, false, parameters); visitChildren(refLinkNode); getListener().endLink(reference, false, parameters); } } @Override public void visit(WikiLinkNode wikiLinkNode) { ResourceReference reference = this.linkResourceReferenceParser.parse(wikiLinkNode.getText()); getListener().beginLink(reference, false, Collections.EMPTY_MAP); getListener().endLink(reference, false, Collections.EMPTY_MAP); } }
true
true
public void visit(RefLinkNode refLinkNode) { // Since XWiki doesn't support reference links, we generate a standard link instead String label = extractText(refLinkNode.referenceKey); ReferenceNode referenceNode = this.references.get(label); if (referenceNode != null) { ResourceReference reference = this.linkResourceReferenceParser.parse(referenceNode.getUrl()); // Handle an optional link title Map<String, String> parameters = Collections.EMPTY_MAP; if (StringUtils.isNotEmpty(referenceNode.getTitle())) { parameters = Collections.singletonMap(TITLE_ATTRIBUTE, referenceNode.getTitle()); } getListener().beginLink(reference, false, parameters); visitChildren(refLinkNode); getListener().endLink(reference, false, parameters); } }
public void visit(RefLinkNode refLinkNode) { // Since XWiki doesn't support reference links, we generate a standard link instead // If the reference key is null then the node content is considered to be the key! String label; if (refLinkNode.referenceKey == null) { label = extractText(refLinkNode); } else { label = extractText(refLinkNode.referenceKey); } ReferenceNode referenceNode = this.references.get(label); if (referenceNode != null) { ResourceReference reference = this.linkResourceReferenceParser.parse(referenceNode.getUrl()); // Handle an optional link title Map<String, String> parameters = Collections.EMPTY_MAP; if (StringUtils.isNotEmpty(referenceNode.getTitle())) { parameters = Collections.singletonMap(TITLE_ATTRIBUTE, referenceNode.getTitle()); } getListener().beginLink(reference, false, parameters); visitChildren(refLinkNode); getListener().endLink(reference, false, parameters); } }
diff --git a/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java b/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java index 120b1c5..0a90676 100644 --- a/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java +++ b/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java @@ -1,42 +1,42 @@ package com.yoursway.utils.os; import java.io.File; import java.io.IOException; public class YsOSUtils { private static OSUtils os; private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); - if (os.equals("Mac OS X")) + if (osName.equals("Mac OS X")) os = new MacUtils(); - else if (os.equals("Windows NT")) + else if (osName.equals("Windows NT")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; } public static boolean isMacOSX() { return os().isMacOSX(); } public static boolean isWindowsNT() { return os().isWindowsNT(); } public static void setExecAttribute(File file) throws IOException { os().setExecAttribute(file); } public static String javaRelativePath() { return os().javaRelativePath(); } }
false
true
private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); if (os.equals("Mac OS X")) os = new MacUtils(); else if (os.equals("Windows NT")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; }
private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); if (osName.equals("Mac OS X")) os = new MacUtils(); else if (osName.equals("Windows NT")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; }
diff --git a/main/src/com/google/gridworks/commands/project/ImportProjectCommand.java b/main/src/com/google/gridworks/commands/project/ImportProjectCommand.java index 586b7c8e..93fe6ff2 100644 --- a/main/src/com/google/gridworks/commands/project/ImportProjectCommand.java +++ b/main/src/com/google/gridworks/commands/project/ImportProjectCommand.java @@ -1,135 +1,135 @@ package com.google.gridworks.commands.project; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gridworks.ProjectManager; import com.google.gridworks.ProjectMetadata; import com.google.gridworks.commands.Command; import com.google.gridworks.model.Project; import com.google.gridworks.util.ParsingUtilities; public class ImportProjectCommand extends Command { final static Logger logger = LoggerFactory.getLogger("import-project_command"); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProjectManager.singleton.setBusy(true); try { Properties options = ParsingUtilities.parseUrlParameters(request); long projectID = Project.generateID(); logger.info("Importing existing project using new ID {}", projectID); internalImport(request, options, projectID); ProjectManager.singleton.loadProjectMetadata(projectID); ProjectMetadata pm = ProjectManager.singleton.getProjectMetadata(projectID); if (pm != null) { if (options.containsKey("project-name")) { String projectName = options.getProperty("project-name"); if (projectName != null && projectName.length() > 0) { pm.setName(projectName); } } redirect(response, "/project?project=" + projectID); } else { - redirect(response, "/error.html?redirect=index.html&msg=" + + redirect(response, "/error.html?redirect=index&msg=" + ParsingUtilities.encode("Failed to import project") ); } } catch (Exception e) { e.printStackTrace(); } finally { ProjectManager.singleton.setBusy(false); } } protected void internalImport( HttpServletRequest request, Properties options, long projectID ) throws Exception { String url = null; ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName().toLowerCase(); InputStream stream = item.openStream(); if (item.isFormField()) { if (name.equals("url")) { url = Streams.asString(stream); } else { options.put(name, Streams.asString(stream)); } } else { String fileName = item.getName().toLowerCase(); try { ProjectManager.singleton.importProject(projectID, stream, !fileName.endsWith(".tar")); } finally { stream.close(); } } } if (url != null && url.length() > 0) { internalImportURL(request, options, projectID, url); } } protected void internalImportURL( HttpServletRequest request, Properties options, long projectID, String urlString ) throws Exception { URL url = new URL(urlString); URLConnection connection = null; try { connection = url.openConnection(); connection.setConnectTimeout(5000); connection.connect(); } catch (Exception e) { throw new Exception("Cannot connect to " + urlString, e); } InputStream inputStream = null; try { inputStream = connection.getInputStream(); } catch (Exception e) { throw new Exception("Cannot retrieve content from " + url, e); } try { ProjectManager.singleton.importProject(projectID, inputStream, !urlString.endsWith(".tar")); } finally { inputStream.close(); } } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProjectManager.singleton.setBusy(true); try { Properties options = ParsingUtilities.parseUrlParameters(request); long projectID = Project.generateID(); logger.info("Importing existing project using new ID {}", projectID); internalImport(request, options, projectID); ProjectManager.singleton.loadProjectMetadata(projectID); ProjectMetadata pm = ProjectManager.singleton.getProjectMetadata(projectID); if (pm != null) { if (options.containsKey("project-name")) { String projectName = options.getProperty("project-name"); if (projectName != null && projectName.length() > 0) { pm.setName(projectName); } } redirect(response, "/project?project=" + projectID); } else { redirect(response, "/error.html?redirect=index.html&msg=" + ParsingUtilities.encode("Failed to import project") ); } } catch (Exception e) { e.printStackTrace(); } finally { ProjectManager.singleton.setBusy(false); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProjectManager.singleton.setBusy(true); try { Properties options = ParsingUtilities.parseUrlParameters(request); long projectID = Project.generateID(); logger.info("Importing existing project using new ID {}", projectID); internalImport(request, options, projectID); ProjectManager.singleton.loadProjectMetadata(projectID); ProjectMetadata pm = ProjectManager.singleton.getProjectMetadata(projectID); if (pm != null) { if (options.containsKey("project-name")) { String projectName = options.getProperty("project-name"); if (projectName != null && projectName.length() > 0) { pm.setName(projectName); } } redirect(response, "/project?project=" + projectID); } else { redirect(response, "/error.html?redirect=index&msg=" + ParsingUtilities.encode("Failed to import project") ); } } catch (Exception e) { e.printStackTrace(); } finally { ProjectManager.singleton.setBusy(false); } }
diff --git a/SHMail.java b/SHMail.java index 7d1bfa6..d47ef12 100644 --- a/SHMail.java +++ b/SHMail.java @@ -1,235 +1,236 @@ /* SHMail.java - sends and gets mail * Copyright (C) 1999 Fredrik Ehnbom * * 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.gjt.fredde.yamm; import java.io.*; import java.util.Properties; import java.util.ResourceBundle; import javax.swing.JButton; import javax.swing.JFrame; import org.gjt.fredde.util.net.*; import org.gjt.fredde.util.gui.MsgDialog; import org.gjt.fredde.yamm.mail.*; import org.gjt.fredde.yamm.YAMM; /** * Sends and gets mail */ public class SHMail extends Thread { /** Properties for smtpserver etc */ static protected Properties props = new Properties(); static protected boolean sent = false; JButton knappen; YAMM frame; /** * Disables the send/get-button and inits some stuff * @param frame1 the frame that will be used for error-msg etc. * @param name the name of this thread. * @param knapp the button to disable. */ public SHMail(YAMM frame1, String name, JButton knapp) { super(name); knappen = knapp; knappen.setEnabled(false); frame = frame1; } /** * Creates a new progress-dialog, checks for server configuration-files and * connects to the servers with a config-file. */ public void run() { frame.status.progress(0); frame.status.setStatus(""); File files[] = new File(YAMM.home + "/servers/").listFiles(); for(int i=0;i<files.length;i++) { /* load the config */ try { InputStream in = new FileInputStream(files[i]); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } String type = props.getProperty("type"); String server = props.getProperty("server"); String username = props.getProperty("username"); String password = YAMM.decrypt(props.getProperty("password")); boolean del = false; if(YAMM.getProperty("delete", "false").equals("true")) del = true; if(YAMM.getProperty("sentbox", "false").equals("true")) sent = true; if(type != null && server != null && username != null && password != null) { if(type.equals("pop3")) { Object[] argstmp = {server}; frame.status.setStatus(YAMM.getString("server.contact", argstmp)); try { Pop3 pop = new Pop3(username, password, server, YAMM.home + "/boxes/.filter"); int messages = pop.getMessageCount(); for(int j = 1; j<=messages;j++) { Object[] args = {"" + j, "" + messages}; frame.status.setStatus(YAMM.getString("server.get", args)); frame.status.progress(100-((100*messages-100*(j-1))/messages)); pop.getMessage(j); if(del) pop.deleteMessage(j); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); pop.closeConnection(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } else new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("server.bad")); } } /* load the config */ /* try { InputStream in = new FileInputStream(YAMM.home + "/.config"); props = new Properties(); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } */ if(YAMM.getProperty("smtpserver") != null && Mailbox.hasMail(YAMM.home + "/boxes/" + YAMM.getString("box.outbox"))) { Object[] argstmp = {""}; frame.status.setStatus(YAMM.getString("server.send", argstmp)); frame.status.progress(0); try { Smtp smtp = new Smtp(YAMM.getProperty("smtpserver")); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")))); PrintWriter out = null; if(sent) { out = new PrintWriter( new BufferedOutputStream( - new FileOutputStream(YAMM.getString("box.sent"), true))); + new FileOutputStream(YAMM.home + YAMM.sep + "boxes" + YAMM.sep + + YAMM.getString("box.sent"), true))); } String temp = null, from2 = null, to2 = null; int i = 1; for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.startsWith("From:")) { smtp.from(temp.substring(temp.indexOf("<") + 1, temp.indexOf(">"))); from2 = temp; } else if(temp.startsWith("To:")) { to2 = temp; if(temp.indexOf(",") == -1) smtp.to(temp.substring(4, temp.length())); else { temp.trim(); temp = temp.substring(4, temp.length()); while(temp.endsWith(",")) { smtp.to(temp.substring(0, temp.length()-1)); temp = in.readLine().trim(); to2 += "\n " + temp; } smtp.to(temp.substring(0, temp.length()-1)); to2 += "\n " + temp; temp = in.readLine(); } } else if(temp.startsWith("Subject:")) { PrintWriter mail = smtp.getOutputStream(); mail.println(from2 + "\n" + to2 + "\n" + temp); for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.equals(".")) { smtp.sendMessage(); Object[] args = {"" + i}; frame.status.setStatus(YAMM.getString("server.send", args)); i++; break; } mail.println(temp); } } } in.close(); if(sent) out.close(); File file = new File(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")); file.delete(); file.createNewFile(); smtp.closeConnection(); } catch(IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); if(Mailbox.hasMail(YAMM.home + "/boxes/.filter")) { frame.status.setStatus(YAMM.getString("server.filter")); frame.status.progress(0); try { new Filter(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); } frame.status.setStatus(""); frame.status.progress(0); knappen.setEnabled(true); } }
true
true
public void run() { frame.status.progress(0); frame.status.setStatus(""); File files[] = new File(YAMM.home + "/servers/").listFiles(); for(int i=0;i<files.length;i++) { /* load the config */ try { InputStream in = new FileInputStream(files[i]); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } String type = props.getProperty("type"); String server = props.getProperty("server"); String username = props.getProperty("username"); String password = YAMM.decrypt(props.getProperty("password")); boolean del = false; if(YAMM.getProperty("delete", "false").equals("true")) del = true; if(YAMM.getProperty("sentbox", "false").equals("true")) sent = true; if(type != null && server != null && username != null && password != null) { if(type.equals("pop3")) { Object[] argstmp = {server}; frame.status.setStatus(YAMM.getString("server.contact", argstmp)); try { Pop3 pop = new Pop3(username, password, server, YAMM.home + "/boxes/.filter"); int messages = pop.getMessageCount(); for(int j = 1; j<=messages;j++) { Object[] args = {"" + j, "" + messages}; frame.status.setStatus(YAMM.getString("server.get", args)); frame.status.progress(100-((100*messages-100*(j-1))/messages)); pop.getMessage(j); if(del) pop.deleteMessage(j); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); pop.closeConnection(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } else new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("server.bad")); } } /* load the config */ /* try { InputStream in = new FileInputStream(YAMM.home + "/.config"); props = new Properties(); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } */ if(YAMM.getProperty("smtpserver") != null && Mailbox.hasMail(YAMM.home + "/boxes/" + YAMM.getString("box.outbox"))) { Object[] argstmp = {""}; frame.status.setStatus(YAMM.getString("server.send", argstmp)); frame.status.progress(0); try { Smtp smtp = new Smtp(YAMM.getProperty("smtpserver")); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")))); PrintWriter out = null; if(sent) { out = new PrintWriter( new BufferedOutputStream( new FileOutputStream(YAMM.getString("box.sent"), true))); } String temp = null, from2 = null, to2 = null; int i = 1; for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.startsWith("From:")) { smtp.from(temp.substring(temp.indexOf("<") + 1, temp.indexOf(">"))); from2 = temp; } else if(temp.startsWith("To:")) { to2 = temp; if(temp.indexOf(",") == -1) smtp.to(temp.substring(4, temp.length())); else { temp.trim(); temp = temp.substring(4, temp.length()); while(temp.endsWith(",")) { smtp.to(temp.substring(0, temp.length()-1)); temp = in.readLine().trim(); to2 += "\n " + temp; } smtp.to(temp.substring(0, temp.length()-1)); to2 += "\n " + temp; temp = in.readLine(); } } else if(temp.startsWith("Subject:")) { PrintWriter mail = smtp.getOutputStream(); mail.println(from2 + "\n" + to2 + "\n" + temp); for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.equals(".")) { smtp.sendMessage(); Object[] args = {"" + i}; frame.status.setStatus(YAMM.getString("server.send", args)); i++; break; } mail.println(temp); } } } in.close(); if(sent) out.close(); File file = new File(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")); file.delete(); file.createNewFile(); smtp.closeConnection(); } catch(IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); if(Mailbox.hasMail(YAMM.home + "/boxes/.filter")) { frame.status.setStatus(YAMM.getString("server.filter")); frame.status.progress(0); try { new Filter(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); } frame.status.setStatus(""); frame.status.progress(0); knappen.setEnabled(true); }
public void run() { frame.status.progress(0); frame.status.setStatus(""); File files[] = new File(YAMM.home + "/servers/").listFiles(); for(int i=0;i<files.length;i++) { /* load the config */ try { InputStream in = new FileInputStream(files[i]); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } String type = props.getProperty("type"); String server = props.getProperty("server"); String username = props.getProperty("username"); String password = YAMM.decrypt(props.getProperty("password")); boolean del = false; if(YAMM.getProperty("delete", "false").equals("true")) del = true; if(YAMM.getProperty("sentbox", "false").equals("true")) sent = true; if(type != null && server != null && username != null && password != null) { if(type.equals("pop3")) { Object[] argstmp = {server}; frame.status.setStatus(YAMM.getString("server.contact", argstmp)); try { Pop3 pop = new Pop3(username, password, server, YAMM.home + "/boxes/.filter"); int messages = pop.getMessageCount(); for(int j = 1; j<=messages;j++) { Object[] args = {"" + j, "" + messages}; frame.status.setStatus(YAMM.getString("server.get", args)); frame.status.progress(100-((100*messages-100*(j-1))/messages)); pop.getMessage(j); if(del) pop.deleteMessage(j); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); pop.closeConnection(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } else new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("server.bad")); } } /* load the config */ /* try { InputStream in = new FileInputStream(YAMM.home + "/.config"); props = new Properties(); props.load(in); in.close(); } catch (IOException propsioe) { System.err.println(propsioe); } */ if(YAMM.getProperty("smtpserver") != null && Mailbox.hasMail(YAMM.home + "/boxes/" + YAMM.getString("box.outbox"))) { Object[] argstmp = {""}; frame.status.setStatus(YAMM.getString("server.send", argstmp)); frame.status.progress(0); try { Smtp smtp = new Smtp(YAMM.getProperty("smtpserver")); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")))); PrintWriter out = null; if(sent) { out = new PrintWriter( new BufferedOutputStream( new FileOutputStream(YAMM.home + YAMM.sep + "boxes" + YAMM.sep + YAMM.getString("box.sent"), true))); } String temp = null, from2 = null, to2 = null; int i = 1; for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.startsWith("From:")) { smtp.from(temp.substring(temp.indexOf("<") + 1, temp.indexOf(">"))); from2 = temp; } else if(temp.startsWith("To:")) { to2 = temp; if(temp.indexOf(",") == -1) smtp.to(temp.substring(4, temp.length())); else { temp.trim(); temp = temp.substring(4, temp.length()); while(temp.endsWith(",")) { smtp.to(temp.substring(0, temp.length()-1)); temp = in.readLine().trim(); to2 += "\n " + temp; } smtp.to(temp.substring(0, temp.length()-1)); to2 += "\n " + temp; temp = in.readLine(); } } else if(temp.startsWith("Subject:")) { PrintWriter mail = smtp.getOutputStream(); mail.println(from2 + "\n" + to2 + "\n" + temp); for(;;) { temp = in.readLine(); if(temp == null) break; if(sent) out.println(temp); if(temp.equals(".")) { smtp.sendMessage(); Object[] args = {"" + i}; frame.status.setStatus(YAMM.getString("server.send", args)); i++; break; } mail.println(temp); } } } in.close(); if(sent) out.close(); File file = new File(YAMM.home + "/boxes/" + YAMM.getString("box.outbox")); file.delete(); file.createNewFile(); smtp.closeConnection(); } catch(IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); if(Mailbox.hasMail(YAMM.home + "/boxes/.filter")) { frame.status.setStatus(YAMM.getString("server.filter")); frame.status.progress(0); try { new Filter(); } catch (IOException ioe) { Object[] args = {ioe.toString()}; new MsgDialog(frame, YAMM.getString("msg.error"), YAMM.getString("msg.exception", args)); } frame.status.setStatus(YAMM.getString("msg.done")); frame.status.progress(100); } frame.status.setStatus(""); frame.status.progress(0); knappen.setEnabled(true); }
diff --git a/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/CustomLayoutAjaxAutocompleteExamplePageContribution.java b/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/CustomLayoutAjaxAutocompleteExamplePageContribution.java index 623c1b141..5927980d9 100644 --- a/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/CustomLayoutAjaxAutocompleteExamplePageContribution.java +++ b/wicket-contrib-scriptaculous-examples/src/java/wicket/contrib/scriptaculous/examples/CustomLayoutAjaxAutocompleteExamplePageContribution.java @@ -1,65 +1,65 @@ package wicket.contrib.scriptaculous.examples; import java.util.ArrayList; import java.util.List; import wicket.PageParameters; import wicket.contrib.scriptaculous.autocomplete.CustomLayoutAutocompleteResultsPageContribution; import wicket.markup.html.basic.Label; import wicket.markup.html.list.ListItem; import wicket.markup.html.list.ListView; public class CustomLayoutAjaxAutocompleteExamplePageContribution extends CustomLayoutAutocompleteResultsPageContribution { public CustomLayoutAjaxAutocompleteExamplePageContribution(PageParameters parameters) { super(parameters); } protected ListView buildListView(String input) { List results = new ArrayList(); results.add(new CustomResultObject("ryan.gif", "Ryan Sonnek", "ryan@youremail.com")); results.add(new CustomResultObject("billy.gif", "Bill Gates", "bill.gates@microsoft.com")); results.add(new CustomResultObject("janet.gif", "Janet Someone", "janet@thethirdwheel.com")); - return new ListView("entries", results) { + return new ListView("entry", results) { protected void populateItem(ListItem item) { CustomResultObject result = (CustomResultObject) item.getModelObject(); item.add(new Label("name", result.getName())); item.add(new Label("email", result.getEmail())); } }; } private class CustomResultObject { private final String name; private final String image; private final String email; public CustomResultObject(String image, String name, String email) { this.image = image; this.name = name; this.email = email; } public String getEmail() { return email; } public String getImage() { return image; } public String getName() { return name; } } }
true
true
protected ListView buildListView(String input) { List results = new ArrayList(); results.add(new CustomResultObject("ryan.gif", "Ryan Sonnek", "ryan@youremail.com")); results.add(new CustomResultObject("billy.gif", "Bill Gates", "bill.gates@microsoft.com")); results.add(new CustomResultObject("janet.gif", "Janet Someone", "janet@thethirdwheel.com")); return new ListView("entries", results) { protected void populateItem(ListItem item) { CustomResultObject result = (CustomResultObject) item.getModelObject(); item.add(new Label("name", result.getName())); item.add(new Label("email", result.getEmail())); } }; }
protected ListView buildListView(String input) { List results = new ArrayList(); results.add(new CustomResultObject("ryan.gif", "Ryan Sonnek", "ryan@youremail.com")); results.add(new CustomResultObject("billy.gif", "Bill Gates", "bill.gates@microsoft.com")); results.add(new CustomResultObject("janet.gif", "Janet Someone", "janet@thethirdwheel.com")); return new ListView("entry", results) { protected void populateItem(ListItem item) { CustomResultObject result = (CustomResultObject) item.getModelObject(); item.add(new Label("name", result.getName())); item.add(new Label("email", result.getEmail())); } }; }
diff --git a/smos-reader/src/test/java/org/esa/beam/dataio/smos/BandDescriptorRegistryTest.java b/smos-reader/src/test/java/org/esa/beam/dataio/smos/BandDescriptorRegistryTest.java index 8fbbb0db..eebdc464 100644 --- a/smos-reader/src/test/java/org/esa/beam/dataio/smos/BandDescriptorRegistryTest.java +++ b/smos-reader/src/test/java/org/esa/beam/dataio/smos/BandDescriptorRegistryTest.java @@ -1,38 +1,38 @@ package org.esa.beam.dataio.smos; import static junit.framework.Assert.*; import org.junit.Test; public class BandDescriptorRegistryTest { @Test public void getDescriptorsFor_DBL_SM_XXXX_AUX_ECMWF__0200() { final String formatName = "DBL_SM_XXXX_AUX_ECMWF__0200"; final BandDescriptors descriptors = BandDescriptorRegistry.getInstance().getDescriptors(formatName); assertEquals(38, descriptors.asList().size()); final BandDescriptor descriptor = descriptors.getDescriptor("RR"); assertNotNull(descriptor); assertEquals("RR", descriptor.getBandName()); assertEquals("Rain_Rate", descriptor.getMemberName()); assertTrue(descriptor.hasTypicalMin()); assertTrue(descriptor.hasTypicalMax()); assertFalse(descriptor.isCyclic()); assertTrue(descriptor.hasFillValue()); assertFalse(descriptor.getValidPixelExpression().isEmpty()); assertEquals("RR.raw != -99999.0 && RR.raw != -99998.0", descriptor.getValidPixelExpression()); assertFalse(descriptor.getUnit().isEmpty()); assertFalse(descriptor.getDescription().isEmpty()); assertEquals(0.0, descriptor.getTypicalMin(), 0.0); - assertEquals("mm h-1", descriptor.getUnit()); + assertEquals("m 3h-1", descriptor.getUnit()); final FlagDescriptors flagDescriptors = descriptors.getDescriptor("F1").getFlagDescriptors(); assertNotNull(flagDescriptors); assertSame(FlagDescriptorRegistry.getInstance().getDescriptors("DBL_SM_XXXX_AUX_ECMWF__0200_F1.txt"), flagDescriptors); descriptor.getFlagDescriptors(); } }
true
true
public void getDescriptorsFor_DBL_SM_XXXX_AUX_ECMWF__0200() { final String formatName = "DBL_SM_XXXX_AUX_ECMWF__0200"; final BandDescriptors descriptors = BandDescriptorRegistry.getInstance().getDescriptors(formatName); assertEquals(38, descriptors.asList().size()); final BandDescriptor descriptor = descriptors.getDescriptor("RR"); assertNotNull(descriptor); assertEquals("RR", descriptor.getBandName()); assertEquals("Rain_Rate", descriptor.getMemberName()); assertTrue(descriptor.hasTypicalMin()); assertTrue(descriptor.hasTypicalMax()); assertFalse(descriptor.isCyclic()); assertTrue(descriptor.hasFillValue()); assertFalse(descriptor.getValidPixelExpression().isEmpty()); assertEquals("RR.raw != -99999.0 && RR.raw != -99998.0", descriptor.getValidPixelExpression()); assertFalse(descriptor.getUnit().isEmpty()); assertFalse(descriptor.getDescription().isEmpty()); assertEquals(0.0, descriptor.getTypicalMin(), 0.0); assertEquals("mm h-1", descriptor.getUnit()); final FlagDescriptors flagDescriptors = descriptors.getDescriptor("F1").getFlagDescriptors(); assertNotNull(flagDescriptors); assertSame(FlagDescriptorRegistry.getInstance().getDescriptors("DBL_SM_XXXX_AUX_ECMWF__0200_F1.txt"), flagDescriptors); descriptor.getFlagDescriptors(); }
public void getDescriptorsFor_DBL_SM_XXXX_AUX_ECMWF__0200() { final String formatName = "DBL_SM_XXXX_AUX_ECMWF__0200"; final BandDescriptors descriptors = BandDescriptorRegistry.getInstance().getDescriptors(formatName); assertEquals(38, descriptors.asList().size()); final BandDescriptor descriptor = descriptors.getDescriptor("RR"); assertNotNull(descriptor); assertEquals("RR", descriptor.getBandName()); assertEquals("Rain_Rate", descriptor.getMemberName()); assertTrue(descriptor.hasTypicalMin()); assertTrue(descriptor.hasTypicalMax()); assertFalse(descriptor.isCyclic()); assertTrue(descriptor.hasFillValue()); assertFalse(descriptor.getValidPixelExpression().isEmpty()); assertEquals("RR.raw != -99999.0 && RR.raw != -99998.0", descriptor.getValidPixelExpression()); assertFalse(descriptor.getUnit().isEmpty()); assertFalse(descriptor.getDescription().isEmpty()); assertEquals(0.0, descriptor.getTypicalMin(), 0.0); assertEquals("m 3h-1", descriptor.getUnit()); final FlagDescriptors flagDescriptors = descriptors.getDescriptor("F1").getFlagDescriptors(); assertNotNull(flagDescriptors); assertSame(FlagDescriptorRegistry.getInstance().getDescriptors("DBL_SM_XXXX_AUX_ECMWF__0200_F1.txt"), flagDescriptors); descriptor.getFlagDescriptors(); }
diff --git a/farrago/src/net/sf/farrago/ddl/DdlHandler.java b/farrago/src/net/sf/farrago/ddl/DdlHandler.java index 7a6f1cf7a..0c50cc348 100644 --- a/farrago/src/net/sf/farrago/ddl/DdlHandler.java +++ b/farrago/src/net/sf/farrago/ddl/DdlHandler.java @@ -1,614 +1,614 @@ /* // $Id$ // Farrago is an extensible data management system. // Copyright (C) 2005-2005 The Eigenbase Project // Copyright (C) 2005-2005 Disruptive Tech // Copyright (C) 2005-2005 LucidEra, Inc. // Portions Copyright (C) 2004-2005 John V. Sichi // // 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 The Eigenbase Project. // // 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 net.sf.farrago.ddl; import org.eigenbase.util.*; import org.eigenbase.resource.*; import org.eigenbase.relopt.*; import org.eigenbase.reltype.*; import org.eigenbase.sql.*; import org.eigenbase.sql.parser.*; import org.eigenbase.sql.type.*; import org.eigenbase.sql.validate.*; import net.sf.farrago.catalog.*; import net.sf.farrago.resource.*; import net.sf.farrago.query.*; import net.sf.farrago.session.*; import net.sf.farrago.trace.*; import net.sf.farrago.type.*; import net.sf.farrago.util.*; import net.sf.farrago.cwm.core.*; import net.sf.farrago.cwm.relational.*; import net.sf.farrago.cwm.relational.enumerations.*; import net.sf.farrago.fem.sql2003.*; import net.sf.farrago.fem.med.*; import java.io.*; import java.nio.charset.*; import java.sql.*; import java.util.*; import java.util.logging.*; /** * DdlHandler is an abstract base for classes which provide implementations for * the actions taken by {@link DdlValidator} on individual objects. See {@link * FarragoSessionDdlHandler} for an explanation. * * @author John V. Sichi * @version $Id$ */ public abstract class DdlHandler { protected static final Logger tracer = FarragoTrace.getDdlValidatorTracer(); protected final FarragoSessionDdlValidator validator; protected final FarragoRepos repos; /** * An instance of FarragoResource for use in throwing validation * errors. The name is intentionally short to keep line length under * control. */ protected final FarragoResource res; public DdlHandler(FarragoSessionDdlValidator validator) { this.validator = validator; repos = validator.getRepos(); res = FarragoResource.instance(); } public FarragoSessionDdlValidator getValidator() { return validator; } public void validateAttributeSet(CwmClass cwmClass) { List structuralFeatures = FarragoCatalogUtil.getStructuralFeatures(cwmClass); validator.validateUniqueNames( cwmClass, structuralFeatures, false); Iterator iter = structuralFeatures.iterator(); while (iter.hasNext()) { FemAbstractAttribute attribute = (FemAbstractAttribute) iter.next(); validateAttribute(attribute); } } public void validateBaseColumnSet(FemBaseColumnSet columnSet) { validateAttributeSet(columnSet); // REVIEW jvs 21-Jan-2005: something fishy here... // Foreign tables should not support constraint definitions. Eventually // we may want to allow this as a hint to the optimizer, but it's not // standard so for now we should prevent it. Iterator constraintIter = columnSet.getOwnedElement().iterator(); while (constraintIter.hasNext()) { Object obj = constraintIter.next(); if (!(obj instanceof FemAbstractKeyConstraint)) { continue; } throw res.ValidatorNoConstraintAllowed.ex( repos.getLocalizedObjectName(columnSet)); } } public void validateAttribute(FemAbstractAttribute attribute) { // REVIEW jvs 26-Feb-2005: This relies on the fact that // attributes always come before operations. We'll need to // take this into account in the implementation of ALTER TYPE. int ordinal = attribute.getOwner().getFeature().indexOf(attribute); assert (ordinal != -1); attribute.setOrdinal(ordinal); if (attribute.getInitialValue() == null) { CwmExpression nullExpression = repos.newCwmExpression(); nullExpression.setLanguage("SQL"); nullExpression.setBody("NULL"); attribute.setInitialValue(nullExpression); } // if NOT NULL not specified, default to nullable if (attribute.getIsNullable() == null) { attribute.setIsNullable(NullableTypeEnum.COLUMN_NULLABLE); } validateTypedElement(attribute, attribute.getOwner()); String defaultExpression = attribute.getInitialValue().getBody(); if (!defaultExpression.equalsIgnoreCase("NULL")) { FarragoSession session = validator.newReentrantSession(); try { validateDefaultClause(attribute, session, defaultExpression); } catch (Throwable ex) { throw validator.newPositionalError( attribute, res.ValidatorBadDefaultClause.ex( repos.getLocalizedObjectName(attribute), ex)); } finally { validator.releaseReentrantSession(session); } } } private void convertSqlToCatalogType( SqlDataTypeSpec dataType, FemSqltypedElement element) { CwmSqldataType type = validator.getStmtValidator().findSqldataType( dataType.getTypeName()); element.setType(type); if (dataType.getPrecision() > 0) { element.setPrecision(new Integer(dataType.getPrecision())); } if (dataType.getScale() > 0) { element.setScale(new Integer(dataType.getScale())); } if (dataType.getCharSetName() != null) { element.setCharacterSetName(dataType.getCharSetName()); } } public void validateTypedElement( FemAbstractTypedElement abstractElement, CwmNamespace cwmNamespace) { validateTypedElement( FarragoCatalogUtil.toFemSqltypedElement(abstractElement), cwmNamespace); } private void validateTypedElement( FemSqltypedElement element, CwmNamespace cwmNamespace) { final FemAbstractTypedElement abstractElement = element.getModelElement(); SqlDataTypeSpec dataType = (SqlDataTypeSpec) validator.getSqlDefinition(abstractElement); if (dataType != null) { convertSqlToCatalogType(dataType, element); } CwmSqldataType type = (CwmSqldataType) element.getType(); SqlTypeName typeName = SqlTypeName.get(type.getName()); // Check that every type is supported. For example, we don't support // columns of type DECIMAL(p, s) or LONG VARCHAR right now. final FarragoSessionPersonality personality = validator.getStmtValidator().getSession().getPersonality(); if (!personality.isSupportedType(typeName)) { throw newContextException(type, EigenbaseResource.instance().TypeNotSupported.ex( typeName.toString())); } // REVIEW jvs 23-Mar-2005: For now, we attach the dependency to // a containing namespace. For example, if a column is declared // with a UDT for its type, the containing table depends on the // type. This isn't SQL-kosher; the dependency is supposed to // be at the column granularity. To fix this, we need two things: // (1) the ability to declare dependencies from non-namespaces, and // (2) the ability to correctly cascade the DROP at the column level. if (type instanceof FemUserDefinedType) { boolean method = false; if (cwmNamespace instanceof FemRoutine) { FemRoutine routine = (FemRoutine) cwmNamespace; if (FarragoCatalogUtil.isRoutineMethod(routine)) { if (routine.getSpecification().getOwner() == type) { // This is a method of the type in question. In this // case, we don't create a dependency, because the // circularity would foul up DROP. method = true; } } } if (!method) { validator.createDependency( cwmNamespace, Collections.singleton(type)); } } // NOTE: parser only generates precision, but CWM discriminates // precision from length, so we take care of it below Integer precision = element.getPrecision(); if (precision == null) { precision = element.getLength(); } // TODO: break this method up // first, validate presence of modifiers if ((typeName != null) && typeName.allowsPrec()) { if (precision == null) { int p = typeName.getDefaultPrecision(); if (p != -1) { precision = new Integer(p); } } if ((precision == null) && !typeName.allowsNoPrecNoScale()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecRequired.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } else { if (precision != null) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } if ((typeName != null) && typeName.allowsScale()) { // assume scale is always optional } else { if (element.getScale() != null) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } SqlTypeFamily typeFamily = null; if (typeName != null) { typeFamily = SqlTypeFamily.getFamilyForSqlType(typeName); } if ((typeFamily == SqlTypeFamily.Character) || (typeFamily == SqlTypeFamily.Binary)) { // convert precision to length - if (element.getLength() == null) { + if (element.getPrecision() != null) { element.setLength(element.getPrecision()); element.setPrecision(null); } } if (typeFamily == SqlTypeFamily.Character) { // TODO jvs 18-April-2004: Should be inheriting these defaults // from schema/catalog. if (JmiUtil.isBlank(element.getCharacterSetName())) { // NOTE: don't leave character set name implicit, since if the // default ever changed, that would invalidate existing data element.setCharacterSetName( repos.getDefaultCharsetName()); } else { if (!Charset.isSupported(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnsupported.ex( element.getCharacterSetName(), repos.getLocalizedObjectName(abstractElement))); } } Charset charSet = Charset.forName(element.getCharacterSetName()); if (charSet.newEncoder().maxBytesPerChar() > 1) { // TODO: implement multi-byte character sets throw Util.needToImplement(charSet); } } else { if (!JmiUtil.isBlank(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } // now, enforce type-defined limits if (type instanceof CwmSqlsimpleType) { CwmSqlsimpleType simpleType = (CwmSqlsimpleType) type; if (element.getLength() != null) { Integer maximum = simpleType.getCharacterMaximumLength(); assert (maximum != null); if (element.getLength().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorLengthExceeded.ex( element.getLength(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getPrecision() != null) { Integer maximum = simpleType.getNumericPrecision(); if (maximum == null) { maximum = simpleType.getDateTimePrecision(); } assert (maximum != null); if (element.getPrecision().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecisionExceeded.ex( element.getPrecision(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getScale() != null) { Integer maximum = simpleType.getNumericScale(); assert (maximum != null); if (element.getScale().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleExceeded.ex( element.getScale(), maximum, repos.getLocalizedObjectName(abstractElement))); } } } else if (type instanceof FemSqlcollectionType) { FemSqlcollectionType collectionType = (FemSqlcollectionType) type; FemSqltypeAttribute componentType = (FemSqltypeAttribute) collectionType.getFeature().get(0); validateAttribute(componentType); } else if (type instanceof FemUserDefinedType) { // nothing special to do for UDT's, which were // already validated on creation } else if (type instanceof FemSqlrowType) { FemSqlrowType rowType = (FemSqlrowType) type; for (Iterator columnIter = rowType.getFeature().iterator(); columnIter.hasNext();) { FemAbstractAttribute column = (FemAbstractAttribute) columnIter.next(); validateAttribute(column); } } else { throw Util.needToImplement(type); } // REVIEW jvs 18-April-2004: I had to put these in because CWM // declares them as mandatory. This is stupid, since CWM also says // these fields are inapplicable for non-character types. if (element.getCollationName() == null) { element.setCollationName(""); } if (element.getCharacterSetName() == null) { element.setCharacterSetName(""); } validator.getStmtValidator().setParserPosition(null); } /** * Adds position information to an exception. * * <p>This method is similar to * {@link SqlValidator#newValidationError(SqlNode, SqlValidatorException)} * and should be unified with it, if only we could figure out how. * * @param element Element which had the error, and is therefore the locus * of the exception * @param e Exception raised * @return Exception with position information */ private RuntimeException newContextException( CwmModelElement element, Exception e) { SqlParserPos pos = validator.getParserOffset(element); if (pos == null) { pos = SqlParserPos.ZERO; } return SqlUtil.newContextException(pos, e); } /** * Initializes a {@link CwmColumn} definition based on a * {@link RelDataTypeField}. * * <p>As well as calling {@link CwmColumn#setType(CwmClassifier)}, * also calls {@link CwmColumn#setPrecision(Integer)}, * {@link CwmColumn#setScale(Integer)} and * {@link CwmColumn#setIsNullable(NullableType)}. * * <p>If the column has no name, the name is initialized from the field * name; otherwise, the existing name is left unmodified. * * @param field input field * @param column on input, contains unintialized CwmColumn instance; * @param owner The object which is to own any anonymous datatypes created; * typically, the table which this column belongs to * @pre field != null && column != null && owner != null */ public void convertFieldToCwmColumn( RelDataTypeField field, CwmColumn column, CwmNamespace owner) { assert field != null && column != null && owner != null : "pre"; if (column.getName() == null) { final String name = field.getName(); assert name != null; column.setName(name); } convertTypeToCwmColumn(field.getType(), column, owner); } /** * Populates a {@link CwmColumn} object with type information. * * <p>As well as calling {@link CwmColumn#setType(CwmClassifier)}, * also calls {@link CwmColumn#setPrecision(Integer)}, * {@link CwmColumn#setScale(Integer)} and * {@link CwmColumn#setIsNullable(NullableType)}. * * <p>If the type is structured or a multiset, the implementation is * recursive. * * @param type Type to convert * @param column Column to populate with type information * @param owner The object which is to own any anonymous datatypes created; * typically, the table which this column belongs to */ private void convertTypeToCwmColumn( RelDataType type, CwmColumn column, CwmNamespace owner) { CwmSqldataType cwmType; final SqlTypeName typeName = type.getSqlTypeName(); if (typeName == SqlTypeName.Row) { Util.permAssert(type.isStruct(), "type.isStruct()"); FemSqlrowType rowType = repos.newFemSqlrowType(); rowType.setName("SYS$ROW_" + rowType.refMofId()); final RelDataTypeField[] fields = type.getFields(); for (int i = 0; i < fields.length; i++) { RelDataTypeField subField = fields[i]; FemSqltypeAttribute subColumn = repos.newFemSqltypeAttribute(); convertFieldToCwmColumn(subField, subColumn, owner); rowType.getFeature().add(subColumn); } // Attach the anonymous type to the owner of the column, to ensure // that it is destroyed. owner.getOwnedElement().add(rowType); cwmType = rowType; } else if (type.getComponentType() != null) { final RelDataType componentType = type.getComponentType(); final FemSqlmultisetType multisetType = repos.newFemSqlmultisetType(); multisetType.setName("SYS$MULTISET_" + multisetType.refMofId()); final FemAbstractAttribute attr = repos.newFemSqltypeAttribute(); attr.setName("SYS$MULTISET_COMPONENT_" + attr.refMofId()); convertTypeToCwmColumn(componentType, attr, owner); multisetType.getFeature().add(attr); // Attach the anonymous type to the owner of the column, to ensure // that it is destroyed. owner.getOwnedElement().add(multisetType); cwmType = multisetType; } else { cwmType = validator.getStmtValidator().findSqldataType( type.getSqlIdentifier()); Util.permAssert(cwmType != null, "cwmType != null"); if (typeName != null) { if (typeName.allowsPrec()) { column.setPrecision(new Integer(type.getPrecision())); if (typeName.allowsScale()) { column.setScale(new Integer(type.getScale())); } } } else { throw Util.needToImplement(type); } } column.setType(cwmType); if (type.isNullable()) { column.setIsNullable(NullableTypeEnum.COLUMN_NULLABLE); } else { column.setIsNullable(NullableTypeEnum.COLUMN_NO_NULLS); } } public Throwable adjustExceptionParserPosition( CwmModelElement modelElement, Throwable ex) { if (!(ex instanceof EigenbaseContextException)) { return ex; } EigenbaseContextException contextExcn = (EigenbaseContextException) ex; // We have context information for the query, and // need to adjust the position to match the original // DDL statement. SqlParserPos offsetPos = validator.getParserOffset(modelElement); int line = contextExcn.getPosLine(); int col = contextExcn.getPosColumn(); int endLine = contextExcn.getEndPosLine(); int endCol = contextExcn.getEndPosColumn(); if (line == 1) { col += (offsetPos.getColumnNum() - 1); } line += (offsetPos.getLineNum() - 1); if (endLine == 1) { endCol += (offsetPos.getColumnNum() - 1); } endLine += (offsetPos.getLineNum() - 1); return SqlUtil.newContextException( line, col, endLine, endCol, ex.getCause()); } private void validateDefaultClause( FemAbstractAttribute attribute, FarragoSession session, String defaultExpression) { String sql = "VALUES(" + defaultExpression + ")"; // null param def factory okay because we won't use dynamic params FarragoSessionStmtContext stmtContext = session.newStmtContext(null); stmtContext.prepare(sql, false); RelDataType rowType = stmtContext.getPreparedRowType(); assert (rowType.getFieldList().size() == 1); if (stmtContext.getPreparedParamType().getFieldList().size() > 0) { throw validator.newPositionalError( attribute, res.ValidatorBadDefaultParam.ex( repos.getLocalizedObjectName(attribute))); } // SQL standard is very picky about what can go in a DEFAULT clause RelDataType sourceType = rowType.getFields()[0].getType(); RelDataTypeFamily sourceTypeFamily = sourceType.getFamily(); RelDataType targetType = validator.getTypeFactory().createCwmElementType(attribute); RelDataTypeFamily targetTypeFamily = targetType.getFamily(); if (sourceTypeFamily != targetTypeFamily) { throw validator.newPositionalError( attribute, res.ValidatorBadDefaultType.ex( repos.getLocalizedObjectName(attribute), targetTypeFamily.toString(), sourceTypeFamily.toString())); } // TODO: additional rules from standard, like no truncation allowed. // Maybe just execute SELECT with and without cast to target type and // make sure the same value comes back. } } // End DdlHandler.java
true
true
private void validateTypedElement( FemSqltypedElement element, CwmNamespace cwmNamespace) { final FemAbstractTypedElement abstractElement = element.getModelElement(); SqlDataTypeSpec dataType = (SqlDataTypeSpec) validator.getSqlDefinition(abstractElement); if (dataType != null) { convertSqlToCatalogType(dataType, element); } CwmSqldataType type = (CwmSqldataType) element.getType(); SqlTypeName typeName = SqlTypeName.get(type.getName()); // Check that every type is supported. For example, we don't support // columns of type DECIMAL(p, s) or LONG VARCHAR right now. final FarragoSessionPersonality personality = validator.getStmtValidator().getSession().getPersonality(); if (!personality.isSupportedType(typeName)) { throw newContextException(type, EigenbaseResource.instance().TypeNotSupported.ex( typeName.toString())); } // REVIEW jvs 23-Mar-2005: For now, we attach the dependency to // a containing namespace. For example, if a column is declared // with a UDT for its type, the containing table depends on the // type. This isn't SQL-kosher; the dependency is supposed to // be at the column granularity. To fix this, we need two things: // (1) the ability to declare dependencies from non-namespaces, and // (2) the ability to correctly cascade the DROP at the column level. if (type instanceof FemUserDefinedType) { boolean method = false; if (cwmNamespace instanceof FemRoutine) { FemRoutine routine = (FemRoutine) cwmNamespace; if (FarragoCatalogUtil.isRoutineMethod(routine)) { if (routine.getSpecification().getOwner() == type) { // This is a method of the type in question. In this // case, we don't create a dependency, because the // circularity would foul up DROP. method = true; } } } if (!method) { validator.createDependency( cwmNamespace, Collections.singleton(type)); } } // NOTE: parser only generates precision, but CWM discriminates // precision from length, so we take care of it below Integer precision = element.getPrecision(); if (precision == null) { precision = element.getLength(); } // TODO: break this method up // first, validate presence of modifiers if ((typeName != null) && typeName.allowsPrec()) { if (precision == null) { int p = typeName.getDefaultPrecision(); if (p != -1) { precision = new Integer(p); } } if ((precision == null) && !typeName.allowsNoPrecNoScale()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecRequired.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } else { if (precision != null) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } if ((typeName != null) && typeName.allowsScale()) { // assume scale is always optional } else { if (element.getScale() != null) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } SqlTypeFamily typeFamily = null; if (typeName != null) { typeFamily = SqlTypeFamily.getFamilyForSqlType(typeName); } if ((typeFamily == SqlTypeFamily.Character) || (typeFamily == SqlTypeFamily.Binary)) { // convert precision to length if (element.getLength() == null) { element.setLength(element.getPrecision()); element.setPrecision(null); } } if (typeFamily == SqlTypeFamily.Character) { // TODO jvs 18-April-2004: Should be inheriting these defaults // from schema/catalog. if (JmiUtil.isBlank(element.getCharacterSetName())) { // NOTE: don't leave character set name implicit, since if the // default ever changed, that would invalidate existing data element.setCharacterSetName( repos.getDefaultCharsetName()); } else { if (!Charset.isSupported(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnsupported.ex( element.getCharacterSetName(), repos.getLocalizedObjectName(abstractElement))); } } Charset charSet = Charset.forName(element.getCharacterSetName()); if (charSet.newEncoder().maxBytesPerChar() > 1) { // TODO: implement multi-byte character sets throw Util.needToImplement(charSet); } } else { if (!JmiUtil.isBlank(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } // now, enforce type-defined limits if (type instanceof CwmSqlsimpleType) { CwmSqlsimpleType simpleType = (CwmSqlsimpleType) type; if (element.getLength() != null) { Integer maximum = simpleType.getCharacterMaximumLength(); assert (maximum != null); if (element.getLength().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorLengthExceeded.ex( element.getLength(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getPrecision() != null) { Integer maximum = simpleType.getNumericPrecision(); if (maximum == null) { maximum = simpleType.getDateTimePrecision(); } assert (maximum != null); if (element.getPrecision().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecisionExceeded.ex( element.getPrecision(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getScale() != null) { Integer maximum = simpleType.getNumericScale(); assert (maximum != null); if (element.getScale().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleExceeded.ex( element.getScale(), maximum, repos.getLocalizedObjectName(abstractElement))); } } } else if (type instanceof FemSqlcollectionType) { FemSqlcollectionType collectionType = (FemSqlcollectionType) type; FemSqltypeAttribute componentType = (FemSqltypeAttribute) collectionType.getFeature().get(0); validateAttribute(componentType); } else if (type instanceof FemUserDefinedType) { // nothing special to do for UDT's, which were // already validated on creation } else if (type instanceof FemSqlrowType) { FemSqlrowType rowType = (FemSqlrowType) type; for (Iterator columnIter = rowType.getFeature().iterator(); columnIter.hasNext();) { FemAbstractAttribute column = (FemAbstractAttribute) columnIter.next(); validateAttribute(column); } } else { throw Util.needToImplement(type); } // REVIEW jvs 18-April-2004: I had to put these in because CWM // declares them as mandatory. This is stupid, since CWM also says // these fields are inapplicable for non-character types. if (element.getCollationName() == null) { element.setCollationName(""); } if (element.getCharacterSetName() == null) { element.setCharacterSetName(""); } validator.getStmtValidator().setParserPosition(null); }
private void validateTypedElement( FemSqltypedElement element, CwmNamespace cwmNamespace) { final FemAbstractTypedElement abstractElement = element.getModelElement(); SqlDataTypeSpec dataType = (SqlDataTypeSpec) validator.getSqlDefinition(abstractElement); if (dataType != null) { convertSqlToCatalogType(dataType, element); } CwmSqldataType type = (CwmSqldataType) element.getType(); SqlTypeName typeName = SqlTypeName.get(type.getName()); // Check that every type is supported. For example, we don't support // columns of type DECIMAL(p, s) or LONG VARCHAR right now. final FarragoSessionPersonality personality = validator.getStmtValidator().getSession().getPersonality(); if (!personality.isSupportedType(typeName)) { throw newContextException(type, EigenbaseResource.instance().TypeNotSupported.ex( typeName.toString())); } // REVIEW jvs 23-Mar-2005: For now, we attach the dependency to // a containing namespace. For example, if a column is declared // with a UDT for its type, the containing table depends on the // type. This isn't SQL-kosher; the dependency is supposed to // be at the column granularity. To fix this, we need two things: // (1) the ability to declare dependencies from non-namespaces, and // (2) the ability to correctly cascade the DROP at the column level. if (type instanceof FemUserDefinedType) { boolean method = false; if (cwmNamespace instanceof FemRoutine) { FemRoutine routine = (FemRoutine) cwmNamespace; if (FarragoCatalogUtil.isRoutineMethod(routine)) { if (routine.getSpecification().getOwner() == type) { // This is a method of the type in question. In this // case, we don't create a dependency, because the // circularity would foul up DROP. method = true; } } } if (!method) { validator.createDependency( cwmNamespace, Collections.singleton(type)); } } // NOTE: parser only generates precision, but CWM discriminates // precision from length, so we take care of it below Integer precision = element.getPrecision(); if (precision == null) { precision = element.getLength(); } // TODO: break this method up // first, validate presence of modifiers if ((typeName != null) && typeName.allowsPrec()) { if (precision == null) { int p = typeName.getDefaultPrecision(); if (p != -1) { precision = new Integer(p); } } if ((precision == null) && !typeName.allowsNoPrecNoScale()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecRequired.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } else { if (precision != null) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } if ((typeName != null) && typeName.allowsScale()) { // assume scale is always optional } else { if (element.getScale() != null) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } SqlTypeFamily typeFamily = null; if (typeName != null) { typeFamily = SqlTypeFamily.getFamilyForSqlType(typeName); } if ((typeFamily == SqlTypeFamily.Character) || (typeFamily == SqlTypeFamily.Binary)) { // convert precision to length if (element.getPrecision() != null) { element.setLength(element.getPrecision()); element.setPrecision(null); } } if (typeFamily == SqlTypeFamily.Character) { // TODO jvs 18-April-2004: Should be inheriting these defaults // from schema/catalog. if (JmiUtil.isBlank(element.getCharacterSetName())) { // NOTE: don't leave character set name implicit, since if the // default ever changed, that would invalidate existing data element.setCharacterSetName( repos.getDefaultCharsetName()); } else { if (!Charset.isSupported(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnsupported.ex( element.getCharacterSetName(), repos.getLocalizedObjectName(abstractElement))); } } Charset charSet = Charset.forName(element.getCharacterSetName()); if (charSet.newEncoder().maxBytesPerChar() > 1) { // TODO: implement multi-byte character sets throw Util.needToImplement(charSet); } } else { if (!JmiUtil.isBlank(element.getCharacterSetName())) { throw validator.newPositionalError( abstractElement, res.ValidatorCharsetUnexpected.ex( repos.getLocalizedObjectName(type), repos.getLocalizedObjectName(abstractElement))); } } // now, enforce type-defined limits if (type instanceof CwmSqlsimpleType) { CwmSqlsimpleType simpleType = (CwmSqlsimpleType) type; if (element.getLength() != null) { Integer maximum = simpleType.getCharacterMaximumLength(); assert (maximum != null); if (element.getLength().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorLengthExceeded.ex( element.getLength(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getPrecision() != null) { Integer maximum = simpleType.getNumericPrecision(); if (maximum == null) { maximum = simpleType.getDateTimePrecision(); } assert (maximum != null); if (element.getPrecision().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorPrecisionExceeded.ex( element.getPrecision(), maximum, repos.getLocalizedObjectName(abstractElement))); } } if (element.getScale() != null) { Integer maximum = simpleType.getNumericScale(); assert (maximum != null); if (element.getScale().intValue() > maximum.intValue()) { throw validator.newPositionalError( abstractElement, res.ValidatorScaleExceeded.ex( element.getScale(), maximum, repos.getLocalizedObjectName(abstractElement))); } } } else if (type instanceof FemSqlcollectionType) { FemSqlcollectionType collectionType = (FemSqlcollectionType) type; FemSqltypeAttribute componentType = (FemSqltypeAttribute) collectionType.getFeature().get(0); validateAttribute(componentType); } else if (type instanceof FemUserDefinedType) { // nothing special to do for UDT's, which were // already validated on creation } else if (type instanceof FemSqlrowType) { FemSqlrowType rowType = (FemSqlrowType) type; for (Iterator columnIter = rowType.getFeature().iterator(); columnIter.hasNext();) { FemAbstractAttribute column = (FemAbstractAttribute) columnIter.next(); validateAttribute(column); } } else { throw Util.needToImplement(type); } // REVIEW jvs 18-April-2004: I had to put these in because CWM // declares them as mandatory. This is stupid, since CWM also says // these fields are inapplicable for non-character types. if (element.getCollationName() == null) { element.setCollationName(""); } if (element.getCharacterSetName() == null) { element.setCharacterSetName(""); } validator.getStmtValidator().setParserPosition(null); }
diff --git a/mmstudio/src/org/micromanager/conf/AddDeviceDlg.java b/mmstudio/src/org/micromanager/conf/AddDeviceDlg.java index 654f54e5a..9dd279bf3 100644 --- a/mmstudio/src/org/micromanager/conf/AddDeviceDlg.java +++ b/mmstudio/src/org/micromanager/conf/AddDeviceDlg.java @@ -1,329 +1,329 @@ /////////////////////////////////////////////////////////////////////////////// //FILE: AddDeviceDlg.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- // // AUTHOR: Nenad Amodaj, nenad@amodaj.com, November 07, 2006 // New Tree View: Karl Hoover January 13, 2011 // // COPYRIGHT: University of California, San Francisco, 2006 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // CVS: $Id$ package org.micromanager.conf; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.micromanager.utils.ReportingUtils; /** * Dialog to add a new device to the configuration. */ public class AddDeviceDlg extends JDialog implements MouseListener, TreeSelectionListener { private static final long serialVersionUID = 1L; class TreeWContextMenu extends JTree implements ActionListener { public TreeWContextMenu(DefaultMutableTreeNode n, AddDeviceDlg d){ super(n); d_ = d; popupMenu_ = new JPopupMenu(); JMenuItem jmi = new JMenuItem("Add"); jmi.setActionCommand("add"); jmi.addActionListener(this); popupMenu_.add(jmi); jmi = new JMenuItem("Help"); jmi.setActionCommand("help"); jmi.addActionListener(this); popupMenu_.add(jmi); popupMenu_.setOpaque(true); popupMenu_.setLightWeightPopupEnabled(true); addMouseListener( new MouseAdapter() { public void mouseReleased( MouseEvent e ) { if ( e.isPopupTrigger()) { popupMenu_.show( (JComponent)e.getSource(), e.getX(), e.getY() ); } } } ); } JPopupMenu popupMenu_; AddDeviceDlg d_; // pretty ugly public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("help")) { d_.displayDocumentation(); } else if (ae.getActionCommand().equals("add")) { if (d_.addDevice()) { d_.rebuildTable(); } } } } class TreeNodeShowsDeviceAndDescription extends DefaultMutableTreeNode { public TreeNodeShowsDeviceAndDescription(String value) { super(value); } @Override public String toString() { String ret = ""; Object uo = getUserObject(); if (null != uo) { if (uo.getClass().isArray()) { Object[] userData = (Object[]) uo; if (2 < userData.length) { ret = userData[1].toString() + " | " + userData[2].toString(); } } else { ret = uo.toString(); } } return ret; } // if user clicks on a container node, just return a null array instead of the user data public Object[] getUserDataArray() { Object[] ret = null; Object uo = getUserObject(); if (null != uo) { if (uo.getClass().isArray()) { // retrieve the device info tuple Object[] userData = (Object[]) uo; if (1 < userData.length) { ret = userData; } } } return ret; } } private MicroscopeModel model_; private DevicesPage devicesPage_; private TreeWContextMenu theTree_; final String documentationURLroot_; String libraryDocumentationName_; /** * Create the dialog */ public AddDeviceDlg(MicroscopeModel model, DevicesPage devicesPage) { super(); setModal(true); setResizable(false); getContentPane().setLayout(null); setTitle("Add Device"); setBounds(400, 100, 596, 529); devicesPage_ = devicesPage; Device allDevs_[] = model.getAvailableDeviceList(); String thisLibrary = ""; DefaultMutableTreeNode root = new DefaultMutableTreeNode("Devices supported by " + "\u00B5" + "Manager"); TreeNodeShowsDeviceAndDescription node = null; for (int idd = 0; idd < allDevs_.length; ++idd) { // assume that the first library doesn't have an empty name! (of course!) if( !allDevs_[idd].isDiscoverable()) { // don't add devices which can be added by their respective master / hub if (0 != thisLibrary.compareTo(allDevs_[idd].getLibrary())) { // create a new node of devices for this library node = new TreeNodeShowsDeviceAndDescription(allDevs_[idd].getLibrary()); root.add(node); thisLibrary = allDevs_[idd].getLibrary(); // remember which library we are processing } Object[] userObject = {allDevs_[idd].getLibrary(), allDevs_[idd].getAdapterName(), allDevs_[idd].getDescription()}; TreeNodeShowsDeviceAndDescription aLeaf = new TreeNodeShowsDeviceAndDescription(""); aLeaf.setUserObject(userObject); node.add(aLeaf); } } // try building a tree theTree_ = new TreeWContextMenu(root, this); theTree_.addTreeSelectionListener(this); // double click should add the device, single click selects row and waits for user to press 'add' MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (2 == e.getClickCount()) { if (addDevice()) { rebuildTable(); } } } }; theTree_.addMouseListener(ml); theTree_.setRootVisible(false); theTree_.setShowsRootHandles(true); final JScrollPane scrollPane = new JScrollPane(theTree_); scrollPane.setBounds(10, 10, 471, 475); getContentPane().add(scrollPane); final JButton addButton = new JButton(); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (addDevice()) { rebuildTable(); } } }); addButton.setText("Add"); addButton.setBounds(490, 10, 93, 23); getContentPane().add(addButton); getRootPane().setDefaultButton(addButton); final JButton doneButton = new JButton(); doneButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); doneButton.setText("Done"); doneButton.setBounds(490, 39, 93, 23); getContentPane().add(doneButton); getRootPane().setDefaultButton(doneButton); model_ = model; //put the URL for the documentation for the selected node into a browser control - documentationURLroot_ = "https://valelab.ucsf.edu/~nico/MMwiki/index.php/"; + documentationURLroot_ = "https://valelab.ucsf.edu/~MM/MMwiki/index.php/"; final JButton documentationButton = new JButton(); documentationButton.setText("Help"); documentationButton.setBounds(490, 68, 93, 23); getContentPane().add(documentationButton); documentationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayDocumentation(); } }); } private void displayDocumentation(){ try { ij.plugin.BrowserLauncher.openURL(documentationURLroot_ + libraryDocumentationName_); } catch (IOException e1) { ReportingUtils.showError(e1); } } private void rebuildTable() { devicesPage_.rebuildTable(); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } protected boolean addDevice() { int srows[] = theTree_.getSelectionRows(); if (srows == null) { return false; } if (0 < srows.length) { if (0 < srows[0]) { TreeNodeShowsDeviceAndDescription node = (TreeNodeShowsDeviceAndDescription) theTree_.getLastSelectedPathComponent(); Object[] userData = node.getUserDataArray(); if (null == userData) { // if a folder has one child go ahead and add the childer if(1==node.getLeafCount()) { node = (TreeNodeShowsDeviceAndDescription)node.getChildAt(0); userData = node.getUserDataArray(); if (null==userData) return false; } } boolean validName = false; while (!validName) { String name = JOptionPane.showInputDialog("Please type in the new device name", userData[1].toString()); if (name == null) { return false; } Device newDev = new Device(name, userData[0].toString(), userData[1].toString(), userData[2].toString()); try { model_.addDevice(newDev); validName = true; } catch (MMConfigFileException e) { ReportingUtils.showError(e); return false; } } } } return true; } public void valueChanged(TreeSelectionEvent event) { // update URL for library documentation int srows[] = theTree_.getSelectionRows(); if (null != srows) { if (0 < srows.length) { if (0 < srows[0]) { TreeNodeShowsDeviceAndDescription node = (TreeNodeShowsDeviceAndDescription) theTree_.getLastSelectedPathComponent(); Object uo = node.getUserObject(); if (uo != null) { if (uo.getClass().isArray()) { libraryDocumentationName_ = ((Object[]) uo)[0].toString(); } else { libraryDocumentationName_ = uo.toString(); } } } } } } }
true
true
public AddDeviceDlg(MicroscopeModel model, DevicesPage devicesPage) { super(); setModal(true); setResizable(false); getContentPane().setLayout(null); setTitle("Add Device"); setBounds(400, 100, 596, 529); devicesPage_ = devicesPage; Device allDevs_[] = model.getAvailableDeviceList(); String thisLibrary = ""; DefaultMutableTreeNode root = new DefaultMutableTreeNode("Devices supported by " + "\u00B5" + "Manager"); TreeNodeShowsDeviceAndDescription node = null; for (int idd = 0; idd < allDevs_.length; ++idd) { // assume that the first library doesn't have an empty name! (of course!) if( !allDevs_[idd].isDiscoverable()) { // don't add devices which can be added by their respective master / hub if (0 != thisLibrary.compareTo(allDevs_[idd].getLibrary())) { // create a new node of devices for this library node = new TreeNodeShowsDeviceAndDescription(allDevs_[idd].getLibrary()); root.add(node); thisLibrary = allDevs_[idd].getLibrary(); // remember which library we are processing } Object[] userObject = {allDevs_[idd].getLibrary(), allDevs_[idd].getAdapterName(), allDevs_[idd].getDescription()}; TreeNodeShowsDeviceAndDescription aLeaf = new TreeNodeShowsDeviceAndDescription(""); aLeaf.setUserObject(userObject); node.add(aLeaf); } } // try building a tree theTree_ = new TreeWContextMenu(root, this); theTree_.addTreeSelectionListener(this); // double click should add the device, single click selects row and waits for user to press 'add' MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (2 == e.getClickCount()) { if (addDevice()) { rebuildTable(); } } } }; theTree_.addMouseListener(ml); theTree_.setRootVisible(false); theTree_.setShowsRootHandles(true); final JScrollPane scrollPane = new JScrollPane(theTree_); scrollPane.setBounds(10, 10, 471, 475); getContentPane().add(scrollPane); final JButton addButton = new JButton(); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (addDevice()) { rebuildTable(); } } }); addButton.setText("Add"); addButton.setBounds(490, 10, 93, 23); getContentPane().add(addButton); getRootPane().setDefaultButton(addButton); final JButton doneButton = new JButton(); doneButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); doneButton.setText("Done"); doneButton.setBounds(490, 39, 93, 23); getContentPane().add(doneButton); getRootPane().setDefaultButton(doneButton); model_ = model; //put the URL for the documentation for the selected node into a browser control documentationURLroot_ = "https://valelab.ucsf.edu/~nico/MMwiki/index.php/"; final JButton documentationButton = new JButton(); documentationButton.setText("Help"); documentationButton.setBounds(490, 68, 93, 23); getContentPane().add(documentationButton); documentationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayDocumentation(); } }); }
public AddDeviceDlg(MicroscopeModel model, DevicesPage devicesPage) { super(); setModal(true); setResizable(false); getContentPane().setLayout(null); setTitle("Add Device"); setBounds(400, 100, 596, 529); devicesPage_ = devicesPage; Device allDevs_[] = model.getAvailableDeviceList(); String thisLibrary = ""; DefaultMutableTreeNode root = new DefaultMutableTreeNode("Devices supported by " + "\u00B5" + "Manager"); TreeNodeShowsDeviceAndDescription node = null; for (int idd = 0; idd < allDevs_.length; ++idd) { // assume that the first library doesn't have an empty name! (of course!) if( !allDevs_[idd].isDiscoverable()) { // don't add devices which can be added by their respective master / hub if (0 != thisLibrary.compareTo(allDevs_[idd].getLibrary())) { // create a new node of devices for this library node = new TreeNodeShowsDeviceAndDescription(allDevs_[idd].getLibrary()); root.add(node); thisLibrary = allDevs_[idd].getLibrary(); // remember which library we are processing } Object[] userObject = {allDevs_[idd].getLibrary(), allDevs_[idd].getAdapterName(), allDevs_[idd].getDescription()}; TreeNodeShowsDeviceAndDescription aLeaf = new TreeNodeShowsDeviceAndDescription(""); aLeaf.setUserObject(userObject); node.add(aLeaf); } } // try building a tree theTree_ = new TreeWContextMenu(root, this); theTree_.addTreeSelectionListener(this); // double click should add the device, single click selects row and waits for user to press 'add' MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (2 == e.getClickCount()) { if (addDevice()) { rebuildTable(); } } } }; theTree_.addMouseListener(ml); theTree_.setRootVisible(false); theTree_.setShowsRootHandles(true); final JScrollPane scrollPane = new JScrollPane(theTree_); scrollPane.setBounds(10, 10, 471, 475); getContentPane().add(scrollPane); final JButton addButton = new JButton(); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (addDevice()) { rebuildTable(); } } }); addButton.setText("Add"); addButton.setBounds(490, 10, 93, 23); getContentPane().add(addButton); getRootPane().setDefaultButton(addButton); final JButton doneButton = new JButton(); doneButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); doneButton.setText("Done"); doneButton.setBounds(490, 39, 93, 23); getContentPane().add(doneButton); getRootPane().setDefaultButton(doneButton); model_ = model; //put the URL for the documentation for the selected node into a browser control documentationURLroot_ = "https://valelab.ucsf.edu/~MM/MMwiki/index.php/"; final JButton documentationButton = new JButton(); documentationButton.setText("Help"); documentationButton.setBounds(490, 68, 93, 23); getContentPane().add(documentationButton); documentationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { displayDocumentation(); } }); }
diff --git a/src/main/java/com/pardot/rhombus/cli/commands/RunMigration.java b/src/main/java/com/pardot/rhombus/cli/commands/RunMigration.java index 696b505..6b165fe 100644 --- a/src/main/java/com/pardot/rhombus/cli/commands/RunMigration.java +++ b/src/main/java/com/pardot/rhombus/cli/commands/RunMigration.java @@ -1,98 +1,99 @@ package com.pardot.rhombus.cli.commands; import com.pardot.rhombus.ConnectionManager; import com.pardot.rhombus.cobject.CKeyspaceDefinition; import com.pardot.rhombus.cobject.statement.CQLStatement; import com.pardot.rhombus.cobject.migrations.CObjectMigrationException; import com.pardot.rhombus.util.JsonUtil; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import java.io.IOException; import java.util.List; /** * User: Rob Righter * Date: 10/9/13 */ public class RunMigration extends RcliWithExistingKeyspace { public Options getCommandOptions(){ Options ret = super.getCommandOptions(); Option keyspaceFile = OptionBuilder.withArgName("filename") .hasArg() .withDescription("Filename of the new keyspace definition") .create( "newkeyspacefile" ); Option keyspaceResource = OptionBuilder.withArgName( "filename" ) .hasArg() .withDescription("Resource filename of the new keyspace definition") .create( "newkeyspaceresource" ); Option list = new Option( "l", "Only list the cql for the migration (does not run the migration)" ); ret.addOption(keyspaceFile); ret.addOption(keyspaceResource); return ret; } public boolean executeCommand(CommandLine cl){ boolean ret = false; try { ret = super.executeCommand(cl); } catch (Exception e) { System.out.println("Exception executing command"); e.printStackTrace(); } if(!ret){ return false; } if(!(cl.hasOption("newkeyspacefile") || cl.hasOption("newkeyspaceresource"))){ displayHelpMessage(); return false; } String NewKeyspaceFileName = cl.hasOption("newkeyspacefile") ? cl.getOptionValue("newkeyspacefile") : cl.getOptionValue("newkeyspaceresource"); //make the keyspace definition CKeyspaceDefinition NewkeyDef = null; try{ NewkeyDef = cl.hasOption("newkeyspacefile") ? JsonUtil.objectFromJsonFile(CKeyspaceDefinition.class, CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName) : JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class,CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName); } catch (IOException e){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } if(NewkeyDef == null){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } //now run the migration try{ boolean printOnly = cl.hasOption("l"); return runMigration(this.getConnectionManager(), NewkeyDef, printOnly); } catch (Exception e){ System.out.println("Error encountered while attempting to run migration"); + e.printStackTrace(); return false; } } public boolean runMigration(ConnectionManager cm, CKeyspaceDefinition oldDefinition, boolean printOnly) throws CObjectMigrationException { if(printOnly){ //just print out a list of CQL statements for the migration List<CQLStatement> torun = cm.runMigration(oldDefinition, printOnly); for(CQLStatement c:torun){ System.out.println(c.getQuery()); } } else { //actually run the migration cm.runMigration(oldDefinition, printOnly); } return true; } }
true
true
public boolean executeCommand(CommandLine cl){ boolean ret = false; try { ret = super.executeCommand(cl); } catch (Exception e) { System.out.println("Exception executing command"); e.printStackTrace(); } if(!ret){ return false; } if(!(cl.hasOption("newkeyspacefile") || cl.hasOption("newkeyspaceresource"))){ displayHelpMessage(); return false; } String NewKeyspaceFileName = cl.hasOption("newkeyspacefile") ? cl.getOptionValue("newkeyspacefile") : cl.getOptionValue("newkeyspaceresource"); //make the keyspace definition CKeyspaceDefinition NewkeyDef = null; try{ NewkeyDef = cl.hasOption("newkeyspacefile") ? JsonUtil.objectFromJsonFile(CKeyspaceDefinition.class, CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName) : JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class,CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName); } catch (IOException e){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } if(NewkeyDef == null){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } //now run the migration try{ boolean printOnly = cl.hasOption("l"); return runMigration(this.getConnectionManager(), NewkeyDef, printOnly); } catch (Exception e){ System.out.println("Error encountered while attempting to run migration"); return false; } }
public boolean executeCommand(CommandLine cl){ boolean ret = false; try { ret = super.executeCommand(cl); } catch (Exception e) { System.out.println("Exception executing command"); e.printStackTrace(); } if(!ret){ return false; } if(!(cl.hasOption("newkeyspacefile") || cl.hasOption("newkeyspaceresource"))){ displayHelpMessage(); return false; } String NewKeyspaceFileName = cl.hasOption("newkeyspacefile") ? cl.getOptionValue("newkeyspacefile") : cl.getOptionValue("newkeyspaceresource"); //make the keyspace definition CKeyspaceDefinition NewkeyDef = null; try{ NewkeyDef = cl.hasOption("newkeyspacefile") ? JsonUtil.objectFromJsonFile(CKeyspaceDefinition.class, CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName) : JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class,CKeyspaceDefinition.class.getClassLoader(), NewKeyspaceFileName); } catch (IOException e){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } if(NewkeyDef == null){ System.out.println("Could not parse keyspace file "+NewKeyspaceFileName); return false; } //now run the migration try{ boolean printOnly = cl.hasOption("l"); return runMigration(this.getConnectionManager(), NewkeyDef, printOnly); } catch (Exception e){ System.out.println("Error encountered while attempting to run migration"); e.printStackTrace(); return false; } }
diff --git a/src/main/java/com/goda5/jsmodelgenerator/JavascriptDomainModelGenerator.java b/src/main/java/com/goda5/jsmodelgenerator/JavascriptDomainModelGenerator.java index 3419fa2..00e86db 100644 --- a/src/main/java/com/goda5/jsmodelgenerator/JavascriptDomainModelGenerator.java +++ b/src/main/java/com/goda5/jsmodelgenerator/JavascriptDomainModelGenerator.java @@ -1,41 +1,41 @@ package com.goda5.jsmodelgenerator; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; public class JavascriptDomainModelGenerator { public void generate(Class<?> clazz, File targetJsFolder) throws Exception { StringBuilder b = new StringBuilder(); String prefix = ""; String suffix = ";"; if (clazz.isAnnotationPresent(JavascriptDomainModel.class)) { b.append("function " + clazz.getSimpleName() + "("); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { b.append(prefix); - prefix = ""; + prefix = ", "; b.append(field.getName()); } } b.append(") {" + System.getProperty("line.separator")); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { - if(field.getType().isAssignableFrom(Collection.class)) { - b.append("//Array" + System.getProperty("line.separator")); + if(Collection.class.isAssignableFrom(field.getType())) { + b.append(" //Array" + System.getProperty("line.separator")); } b.append(" this." + field.getName() + " = " + field.getName() + suffix + System.getProperty("line.separator")); } } b.append("}"); if(!targetJsFolder.exists()) { targetJsFolder.mkdirs(); } FileWriter fw = new FileWriter(targetJsFolder + "/" + clazz.getSimpleName() + ".js"); fw.write(b.toString()); fw.close(); } } }
false
true
public void generate(Class<?> clazz, File targetJsFolder) throws Exception { StringBuilder b = new StringBuilder(); String prefix = ""; String suffix = ";"; if (clazz.isAnnotationPresent(JavascriptDomainModel.class)) { b.append("function " + clazz.getSimpleName() + "("); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { b.append(prefix); prefix = ""; b.append(field.getName()); } } b.append(") {" + System.getProperty("line.separator")); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { if(field.getType().isAssignableFrom(Collection.class)) { b.append("//Array" + System.getProperty("line.separator")); } b.append(" this." + field.getName() + " = " + field.getName() + suffix + System.getProperty("line.separator")); } } b.append("}"); if(!targetJsFolder.exists()) { targetJsFolder.mkdirs(); } FileWriter fw = new FileWriter(targetJsFolder + "/" + clazz.getSimpleName() + ".js"); fw.write(b.toString()); fw.close(); } }
public void generate(Class<?> clazz, File targetJsFolder) throws Exception { StringBuilder b = new StringBuilder(); String prefix = ""; String suffix = ";"; if (clazz.isAnnotationPresent(JavascriptDomainModel.class)) { b.append("function " + clazz.getSimpleName() + "("); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { b.append(prefix); prefix = ", "; b.append(field.getName()); } } b.append(") {" + System.getProperty("line.separator")); for(Field field:clazz.getDeclaredFields()) { if(!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { if(Collection.class.isAssignableFrom(field.getType())) { b.append(" //Array" + System.getProperty("line.separator")); } b.append(" this." + field.getName() + " = " + field.getName() + suffix + System.getProperty("line.separator")); } } b.append("}"); if(!targetJsFolder.exists()) { targetJsFolder.mkdirs(); } FileWriter fw = new FileWriter(targetJsFolder + "/" + clazz.getSimpleName() + ".js"); fw.write(b.toString()); fw.close(); } }
diff --git a/nifty-core/src/main/java/de/lessvoid/nifty/layout/manager/AbsolutePositionLayout.java b/nifty-core/src/main/java/de/lessvoid/nifty/layout/manager/AbsolutePositionLayout.java index 89b155a4..301e773b 100644 --- a/nifty-core/src/main/java/de/lessvoid/nifty/layout/manager/AbsolutePositionLayout.java +++ b/nifty-core/src/main/java/de/lessvoid/nifty/layout/manager/AbsolutePositionLayout.java @@ -1,188 +1,188 @@ package de.lessvoid.nifty.layout.manager; import de.lessvoid.nifty.layout.Box; import de.lessvoid.nifty.layout.BoxConstraints; import de.lessvoid.nifty.layout.LayoutPart; import de.lessvoid.nifty.tools.SizeValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; /** * AbsolutePositionLayout doesn't layout things. It just * absolute position it according to the constraints. * * @author void */ public class AbsolutePositionLayout implements LayoutManager { @Nonnull private static final DefaultPostProcess defaultPostProcess = new DefaultPostProcess(); @Nonnull private final PostProcess post; public AbsolutePositionLayout() { this.post = defaultPostProcess; } public AbsolutePositionLayout(@Nonnull final PostProcess post) { this.post = post; } /** * layoutElements. * * @param rootElement @see {@link LayoutManager} * @param elements @see {@link LayoutManager} */ @Override public void layoutElements( @Nullable final LayoutPart rootElement, @Nullable final List<LayoutPart> elements) { // make the params any sense? if (rootElement == null || elements == null || elements.size() == 0) { return; } // get the root box int rootBoxX = getRootBoxX(rootElement); int rootBoxY = getRootBoxY(rootElement); int rootBoxWidth = getRootBoxWidth(rootElement); int rootBoxHeight = getRootBoxHeight(rootElement); // now do the layout for (int i = 0; i < elements.size(); i++) { LayoutPart p = elements.get(i); Box box = p.getBox(); BoxConstraints cons = p.getBoxConstraints(); // makes only sense with constraints given if (cons.getX().hasValue()) { box.setX(rootBoxX + cons.getX().getValueAsInt(rootBoxWidth)); }else{ - box.setX(0);//to handle when a previous setY was done and you want to set back to default + box.setX(0);//to handle when a previous setX was done and you want to set back to default } if (cons.getY().hasValue()) { box.setY(rootBoxY + cons.getY().getValueAsInt(rootBoxHeight)); }else{ box.setY(0); //to handle when a previous setY was done and you want to set back to default } if (cons.getWidth().hasHeightSuffix()) { if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); } box.setWidth(cons.getWidth().getValueAsInt(box.getHeight())); } else if (cons.getHeight().hasWidthSuffix()) { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); } box.setHeight(cons.getHeight().getValueAsInt(box.getWidth())); } else { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); }else{ box.setWidth(0); } if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); }else{ box.setHeight(0); } } post.process(rootBoxX, rootBoxY, rootBoxWidth, rootBoxHeight, box); } } /** * @param children children elements of the root element * @return new calculated SizeValue */ @Nonnull @Override public final SizeValue calculateConstraintWidth( @Nonnull final LayoutPart root, @Nonnull final List<LayoutPart> children) { return SizeValue.def(); } /** * @param children children elements of the root element * @return new calculated SizeValue */ @Nonnull @Override public final SizeValue calculateConstraintHeight( @Nonnull final LayoutPart root, @Nonnull final List<LayoutPart> children) { return SizeValue.def(); } private int getRootBoxX(@Nonnull final LayoutPart root) { return root.getBox().getX() + root.getBoxConstraints().getPaddingLeft().getValueAsInt(root.getBox().getWidth()); } private int getRootBoxY(@Nonnull final LayoutPart root) { return root.getBox().getY() + root.getBoxConstraints().getPaddingTop().getValueAsInt(root.getBox().getHeight()); } private int getRootBoxWidth(@Nonnull final LayoutPart root) { return root.getBox().getWidth() - root.getBoxConstraints().getPaddingLeft().getValueAsInt(root.getBox().getWidth ()) - root.getBoxConstraints().getPaddingRight().getValueAsInt(root.getBox().getWidth()); } private int getRootBoxHeight(@Nonnull final LayoutPart root) { return root.getBox().getHeight() - root.getBoxConstraints().getPaddingTop().getValueAsInt(root.getBox().getHeight ()) - root.getBoxConstraints().getPaddingBottom().getValueAsInt(root.getBox().getHeight()); } public interface PostProcess { void process(int rootBoxX, int rootBoxY, int rootBoxWidth, int rootBoxHeight, @Nonnull Box box); } public static class DefaultPostProcess implements PostProcess { @Override public void process( final int rootBoxX, final int rootBoxY, final int rootBoxWidth, final int rootBoxHeight, @Nonnull final Box box) { } } public static class KeepInsidePostProcess implements PostProcess { @Override public void process( final int rootBoxX, final int rootBoxY, final int rootBoxWidth, final int rootBoxHeight, @Nonnull final Box box) { // first make sure width and height fit into the root box if (box.getWidth() > rootBoxWidth) { box.setWidth(rootBoxWidth); } if (box.getHeight() > rootBoxHeight) { box.setHeight(rootBoxHeight); } // and now make sure the box fits the root box if (box.getX() < rootBoxX) { box.setX(rootBoxX); } if (box.getY() < rootBoxY) { box.setY(rootBoxY); } if ((box.getX() + box.getWidth()) > (rootBoxX + rootBoxWidth)) { box.setX(rootBoxX + rootBoxWidth - box.getWidth()); } if ((box.getY() + box.getHeight()) > (rootBoxY + rootBoxHeight)) { box.setY(rootBoxY + rootBoxHeight - box.getHeight()); } } } }
true
true
public void layoutElements( @Nullable final LayoutPart rootElement, @Nullable final List<LayoutPart> elements) { // make the params any sense? if (rootElement == null || elements == null || elements.size() == 0) { return; } // get the root box int rootBoxX = getRootBoxX(rootElement); int rootBoxY = getRootBoxY(rootElement); int rootBoxWidth = getRootBoxWidth(rootElement); int rootBoxHeight = getRootBoxHeight(rootElement); // now do the layout for (int i = 0; i < elements.size(); i++) { LayoutPart p = elements.get(i); Box box = p.getBox(); BoxConstraints cons = p.getBoxConstraints(); // makes only sense with constraints given if (cons.getX().hasValue()) { box.setX(rootBoxX + cons.getX().getValueAsInt(rootBoxWidth)); }else{ box.setX(0);//to handle when a previous setY was done and you want to set back to default } if (cons.getY().hasValue()) { box.setY(rootBoxY + cons.getY().getValueAsInt(rootBoxHeight)); }else{ box.setY(0); //to handle when a previous setY was done and you want to set back to default } if (cons.getWidth().hasHeightSuffix()) { if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); } box.setWidth(cons.getWidth().getValueAsInt(box.getHeight())); } else if (cons.getHeight().hasWidthSuffix()) { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); } box.setHeight(cons.getHeight().getValueAsInt(box.getWidth())); } else { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); }else{ box.setWidth(0); } if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); }else{ box.setHeight(0); } } post.process(rootBoxX, rootBoxY, rootBoxWidth, rootBoxHeight, box); } }
public void layoutElements( @Nullable final LayoutPart rootElement, @Nullable final List<LayoutPart> elements) { // make the params any sense? if (rootElement == null || elements == null || elements.size() == 0) { return; } // get the root box int rootBoxX = getRootBoxX(rootElement); int rootBoxY = getRootBoxY(rootElement); int rootBoxWidth = getRootBoxWidth(rootElement); int rootBoxHeight = getRootBoxHeight(rootElement); // now do the layout for (int i = 0; i < elements.size(); i++) { LayoutPart p = elements.get(i); Box box = p.getBox(); BoxConstraints cons = p.getBoxConstraints(); // makes only sense with constraints given if (cons.getX().hasValue()) { box.setX(rootBoxX + cons.getX().getValueAsInt(rootBoxWidth)); }else{ box.setX(0);//to handle when a previous setX was done and you want to set back to default } if (cons.getY().hasValue()) { box.setY(rootBoxY + cons.getY().getValueAsInt(rootBoxHeight)); }else{ box.setY(0); //to handle when a previous setY was done and you want to set back to default } if (cons.getWidth().hasHeightSuffix()) { if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); } box.setWidth(cons.getWidth().getValueAsInt(box.getHeight())); } else if (cons.getHeight().hasWidthSuffix()) { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); } box.setHeight(cons.getHeight().getValueAsInt(box.getWidth())); } else { if (cons.getWidth().hasValue()) { box.setWidth(cons.getWidth().getValueAsInt(rootBoxWidth)); }else{ box.setWidth(0); } if (cons.getHeight().hasValue()) { box.setHeight(cons.getHeight().getValueAsInt(rootBoxHeight)); }else{ box.setHeight(0); } } post.process(rootBoxX, rootBoxY, rootBoxWidth, rootBoxHeight, box); } }
diff --git a/TaxonDNA/com/ggvaidya/TaxonDNA/DNA/formats/GenBankFile.java b/TaxonDNA/com/ggvaidya/TaxonDNA/DNA/formats/GenBankFile.java index 8e90517..765f3bb 100644 --- a/TaxonDNA/com/ggvaidya/TaxonDNA/DNA/formats/GenBankFile.java +++ b/TaxonDNA/com/ggvaidya/TaxonDNA/DNA/formats/GenBankFile.java @@ -1,628 +1,626 @@ /** * Allows you to read and write files in GenBank format. * This is the coolest, because just about all the information * is readily available and easily accessible. On the down * side, it's a lot of parsing. * */ /* TaxonDNA Copyright (C) 2006 Gaurav Vaidya 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.ggvaidya.TaxonDNA.DNA.formats; import java.io.*; import java.util.*; import java.util.regex.*; import com.ggvaidya.TaxonDNA.Common.*; import com.ggvaidya.TaxonDNA.DNA.*; public class GenBankFile implements FormatHandler, Testable { /** Creates a GenBankFile format handler */ public GenBankFile() {} /** Returns the short name of this handler, which is "GenBank Flat File format" */ public String getShortName() { return "GenBank format"; } /** Returns the full name of this handler*/ public String getFullName() { return "GenBank format, including being able to select specific coding segments"; } /** * Writes the sequence list 'list' into the File 'file', in GenBank format. * * Not currently implemented; it throws an exception if you try, etc. * * @throws IOException if it can't create or write the file */ public void writeFile(File file, SequenceList list, DelayCallback delay) throws IOException, DelayAbortedException { throw new IOException("Writing GenBank files is not currently supported, sorry!"); } /** * Could 'file' be a GenBank file? That is the question. We 'test' for GenBank files * by looking for a 'LOCUS' as the first non-blank line of the file. */ public boolean mightBe(File file) { try { BufferedReader read = new BufferedReader(new FileReader(file)); String line; while((line = read.readLine()) != null) { line = line.trim(); if(!line.equals("")) { if(line.length() >= 5 && line.toUpperCase().substring(0,5).equals("LOCUS")) return true; else { return false; } } } } catch(IOException e) { } return false; } /** * Read a GenBank file (from 'file') and return a SequenceList containing all the entries. * @throws FormatException if anything is in any whatsoeverway wrong with this format. * @throws IOException if there was a problem accessing or reading the file specified. * @throws DelayAbortedException if the user aborted the DelayCallback. */ public SequenceList readFile(File file, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { SequenceList list = new SequenceList(); appendFromFile(list, file, delay); return list; } private String reverseComplement(String str) { // we flip' and complement char[] data = str.toUpperCase().toCharArray(); char[] result = new char[data.length]; for(int x = 0; x < data.length; x++) { char ch = data[x]; // complement 'ch' ch = Sequence.complement(ch); // put it into 'result' in reverse result[data.length - 1 - x] = ch; } return new String(result); } /* * Note: the following function uses the term 'CDS' a LOT. This is because I thought * I'd be using the CDS information. For our purposes, however, the 'gene' information * is a lot easier to deal with, so we're REALLY using that. Sorry about the confusion. */ public void appendFromFile(SequenceList list, File file, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { list.lock(); if(delay != null) delay.begin(); Hashtable hash_genes = new Hashtable(); Hashtable hash_cds = new Hashtable(); // Hash of String(seq full name) to (Hash of // String(cds gene name) to String(coordinates // in a custom "extractable" format) // // Sigh. // boolean sequence_mode = false; // are we reading in a sequence? boolean features_mode = false; // are we in the 'features' section? try { BufferedReader reader = new BufferedReader(new FileReader(file)); // There is an easier way to do this (using RandomAccessFile to jump to the end, etc.) // but I'm not sure it's more efficient. int total_lines = 0; while((reader.readLine() != null)) { total_lines++; } reader = new BufferedReader(new FileReader(file)); // And now, back to your regularly scheduled program. Pattern p_sequence = Pattern.compile("^\\s*\\d+\\s+([\\w\\s]+)\\s*$"); Pattern p_version = Pattern.compile("^VERSION\\s+(\\w{2}(?:[_])*\\d{6}\\.\\d+)\\s+GI:(\\d+)\\s*$"); Pattern p_gi = Pattern.compile("^VERSION\\s+.+\\s+GI:(\\d+)\\s*$"); Pattern p_organism = Pattern.compile("^\\s*ORGANISM\\s+(.+)\\s*$"); Pattern p_CDS = Pattern.compile("^\\s*CDS\\s+(complement\\()*([<\\d]+)\\.\\.([\\d>]+)\\)*\\s*$", Pattern.CASE_INSENSITIVE); Pattern p_CDS_gene = Pattern.compile("^\\s*/gene=\"(.*)\"\\s*$"); Pattern p_CDS_product = Pattern.compile("^\\s*/product=\"(.*)\"\\s*$"); String currentName = ""; StringBuffer currentSequence = new StringBuffer(); Hashtable currentCDSs = new Hashtable(); int line_no = 1; int interval = total_lines / 100; if(interval == 0) interval = 1; while(reader.ready()) { String line = reader.readLine().trim(); // little formatting stuff if(line == null) break; // handle 'delay' if(delay != null && line_no % interval == 0) try { delay.delay(line_no, total_lines); } catch(DelayAbortedException e) { // cleanup will be handled by the 'finally' at the end of this method return; } line_no++; if(line.equals("")) continue; if(line.equals("//")) { // end of record! Sequence seq = null; try { seq = new Sequence(currentName.trim(), currentSequence.toString()); list.add(seq); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } if(!currentCDSs.isEmpty()) hash_cds.put(seq, currentCDSs); currentName = ""; currentSequence = new StringBuffer(); currentCDSs = new Hashtable(); sequence_mode = false; features_mode = false; continue; } if(sequence_mode) { Matcher m = p_sequence.matcher(line); if(m.matches()) { String sequence = m.group(1); // sequence includes spaces, which need to be removed. sequence = sequence.replaceAll("\\s", ""); currentSequence.append(sequence); } continue; } else { Matcher m; // we are in no 'mode', as such // try to find a match for the 'ORGANISM' m = p_organism.matcher(line); if(m.matches()) { String organism = m.group(1); currentName = organism + " " + currentName; continue; } // try to find a match for the 'VERSION' line m = p_version.matcher(line); if(m.matches()) { String gb = m.group(1); String gi = m.group(2); currentName = currentName + " gi|" + gi + "|gb|" + gb + "|"; continue; } // if the whole "VERSION" reg-ex didn't work, // (i.e. we couldn't understand the accession number) // we fall back to using a basic "how-much-is-that-GI-at-the-end-of-the-line" one. m = p_gi.matcher(line); if(m.matches()) { String gi = m.group(1); currentName = currentName + " gi|" + gi + "|"; continue; } } if(features_mode) { // we handle feature specific stuff here. Matcher m; // I spy with my little eye ... a CDS entry! m = p_CDS.matcher(line); if(m.matches()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); String my_line = ""; boolean open_quotes = false; while((my_line = reader.readLine().trim()) != null) { String gene = null; if(open_quotes) { // if open_quotes, we have an unclosed '"' running // around. So we ignore EVERYTHING until we close // it. if(my_line.indexOf('"') != -1) { // it's here! open_quotes = false; } // in any case, we continue; this line is a quote infestation etc. continue; } if(my_line.length() == 0) { // this will happen if it's an empty line after the features. // unorthodox, but flexibility is good for you. continue; } if(my_line.charAt(0) != '/') { // if it's not a '/', we are OUT of this feature // aiyee! // // It should be noted that a GOTO would be // *brilliant* right about now. line = my_line; break; } if(my_line.indexOf('"') != -1) { // if there's a '"' in this line int count = 0; for(int x = 0; x < my_line.length(); x++) { if(my_line.charAt(x) == '"') count++; } if(count % 2 == 0) { // even number // ignore } else { // quote mode! open_quotes = true; } } // look for '/gene' m = p_CDS_gene.matcher(my_line); if(m.matches()) { gene = m.group(1); } // look for '/product' m = p_CDS_product.matcher(my_line); if(m.matches()) { gene = m.group(1); } // if we have EITHER a /gene or a /product // on this line, we can do our // adding-the-entry magick. if(gene != null) { // watch out for the error case: two identically // named 'features' in one sequence! if(currentCDSs.get(gene) != null) { System.err.println("Warning: GenBankFile: '" + currentName + "' has two features named " + gene + ", using the last one."); } // count the gene/product name //System.err.println("Adding " + gene + " to list"); if(hash_genes.get(gene) != null) hash_genes.put(gene, new Integer(((Integer)hash_genes.get(gene)).intValue() + 1)); else hash_genes.put(gene, new Integer(1)); // set up the cdsString for this particular gene; we'll store it in a hash shortly. String cdsString = ""; if(complement == null) // non-complement sequence cdsString = " [taxondna_CDS:" + from + ":" + to + "]"; else cdsString = " [taxondna_CDS_complement:" + from + ":" + to + "]"; // store the cdsString into the currentCDSs hash. // This will be transfered to hash_cds once we hit the end of this sequence. currentCDSs.put(gene, cdsString); } } if(open_quotes) throw new FormatException("Double quotes not closed properly in file!"); } } if(line.equals("ORIGIN")) { // begin sequence information! sequence_mode = true; continue; } if(line.length() > 8 && line.substring(0,8).equals("FEATURES")) { features_mode = true; continue; } } // Okay, so we're out, BUT // what about anything left in currentName/currentSequence?! if(!currentSequence.toString().equals("")) { try { list.add(new Sequence(currentName, currentSequence.toString())); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } } // Hehe, now the fun REALLY starts // // Translation: Now that we have "imported" the entire list, we need to get // rid of all the CDS tags. The Right Way of doing that is // determining which CDSs to keep, and which to remove, and // then do the chop-chop on the list itself. // We need UI control again. if(delay != null) delay.end(); delay = null; // Now here's the dodgy thing // We are a data-only part of the program, so we're not really supposed // to interact with the user at ALL, except through exceptions or the // like. // // The best compromise I can come up with in my present caffeine-deprived // state is, we have a corresponding Module called CDScutter, which we // will directly invoke. CDScutter will handle the interaction, the CDS // cutting, etc. // // It's not much, but it'll have to do. // Class class_cdsexaminer = null; boolean keep_sequences_without_CDS = false; try { - class_cdsexaminer = ClassLoader.getSystemClassLoader().loadClass("com.ggvaidya.TaxonDNA.Modules.CDSExaminer"); + class_cdsexaminer = com.ggvaidya.TaxonDNA.Modules.CDSExaminer.class; Class[] signature = new Class[2]; signature[0] = String.class; signature[1] = Hashtable.class; Object[] args = new Object[2]; args[0] = "genes"; args[1] = (Object) hash_genes; args = (Object[]) class_cdsexaminer.getDeclaredMethod("checkHashOfCDSs", signature).invoke(null, args); keep_sequences_without_CDS = ((Boolean)args[0]).booleanValue(); hash_genes = ((Hashtable)args[1]); - } catch(ClassNotFoundException e) { - throw new FormatException("An essential component of TaxonDNA (the CDS Examiner) was not found. Please ensure that your TaxonDNA setup is not missing any files.\n\nThe technical description is as follows: " + e); } catch(Exception e) { throw new FormatException("There have been strange changes in the CDS Examiner since installation. This is probably a programming error. Please inform the programmers at [http://taxondna.sf.net/].\n\nThe technical description is as follows: " + e); } // Now, we run through the list, deleting any [taxondna_cds...] tags // *Except* those mentioned in the hash_genes as returned to us by CDSExaminer Iterator i = list.iterator(); Pattern p_taxondna_cds = Pattern.compile("\\[taxondna_CDS(_complement)*:(.+?):(.+?)\\]"); while(i.hasNext()) { Sequence seq = (Sequence)i.next(); Hashtable cdss = (Hashtable) hash_cds.get(seq); boolean fixed_one_in_this_sequence = false; if(cdss != null) { Iterator iCDS = cdss.keySet().iterator(); while(iCDS.hasNext()) { String gene = (String)iCDS.next(); String code = (String)cdss.get(gene); Matcher m = p_taxondna_cds.matcher(code); if(m.find()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); // is this gene in the list? if(!fixed_one_in_this_sequence && hash_genes.get(gene) != null) { int i_from = 0; int i_to = 0; if(from.indexOf("<") != -1) { i_from = Integer.parseInt(from.substring(from.indexOf("<")+1)); } else i_from = Integer.parseInt(from); if(to.indexOf(">") != -1) { i_to = Integer.parseInt(to.substring(to.indexOf(">")+1)); } else i_to = Integer.parseInt(to); int old_length = seq.getLength(); String new_sequence = seq.getSequence().substring(i_from - 1, i_to); if(complement != null) new_sequence = reverseComplement(new_sequence); try { seq.changeSequence(new_sequence); } catch(SequenceException e) { throw new FormatException("I couldn't cut sequence " + seq + "; please check that the CDS of " + gene + " from " + from + " to " + to + " is actually valid."); } String complementary_str = ""; if(complement != null) complementary_str = " complementary"; seq.changeName(seq.getFullName() + " (cut '" + gene + "' from " + from + " to " + to + complementary_str + "; the sequence used to be " + old_length + " bp long)"); // we can't find more than one gene in any given sequence - sorry! fixed_one_in_this_sequence = true; } } } } if(!keep_sequences_without_CDS && !fixed_one_in_this_sequence) { // we couldn't find a match in this sequence! // Best get rid of the Sequence entirely? i.remove(); } } } finally { if(delay != null) delay.end(); list.setFile(file); list.setFormatHandler(this); list.unlock(); } } /** * Tests the GenBankFile class extensively so that bugs don't creep in. */ public void test(TestController testMaster, DelayCallback delay) throws DelayAbortedException { testMaster.begin("DNA.formats.GenBankFile"); File coi_gb = testMaster.file("DNA/formats/genbankfile/coii.gb"); File coi_fasta = testMaster.file("DNA/formats/genbankfile/coii.fasta"); GenBankFile gbf = new GenBankFile(); testMaster.beginTest("Recognize a file as being a GenBank file"); if(gbf.mightBe(coi_gb)) try { FastaFile ff = new FastaFile(); int count = gbf.readFile(coi_gb, delay).count(); int real_count = ff.readFile(coi_fasta, delay).count(); if(count == real_count) testMaster.succeeded(); else testMaster.failed("I got back " + count + " sequences instead of " + real_count + " (from the FASTA file)"); } catch(IOException e) { testMaster.failed("There was an IOException reading a file: " + e); } catch(SequenceException e) { testMaster.failed("There was a SequenceException reading a file: " + e); } catch(FormatException e) { testMaster.failed("There was a FormatException reading a file: " + e); } else testMaster.failed(coi_gb + " was not recognized as a GenBank file"); /* testMaster.beginTest("Recognize a file generated by MEGA export from a FASTA file as a MEGA file"); File test2 = testMaster.file("DNA/formats/megafile/test_mega2.txt"); if(ff.mightBe(test2)) try { if(ff.readFile(test2, delay).count() == 10) testMaster.succeeded(); } catch(IOException e) { testMaster.failed("There was an IOException reading " + test2 + ": " + e); } catch(SequenceException e) { testMaster.failed("There was a SequenceException reading " + test2 + ": " + e); } catch(FormatException e) { testMaster.failed("There was a FormatException reading " + test2 + ": " + e); } else testMaster.failed(test + " was not recognized as a MEGA file"); testMaster.beginTest("Recognize other files as being non-MEGA"); File notfasta = testMaster.file("DNA/formats/megafile/test_nonmega1.txt"); if(notfasta.canRead() && !ff.mightBe(notfasta)) testMaster.succeeded(); else testMaster.failed(notfasta + " was incorrectly identified as a MEGA file"); // err, skip this last test // IT DOESNT WORK testMaster.done(); return; */ /* testMaster.beginTest("Write out a MEGA file, then read it back in (twice!)"); File input = testMaster.file("DNA/formats/megafile/test_megacopy.txt"); File success = testMaster.file("DNA/formats/megafile/test_megacopy_success.txt"); File output = testMaster.tempfile(); File output2 = testMaster.tempfile(); try { SequenceList list = ff.readFile(input, delay); ff.writeFile(output, list, delay); list = ff.readFile(output, delay); ff.writeFile(output2, list, delay); if(testMaster.isIdentical(success, output2)) testMaster.succeeded(); else testMaster.failed( "I read a MEGA file from " + input + ", then wrote it to '" + output2 + "', but they aren't identical" ); } catch(IOException e) { testMaster.failed( "I read a MEGA file from " + input + ", then wrote it to '" + output2 + "', but I got an IOException: " + e ); } catch(SequenceException e) { testMaster.failed( "I read a MEGA file from " + input + ", then wrote it to '" + output2 + "', but I got a SequenceListException: " + e ); } catch(FormatException e) { testMaster.failed( "I read a MEGA file from " + input + ", then wrote it to '" + output2 + "', but I got a SequenceListException: " + e ); } testMaster.done(); */ } }
false
true
public void appendFromFile(SequenceList list, File file, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { list.lock(); if(delay != null) delay.begin(); Hashtable hash_genes = new Hashtable(); Hashtable hash_cds = new Hashtable(); // Hash of String(seq full name) to (Hash of // String(cds gene name) to String(coordinates // in a custom "extractable" format) // // Sigh. // boolean sequence_mode = false; // are we reading in a sequence? boolean features_mode = false; // are we in the 'features' section? try { BufferedReader reader = new BufferedReader(new FileReader(file)); // There is an easier way to do this (using RandomAccessFile to jump to the end, etc.) // but I'm not sure it's more efficient. int total_lines = 0; while((reader.readLine() != null)) { total_lines++; } reader = new BufferedReader(new FileReader(file)); // And now, back to your regularly scheduled program. Pattern p_sequence = Pattern.compile("^\\s*\\d+\\s+([\\w\\s]+)\\s*$"); Pattern p_version = Pattern.compile("^VERSION\\s+(\\w{2}(?:[_])*\\d{6}\\.\\d+)\\s+GI:(\\d+)\\s*$"); Pattern p_gi = Pattern.compile("^VERSION\\s+.+\\s+GI:(\\d+)\\s*$"); Pattern p_organism = Pattern.compile("^\\s*ORGANISM\\s+(.+)\\s*$"); Pattern p_CDS = Pattern.compile("^\\s*CDS\\s+(complement\\()*([<\\d]+)\\.\\.([\\d>]+)\\)*\\s*$", Pattern.CASE_INSENSITIVE); Pattern p_CDS_gene = Pattern.compile("^\\s*/gene=\"(.*)\"\\s*$"); Pattern p_CDS_product = Pattern.compile("^\\s*/product=\"(.*)\"\\s*$"); String currentName = ""; StringBuffer currentSequence = new StringBuffer(); Hashtable currentCDSs = new Hashtable(); int line_no = 1; int interval = total_lines / 100; if(interval == 0) interval = 1; while(reader.ready()) { String line = reader.readLine().trim(); // little formatting stuff if(line == null) break; // handle 'delay' if(delay != null && line_no % interval == 0) try { delay.delay(line_no, total_lines); } catch(DelayAbortedException e) { // cleanup will be handled by the 'finally' at the end of this method return; } line_no++; if(line.equals("")) continue; if(line.equals("//")) { // end of record! Sequence seq = null; try { seq = new Sequence(currentName.trim(), currentSequence.toString()); list.add(seq); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } if(!currentCDSs.isEmpty()) hash_cds.put(seq, currentCDSs); currentName = ""; currentSequence = new StringBuffer(); currentCDSs = new Hashtable(); sequence_mode = false; features_mode = false; continue; } if(sequence_mode) { Matcher m = p_sequence.matcher(line); if(m.matches()) { String sequence = m.group(1); // sequence includes spaces, which need to be removed. sequence = sequence.replaceAll("\\s", ""); currentSequence.append(sequence); } continue; } else { Matcher m; // we are in no 'mode', as such // try to find a match for the 'ORGANISM' m = p_organism.matcher(line); if(m.matches()) { String organism = m.group(1); currentName = organism + " " + currentName; continue; } // try to find a match for the 'VERSION' line m = p_version.matcher(line); if(m.matches()) { String gb = m.group(1); String gi = m.group(2); currentName = currentName + " gi|" + gi + "|gb|" + gb + "|"; continue; } // if the whole "VERSION" reg-ex didn't work, // (i.e. we couldn't understand the accession number) // we fall back to using a basic "how-much-is-that-GI-at-the-end-of-the-line" one. m = p_gi.matcher(line); if(m.matches()) { String gi = m.group(1); currentName = currentName + " gi|" + gi + "|"; continue; } } if(features_mode) { // we handle feature specific stuff here. Matcher m; // I spy with my little eye ... a CDS entry! m = p_CDS.matcher(line); if(m.matches()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); String my_line = ""; boolean open_quotes = false; while((my_line = reader.readLine().trim()) != null) { String gene = null; if(open_quotes) { // if open_quotes, we have an unclosed '"' running // around. So we ignore EVERYTHING until we close // it. if(my_line.indexOf('"') != -1) { // it's here! open_quotes = false; } // in any case, we continue; this line is a quote infestation etc. continue; } if(my_line.length() == 0) { // this will happen if it's an empty line after the features. // unorthodox, but flexibility is good for you. continue; } if(my_line.charAt(0) != '/') { // if it's not a '/', we are OUT of this feature // aiyee! // // It should be noted that a GOTO would be // *brilliant* right about now. line = my_line; break; } if(my_line.indexOf('"') != -1) { // if there's a '"' in this line int count = 0; for(int x = 0; x < my_line.length(); x++) { if(my_line.charAt(x) == '"') count++; } if(count % 2 == 0) { // even number // ignore } else { // quote mode! open_quotes = true; } } // look for '/gene' m = p_CDS_gene.matcher(my_line); if(m.matches()) { gene = m.group(1); } // look for '/product' m = p_CDS_product.matcher(my_line); if(m.matches()) { gene = m.group(1); } // if we have EITHER a /gene or a /product // on this line, we can do our // adding-the-entry magick. if(gene != null) { // watch out for the error case: two identically // named 'features' in one sequence! if(currentCDSs.get(gene) != null) { System.err.println("Warning: GenBankFile: '" + currentName + "' has two features named " + gene + ", using the last one."); } // count the gene/product name //System.err.println("Adding " + gene + " to list"); if(hash_genes.get(gene) != null) hash_genes.put(gene, new Integer(((Integer)hash_genes.get(gene)).intValue() + 1)); else hash_genes.put(gene, new Integer(1)); // set up the cdsString for this particular gene; we'll store it in a hash shortly. String cdsString = ""; if(complement == null) // non-complement sequence cdsString = " [taxondna_CDS:" + from + ":" + to + "]"; else cdsString = " [taxondna_CDS_complement:" + from + ":" + to + "]"; // store the cdsString into the currentCDSs hash. // This will be transfered to hash_cds once we hit the end of this sequence. currentCDSs.put(gene, cdsString); } } if(open_quotes) throw new FormatException("Double quotes not closed properly in file!"); } } if(line.equals("ORIGIN")) { // begin sequence information! sequence_mode = true; continue; } if(line.length() > 8 && line.substring(0,8).equals("FEATURES")) { features_mode = true; continue; } } // Okay, so we're out, BUT // what about anything left in currentName/currentSequence?! if(!currentSequence.toString().equals("")) { try { list.add(new Sequence(currentName, currentSequence.toString())); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } } // Hehe, now the fun REALLY starts // // Translation: Now that we have "imported" the entire list, we need to get // rid of all the CDS tags. The Right Way of doing that is // determining which CDSs to keep, and which to remove, and // then do the chop-chop on the list itself. // We need UI control again. if(delay != null) delay.end(); delay = null; // Now here's the dodgy thing // We are a data-only part of the program, so we're not really supposed // to interact with the user at ALL, except through exceptions or the // like. // // The best compromise I can come up with in my present caffeine-deprived // state is, we have a corresponding Module called CDScutter, which we // will directly invoke. CDScutter will handle the interaction, the CDS // cutting, etc. // // It's not much, but it'll have to do. // Class class_cdsexaminer = null; boolean keep_sequences_without_CDS = false; try { class_cdsexaminer = ClassLoader.getSystemClassLoader().loadClass("com.ggvaidya.TaxonDNA.Modules.CDSExaminer"); Class[] signature = new Class[2]; signature[0] = String.class; signature[1] = Hashtable.class; Object[] args = new Object[2]; args[0] = "genes"; args[1] = (Object) hash_genes; args = (Object[]) class_cdsexaminer.getDeclaredMethod("checkHashOfCDSs", signature).invoke(null, args); keep_sequences_without_CDS = ((Boolean)args[0]).booleanValue(); hash_genes = ((Hashtable)args[1]); } catch(ClassNotFoundException e) { throw new FormatException("An essential component of TaxonDNA (the CDS Examiner) was not found. Please ensure that your TaxonDNA setup is not missing any files.\n\nThe technical description is as follows: " + e); } catch(Exception e) { throw new FormatException("There have been strange changes in the CDS Examiner since installation. This is probably a programming error. Please inform the programmers at [http://taxondna.sf.net/].\n\nThe technical description is as follows: " + e); } // Now, we run through the list, deleting any [taxondna_cds...] tags // *Except* those mentioned in the hash_genes as returned to us by CDSExaminer Iterator i = list.iterator(); Pattern p_taxondna_cds = Pattern.compile("\\[taxondna_CDS(_complement)*:(.+?):(.+?)\\]"); while(i.hasNext()) { Sequence seq = (Sequence)i.next(); Hashtable cdss = (Hashtable) hash_cds.get(seq); boolean fixed_one_in_this_sequence = false; if(cdss != null) { Iterator iCDS = cdss.keySet().iterator(); while(iCDS.hasNext()) { String gene = (String)iCDS.next(); String code = (String)cdss.get(gene); Matcher m = p_taxondna_cds.matcher(code); if(m.find()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); // is this gene in the list? if(!fixed_one_in_this_sequence && hash_genes.get(gene) != null) { int i_from = 0; int i_to = 0; if(from.indexOf("<") != -1) { i_from = Integer.parseInt(from.substring(from.indexOf("<")+1)); } else i_from = Integer.parseInt(from); if(to.indexOf(">") != -1) { i_to = Integer.parseInt(to.substring(to.indexOf(">")+1)); } else i_to = Integer.parseInt(to); int old_length = seq.getLength(); String new_sequence = seq.getSequence().substring(i_from - 1, i_to); if(complement != null) new_sequence = reverseComplement(new_sequence); try { seq.changeSequence(new_sequence); } catch(SequenceException e) { throw new FormatException("I couldn't cut sequence " + seq + "; please check that the CDS of " + gene + " from " + from + " to " + to + " is actually valid."); } String complementary_str = ""; if(complement != null) complementary_str = " complementary"; seq.changeName(seq.getFullName() + " (cut '" + gene + "' from " + from + " to " + to + complementary_str + "; the sequence used to be " + old_length + " bp long)"); // we can't find more than one gene in any given sequence - sorry! fixed_one_in_this_sequence = true; } } } } if(!keep_sequences_without_CDS && !fixed_one_in_this_sequence) { // we couldn't find a match in this sequence! // Best get rid of the Sequence entirely? i.remove(); } } } finally { if(delay != null) delay.end(); list.setFile(file); list.setFormatHandler(this); list.unlock(); } }
public void appendFromFile(SequenceList list, File file, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { list.lock(); if(delay != null) delay.begin(); Hashtable hash_genes = new Hashtable(); Hashtable hash_cds = new Hashtable(); // Hash of String(seq full name) to (Hash of // String(cds gene name) to String(coordinates // in a custom "extractable" format) // // Sigh. // boolean sequence_mode = false; // are we reading in a sequence? boolean features_mode = false; // are we in the 'features' section? try { BufferedReader reader = new BufferedReader(new FileReader(file)); // There is an easier way to do this (using RandomAccessFile to jump to the end, etc.) // but I'm not sure it's more efficient. int total_lines = 0; while((reader.readLine() != null)) { total_lines++; } reader = new BufferedReader(new FileReader(file)); // And now, back to your regularly scheduled program. Pattern p_sequence = Pattern.compile("^\\s*\\d+\\s+([\\w\\s]+)\\s*$"); Pattern p_version = Pattern.compile("^VERSION\\s+(\\w{2}(?:[_])*\\d{6}\\.\\d+)\\s+GI:(\\d+)\\s*$"); Pattern p_gi = Pattern.compile("^VERSION\\s+.+\\s+GI:(\\d+)\\s*$"); Pattern p_organism = Pattern.compile("^\\s*ORGANISM\\s+(.+)\\s*$"); Pattern p_CDS = Pattern.compile("^\\s*CDS\\s+(complement\\()*([<\\d]+)\\.\\.([\\d>]+)\\)*\\s*$", Pattern.CASE_INSENSITIVE); Pattern p_CDS_gene = Pattern.compile("^\\s*/gene=\"(.*)\"\\s*$"); Pattern p_CDS_product = Pattern.compile("^\\s*/product=\"(.*)\"\\s*$"); String currentName = ""; StringBuffer currentSequence = new StringBuffer(); Hashtable currentCDSs = new Hashtable(); int line_no = 1; int interval = total_lines / 100; if(interval == 0) interval = 1; while(reader.ready()) { String line = reader.readLine().trim(); // little formatting stuff if(line == null) break; // handle 'delay' if(delay != null && line_no % interval == 0) try { delay.delay(line_no, total_lines); } catch(DelayAbortedException e) { // cleanup will be handled by the 'finally' at the end of this method return; } line_no++; if(line.equals("")) continue; if(line.equals("//")) { // end of record! Sequence seq = null; try { seq = new Sequence(currentName.trim(), currentSequence.toString()); list.add(seq); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } if(!currentCDSs.isEmpty()) hash_cds.put(seq, currentCDSs); currentName = ""; currentSequence = new StringBuffer(); currentCDSs = new Hashtable(); sequence_mode = false; features_mode = false; continue; } if(sequence_mode) { Matcher m = p_sequence.matcher(line); if(m.matches()) { String sequence = m.group(1); // sequence includes spaces, which need to be removed. sequence = sequence.replaceAll("\\s", ""); currentSequence.append(sequence); } continue; } else { Matcher m; // we are in no 'mode', as such // try to find a match for the 'ORGANISM' m = p_organism.matcher(line); if(m.matches()) { String organism = m.group(1); currentName = organism + " " + currentName; continue; } // try to find a match for the 'VERSION' line m = p_version.matcher(line); if(m.matches()) { String gb = m.group(1); String gi = m.group(2); currentName = currentName + " gi|" + gi + "|gb|" + gb + "|"; continue; } // if the whole "VERSION" reg-ex didn't work, // (i.e. we couldn't understand the accession number) // we fall back to using a basic "how-much-is-that-GI-at-the-end-of-the-line" one. m = p_gi.matcher(line); if(m.matches()) { String gi = m.group(1); currentName = currentName + " gi|" + gi + "|"; continue; } } if(features_mode) { // we handle feature specific stuff here. Matcher m; // I spy with my little eye ... a CDS entry! m = p_CDS.matcher(line); if(m.matches()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); String my_line = ""; boolean open_quotes = false; while((my_line = reader.readLine().trim()) != null) { String gene = null; if(open_quotes) { // if open_quotes, we have an unclosed '"' running // around. So we ignore EVERYTHING until we close // it. if(my_line.indexOf('"') != -1) { // it's here! open_quotes = false; } // in any case, we continue; this line is a quote infestation etc. continue; } if(my_line.length() == 0) { // this will happen if it's an empty line after the features. // unorthodox, but flexibility is good for you. continue; } if(my_line.charAt(0) != '/') { // if it's not a '/', we are OUT of this feature // aiyee! // // It should be noted that a GOTO would be // *brilliant* right about now. line = my_line; break; } if(my_line.indexOf('"') != -1) { // if there's a '"' in this line int count = 0; for(int x = 0; x < my_line.length(); x++) { if(my_line.charAt(x) == '"') count++; } if(count % 2 == 0) { // even number // ignore } else { // quote mode! open_quotes = true; } } // look for '/gene' m = p_CDS_gene.matcher(my_line); if(m.matches()) { gene = m.group(1); } // look for '/product' m = p_CDS_product.matcher(my_line); if(m.matches()) { gene = m.group(1); } // if we have EITHER a /gene or a /product // on this line, we can do our // adding-the-entry magick. if(gene != null) { // watch out for the error case: two identically // named 'features' in one sequence! if(currentCDSs.get(gene) != null) { System.err.println("Warning: GenBankFile: '" + currentName + "' has two features named " + gene + ", using the last one."); } // count the gene/product name //System.err.println("Adding " + gene + " to list"); if(hash_genes.get(gene) != null) hash_genes.put(gene, new Integer(((Integer)hash_genes.get(gene)).intValue() + 1)); else hash_genes.put(gene, new Integer(1)); // set up the cdsString for this particular gene; we'll store it in a hash shortly. String cdsString = ""; if(complement == null) // non-complement sequence cdsString = " [taxondna_CDS:" + from + ":" + to + "]"; else cdsString = " [taxondna_CDS_complement:" + from + ":" + to + "]"; // store the cdsString into the currentCDSs hash. // This will be transfered to hash_cds once we hit the end of this sequence. currentCDSs.put(gene, cdsString); } } if(open_quotes) throw new FormatException("Double quotes not closed properly in file!"); } } if(line.equals("ORIGIN")) { // begin sequence information! sequence_mode = true; continue; } if(line.length() > 8 && line.substring(0,8).equals("FEATURES")) { features_mode = true; continue; } } // Okay, so we're out, BUT // what about anything left in currentName/currentSequence?! if(!currentSequence.toString().equals("")) { try { list.add(new Sequence(currentName, currentSequence.toString())); } catch(SequenceException e) { throw new FormatException("There was an error while processing the sequence '" + currentName + "' on line " + line_no + ": " + e); } } // Hehe, now the fun REALLY starts // // Translation: Now that we have "imported" the entire list, we need to get // rid of all the CDS tags. The Right Way of doing that is // determining which CDSs to keep, and which to remove, and // then do the chop-chop on the list itself. // We need UI control again. if(delay != null) delay.end(); delay = null; // Now here's the dodgy thing // We are a data-only part of the program, so we're not really supposed // to interact with the user at ALL, except through exceptions or the // like. // // The best compromise I can come up with in my present caffeine-deprived // state is, we have a corresponding Module called CDScutter, which we // will directly invoke. CDScutter will handle the interaction, the CDS // cutting, etc. // // It's not much, but it'll have to do. // Class class_cdsexaminer = null; boolean keep_sequences_without_CDS = false; try { class_cdsexaminer = com.ggvaidya.TaxonDNA.Modules.CDSExaminer.class; Class[] signature = new Class[2]; signature[0] = String.class; signature[1] = Hashtable.class; Object[] args = new Object[2]; args[0] = "genes"; args[1] = (Object) hash_genes; args = (Object[]) class_cdsexaminer.getDeclaredMethod("checkHashOfCDSs", signature).invoke(null, args); keep_sequences_without_CDS = ((Boolean)args[0]).booleanValue(); hash_genes = ((Hashtable)args[1]); } catch(Exception e) { throw new FormatException("There have been strange changes in the CDS Examiner since installation. This is probably a programming error. Please inform the programmers at [http://taxondna.sf.net/].\n\nThe technical description is as follows: " + e); } // Now, we run through the list, deleting any [taxondna_cds...] tags // *Except* those mentioned in the hash_genes as returned to us by CDSExaminer Iterator i = list.iterator(); Pattern p_taxondna_cds = Pattern.compile("\\[taxondna_CDS(_complement)*:(.+?):(.+?)\\]"); while(i.hasNext()) { Sequence seq = (Sequence)i.next(); Hashtable cdss = (Hashtable) hash_cds.get(seq); boolean fixed_one_in_this_sequence = false; if(cdss != null) { Iterator iCDS = cdss.keySet().iterator(); while(iCDS.hasNext()) { String gene = (String)iCDS.next(); String code = (String)cdss.get(gene); Matcher m = p_taxondna_cds.matcher(code); if(m.find()) { String complement = m.group(1); String from = m.group(2); String to = m.group(3); // is this gene in the list? if(!fixed_one_in_this_sequence && hash_genes.get(gene) != null) { int i_from = 0; int i_to = 0; if(from.indexOf("<") != -1) { i_from = Integer.parseInt(from.substring(from.indexOf("<")+1)); } else i_from = Integer.parseInt(from); if(to.indexOf(">") != -1) { i_to = Integer.parseInt(to.substring(to.indexOf(">")+1)); } else i_to = Integer.parseInt(to); int old_length = seq.getLength(); String new_sequence = seq.getSequence().substring(i_from - 1, i_to); if(complement != null) new_sequence = reverseComplement(new_sequence); try { seq.changeSequence(new_sequence); } catch(SequenceException e) { throw new FormatException("I couldn't cut sequence " + seq + "; please check that the CDS of " + gene + " from " + from + " to " + to + " is actually valid."); } String complementary_str = ""; if(complement != null) complementary_str = " complementary"; seq.changeName(seq.getFullName() + " (cut '" + gene + "' from " + from + " to " + to + complementary_str + "; the sequence used to be " + old_length + " bp long)"); // we can't find more than one gene in any given sequence - sorry! fixed_one_in_this_sequence = true; } } } } if(!keep_sequences_without_CDS && !fixed_one_in_this_sequence) { // we couldn't find a match in this sequence! // Best get rid of the Sequence entirely? i.remove(); } } } finally { if(delay != null) delay.end(); list.setFile(file); list.setFormatHandler(this); list.unlock(); } }
diff --git a/src/powercrystals/core/asm/PCCASMTransformer.java b/src/powercrystals/core/asm/PCCASMTransformer.java index 409432c..c0c88f2 100644 --- a/src/powercrystals/core/asm/PCCASMTransformer.java +++ b/src/powercrystals/core/asm/PCCASMTransformer.java @@ -1,216 +1,216 @@ package powercrystals.core.asm; import cpw.mods.fml.relauncher.FMLRelauncher; import cpw.mods.fml.relauncher.IClassTransformer; import java.util.ArrayList; import java.util.List; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import powercrystals.core.CoreLoader; import powercrystals.core.asm.relauncher.Implementable; public class PCCASMTransformer implements IClassTransformer { private String desc; private ArrayList<String> workingPath = new ArrayList<String>(); private boolean isClient = FMLRelauncher.side().equals("CLIENT"); public PCCASMTransformer() { desc = Type.getDescriptor(Implementable.class); } @Override public byte[] transform(String name, String transformedName, byte[] bytes) { ClassReader cr = new ClassReader(bytes); ClassNode cn = new ClassNode(); cr.accept(cn, 0); workingPath.add(transformedName); if (this.implement(cn)) { System.out.println("Adding runtime interfaces to " + transformedName); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); bytes = cw.toByteArray(); cr = new ClassReader(bytes); } workingPath.remove(workingPath.size() - 1); if ("net.minecraft.world.WorldServer".equals(transformedName)) { bytes = writeWorldServer(name, transformedName, bytes, cr); } else if (!isClient && "net.minecraft.world.World".equals(transformedName)) { bytes = writeWorld(name, transformedName, bytes, cr); } return bytes; } private byte[] writeWorld(String name, String transformedName, byte[] bytes, ClassReader cr) { String[] names = null; if (CoreLoader.runtimeDeobfEnabled) { names = new String[]{"field_73019_z","field_72986_A","field_73011_w","field_72984_F","field_98181_L"}; } else { names = new String[]{"saveHandler","worldInfo","provider","theProfiler","worldLogAgent"}; } name = name.replace('.', '/'); ClassNode cn = new ClassNode(Opcodes.ASM4); cr.accept(cn, ClassReader.EXPAND_FRAMES); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); /* new World constructor * World(ISaveHandler saveHandler, String worldName, WorldProvider provider, WorldSettings worldSettings, Profiler theProfiler, ILogAgent worldLogAgent) **/ String sig = "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/profiler/Profiler;Lnet/minecraft/logging/ILogAgent;)V"; cw.newMethod(name, "<init>", sig, true); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", sig, null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[0], "Lnet/minecraft/world/storage/ISaveHandler;"); mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/world/storage/WorldInfo"); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, 4); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/world/storage/WorldInfo", "<init>", "(Lnet/minecraft/world/WorldSettings;Ljava/lang/String;)V"); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[1], "Lnet/minecraft/world/storage/WorldInfo;"); mv.visitVarInsn(Opcodes.ALOAD, 3); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[2], "Lnet/minecraft/world/WorldProvider;"); mv.visitVarInsn(Opcodes.ALOAD, 5); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/profiler/Profiler;"); mv.visitVarInsn(Opcodes.ALOAD, 6); - mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/logging/ILogAgent;"); + mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[4], "Lnet/minecraft/logging/ILogAgent;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(11, 10); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } private byte[] writeWorldServer(String name, String transformedName, byte[] bytes, ClassReader cr) { String[] names = null; if (CoreLoader.runtimeDeobfEnabled) { names = new String[]{"field_73061_a","field_73062_L","field_73063_M","field_85177_Q"}; } else { names = new String[]{"mcServer","theEntityTracker","thePlayerManager","field_85177_Q"}; } name = name.replace('.', '/'); ClassNode cn = new ClassNode(Opcodes.ASM4); cr.accept(cn, ClassReader.EXPAND_FRAMES); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); /* new WorldServer constructor * WorldServer(MinecraftServer minecraftServer, ISaveHandler saveHandler, String worldName, WorldProvider provider, WorldSettings worldSettings, Profiler theProfiler, ILogAgent worldLogAgent) **/ String sig = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/profiler/Profiler;Lnet/minecraft/logging/ILogAgent;)V"; cw.newMethod(name, "<init>", sig, true); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", sig, null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitVarInsn(Opcodes.ALOAD, 3); mv.visitVarInsn(Opcodes.ALOAD, 4); mv.visitVarInsn(Opcodes.ALOAD, 5); mv.visitVarInsn(Opcodes.ALOAD, 6); mv.visitVarInsn(Opcodes.ALOAD, 7); // [World] super(saveHandler, par2String, provider, par4WorldSettings, theProfiler, worldLogAgent); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/world/World", "<init>", "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/profiler/Profiler;Lnet/minecraft/logging/ILogAgent;)V"); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[0], "Lnet/minecraft/server/MinecraftServer;"); mv.visitInsn(Opcodes.ACONST_NULL); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[1], "Lnet/minecraft/entity/EntityTracker;"); mv.visitInsn(Opcodes.ACONST_NULL); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[2], "Lnet/minecraft/server/management/PlayerManager;"); mv.visitInsn(Opcodes.ACONST_NULL); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/world/Teleporter;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(11, 10); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } private boolean implement(ClassNode cn) { if (cn.visibleAnnotations == null) { return false; } boolean interfaces = false; for (AnnotationNode node : cn.visibleAnnotations) { if (node.desc.equals(desc)) { if (node.values != null) { List<Object> values = node.values; for (int i = 0, e = values.size(); i < e; ) { Object k = values.get(i++); Object v = values.get(i++); if (k instanceof String && k.equals("value") && v instanceof String) { String[] value = ((String)v).split(";"); for (int j = 0, l = value.length; j < l; ++j) { String clazz = value[j].trim(); String cz = clazz.replace('.', '/'); if (!cn.interfaces.contains(cz)) { try { if (!workingPath.contains(clazz)) { Class.forName(clazz, false, this.getClass().getClassLoader()); } cn.interfaces.add(cz); interfaces = true; } catch (Throwable _) {} } } } } } } } return interfaces; } }
true
true
private byte[] writeWorld(String name, String transformedName, byte[] bytes, ClassReader cr) { String[] names = null; if (CoreLoader.runtimeDeobfEnabled) { names = new String[]{"field_73019_z","field_72986_A","field_73011_w","field_72984_F","field_98181_L"}; } else { names = new String[]{"saveHandler","worldInfo","provider","theProfiler","worldLogAgent"}; } name = name.replace('.', '/'); ClassNode cn = new ClassNode(Opcodes.ASM4); cr.accept(cn, ClassReader.EXPAND_FRAMES); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); /* new World constructor * World(ISaveHandler saveHandler, String worldName, WorldProvider provider, WorldSettings worldSettings, Profiler theProfiler, ILogAgent worldLogAgent) **/ String sig = "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/profiler/Profiler;Lnet/minecraft/logging/ILogAgent;)V"; cw.newMethod(name, "<init>", sig, true); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", sig, null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[0], "Lnet/minecraft/world/storage/ISaveHandler;"); mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/world/storage/WorldInfo"); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, 4); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/world/storage/WorldInfo", "<init>", "(Lnet/minecraft/world/WorldSettings;Ljava/lang/String;)V"); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[1], "Lnet/minecraft/world/storage/WorldInfo;"); mv.visitVarInsn(Opcodes.ALOAD, 3); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[2], "Lnet/minecraft/world/WorldProvider;"); mv.visitVarInsn(Opcodes.ALOAD, 5); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/profiler/Profiler;"); mv.visitVarInsn(Opcodes.ALOAD, 6); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/logging/ILogAgent;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(11, 10); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); }
private byte[] writeWorld(String name, String transformedName, byte[] bytes, ClassReader cr) { String[] names = null; if (CoreLoader.runtimeDeobfEnabled) { names = new String[]{"field_73019_z","field_72986_A","field_73011_w","field_72984_F","field_98181_L"}; } else { names = new String[]{"saveHandler","worldInfo","provider","theProfiler","worldLogAgent"}; } name = name.replace('.', '/'); ClassNode cn = new ClassNode(Opcodes.ASM4); cr.accept(cn, ClassReader.EXPAND_FRAMES); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); /* new World constructor * World(ISaveHandler saveHandler, String worldName, WorldProvider provider, WorldSettings worldSettings, Profiler theProfiler, ILogAgent worldLogAgent) **/ String sig = "(Lnet/minecraft/world/storage/ISaveHandler;Ljava/lang/String;Lnet/minecraft/world/WorldProvider;Lnet/minecraft/world/WorldSettings;Lnet/minecraft/profiler/Profiler;Lnet/minecraft/logging/ILogAgent;)V"; cw.newMethod(name, "<init>", sig, true); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", sig, null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitInsn(Opcodes.DUP); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[0], "Lnet/minecraft/world/storage/ISaveHandler;"); mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/world/storage/WorldInfo"); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ALOAD, 4); mv.visitVarInsn(Opcodes.ALOAD, 2); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/world/storage/WorldInfo", "<init>", "(Lnet/minecraft/world/WorldSettings;Ljava/lang/String;)V"); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[1], "Lnet/minecraft/world/storage/WorldInfo;"); mv.visitVarInsn(Opcodes.ALOAD, 3); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[2], "Lnet/minecraft/world/WorldProvider;"); mv.visitVarInsn(Opcodes.ALOAD, 5); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[3], "Lnet/minecraft/profiler/Profiler;"); mv.visitVarInsn(Opcodes.ALOAD, 6); mv.visitFieldInsn(Opcodes.PUTFIELD, name, names[4], "Lnet/minecraft/logging/ILogAgent;"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(11, 10); mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); }
diff --git a/mlt++/swig/java/Play.java b/mlt++/swig/java/Play.java index 3bf0e47a..3f6b4c89 100644 --- a/mlt++/swig/java/Play.java +++ b/mlt++/swig/java/Play.java @@ -1,51 +1,51 @@ import net.sourceforge.mltpp.*; public class Play { static { System.loadLibrary("mltpp_java"); } public static void main (String[] args) { // Start the mlt system Factory.init( null ); // Create the producer Producer p = new Producer( args[0], null ); if ( p.is_valid() ) { p.set ("eof", "loop"); // Create the consumer Consumer c = new Consumer("sdl", null); // Turn off the default rescaling c.set("rescale", "none"); // Connect the producer to the consumer c.connect(p); // Start the consumer c.start(); // Wait until the user stops the consumer Object o = new Object(); - while (c.is_stopped() == 0) { + while ( !c.is_stopped() ) { synchronized (o) { try { o.wait(1000); } catch (InterruptedException e) { // ignored } } } // Stop it anyway c.stop(); } else { System.out.println ("Unable to open " + args[0]); } } }
true
true
public static void main (String[] args) { // Start the mlt system Factory.init( null ); // Create the producer Producer p = new Producer( args[0], null ); if ( p.is_valid() ) { p.set ("eof", "loop"); // Create the consumer Consumer c = new Consumer("sdl", null); // Turn off the default rescaling c.set("rescale", "none"); // Connect the producer to the consumer c.connect(p); // Start the consumer c.start(); // Wait until the user stops the consumer Object o = new Object(); while (c.is_stopped() == 0) { synchronized (o) { try { o.wait(1000); } catch (InterruptedException e) { // ignored } } } // Stop it anyway c.stop(); } else { System.out.println ("Unable to open " + args[0]); } }
public static void main (String[] args) { // Start the mlt system Factory.init( null ); // Create the producer Producer p = new Producer( args[0], null ); if ( p.is_valid() ) { p.set ("eof", "loop"); // Create the consumer Consumer c = new Consumer("sdl", null); // Turn off the default rescaling c.set("rescale", "none"); // Connect the producer to the consumer c.connect(p); // Start the consumer c.start(); // Wait until the user stops the consumer Object o = new Object(); while ( !c.is_stopped() ) { synchronized (o) { try { o.wait(1000); } catch (InterruptedException e) { // ignored } } } // Stop it anyway c.stop(); } else { System.out.println ("Unable to open " + args[0]); } }
diff --git a/src/java/com/idega/presentation/TableCell.java b/src/java/com/idega/presentation/TableCell.java index aaadbf845..55b728de9 100644 --- a/src/java/com/idega/presentation/TableCell.java +++ b/src/java/com/idega/presentation/TableCell.java @@ -1,40 +1,40 @@ /* * * Copyright (C) 2001-2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. * */ package com.idega.presentation; import com.idega.idegaweb.IWUserContext; /** * Used by the table class to represent each cell. * tags for each cell. * * @author <a href="mailto:tryggvi@idega.is">Tryggvi Larusson</a> * @version 1.0 */ public class TableCell extends PresentationObjectContainer { //TODO: A lot of the rendering logic should be moved to this class from the Table class - protected TableCell() { + public TableCell() { super(); this.setTransient(false); } /** * Override this method to bypass the permission logic for TableCells * (because they dont have a direct instance id) */ public Object clonePermissionChecked(IWUserContext iwc, boolean askForPermission) { return clone(iwc, askForPermission); } }
true
true
protected TableCell() { super(); this.setTransient(false); }
public TableCell() { super(); this.setTransient(false); }
diff --git a/src/main/java/nl/giantit/minecraft/giantshop/core/Logger/Logger.java b/src/main/java/nl/giantit/minecraft/giantshop/core/Logger/Logger.java index 9662152..ebd0b00 100644 --- a/src/main/java/nl/giantit/minecraft/giantshop/core/Logger/Logger.java +++ b/src/main/java/nl/giantit/minecraft/giantshop/core/Logger/Logger.java @@ -1,55 +1,54 @@ package nl.giantit.minecraft.giantshop.core.Logger; import nl.giantit.minecraft.giantshop.GiantShop; import nl.giantit.minecraft.giantshop.core.config; import nl.giantit.minecraft.giantcore.database.Driver; import nl.giantit.minecraft.giantcore.database.query.InsertQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Logger { public static void Log(LoggerType type, String playerName, HashMap<String, String> data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.log.useLogging")) { if(conf.getBoolean("GiantShop.log.log." + type.getName().toLowerCase())) { String json = "{"; int i = 0; for(Map.Entry<String, String> d : data.entrySet()) { i++; json += "\"" + d.getKey() + "\": \"" + d.getValue() + "\""; if(i < data.size()) { json += ","; } } json += "}"; Driver DB = GiantShop.getPlugin().getDB().getEngine(); int t = type.getID(); ArrayList<String> fields = new ArrayList<String>(); - ArrayList<HashMap<Integer, HashMap<String, String>>> values = new ArrayList<HashMap<Integer, HashMap<String, String>>>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); InsertQuery iQ = DB.insert("#__log"); iQ.addFields(fields); iQ.addRow(); - iQ.assignValue("type", json, InsertQuery.ValueType.RAW); + iQ.assignValue("type", String.valueOf(t), InsertQuery.ValueType.RAW); iQ.assignValue("user", playerName); iQ.assignValue("data", json); iQ.assignValue("date", String.valueOf(Logger.getTimestamp())); iQ.exec(); } } } public static long getTimestamp() { return System.currentTimeMillis() / 1000; } }
false
true
public static void Log(LoggerType type, String playerName, HashMap<String, String> data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.log.useLogging")) { if(conf.getBoolean("GiantShop.log.log." + type.getName().toLowerCase())) { String json = "{"; int i = 0; for(Map.Entry<String, String> d : data.entrySet()) { i++; json += "\"" + d.getKey() + "\": \"" + d.getValue() + "\""; if(i < data.size()) { json += ","; } } json += "}"; Driver DB = GiantShop.getPlugin().getDB().getEngine(); int t = type.getID(); ArrayList<String> fields = new ArrayList<String>(); ArrayList<HashMap<Integer, HashMap<String, String>>> values = new ArrayList<HashMap<Integer, HashMap<String, String>>>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); InsertQuery iQ = DB.insert("#__log"); iQ.addFields(fields); iQ.addRow(); iQ.assignValue("type", json, InsertQuery.ValueType.RAW); iQ.assignValue("user", playerName); iQ.assignValue("data", json); iQ.assignValue("date", String.valueOf(Logger.getTimestamp())); iQ.exec(); } } }
public static void Log(LoggerType type, String playerName, HashMap<String, String> data) { config conf = config.Obtain(); if(conf.getBoolean("GiantShop.log.useLogging")) { if(conf.getBoolean("GiantShop.log.log." + type.getName().toLowerCase())) { String json = "{"; int i = 0; for(Map.Entry<String, String> d : data.entrySet()) { i++; json += "\"" + d.getKey() + "\": \"" + d.getValue() + "\""; if(i < data.size()) { json += ","; } } json += "}"; Driver DB = GiantShop.getPlugin().getDB().getEngine(); int t = type.getID(); ArrayList<String> fields = new ArrayList<String>(); fields.add("type"); fields.add("user"); fields.add("data"); fields.add("date"); InsertQuery iQ = DB.insert("#__log"); iQ.addFields(fields); iQ.addRow(); iQ.assignValue("type", String.valueOf(t), InsertQuery.ValueType.RAW); iQ.assignValue("user", playerName); iQ.assignValue("data", json); iQ.assignValue("date", String.valueOf(Logger.getTimestamp())); iQ.exec(); } } }
diff --git a/h2/src/main/org/h2/command/Command.java b/h2/src/main/org/h2/command/Command.java index e979c9517..1005afc74 100644 --- a/h2/src/main/org/h2/command/Command.java +++ b/h2/src/main/org/h2/command/Command.java @@ -1,230 +1,237 @@ /* * Copyright 2004-2008 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.command; import java.sql.SQLException; import org.h2.constant.ErrorCode; import org.h2.engine.Constants; import org.h2.engine.Database; import org.h2.engine.Session; import org.h2.message.Message; import org.h2.message.Trace; import org.h2.message.TraceObject; import org.h2.result.LocalResult; import org.h2.result.ResultInterface; import org.h2.util.ObjectArray; /** * Represents a SQL statement. This object is only used on the server side. */ public abstract class Command implements CommandInterface { /** * The session. */ protected final Session session; /** * The trace module. */ protected final Trace trace; /** * The last start time. */ protected long startTime; /** * If this query was cancelled. */ private volatile boolean cancel; private final String sql; public Command(Parser parser, String sql) { this.session = parser.getSession(); this.sql = sql; trace = session.getDatabase().getTrace(Trace.COMMAND); } /** * Check if this command is transactional. * If it is not, then it forces the current transaction to commit. * * @return true if it is */ public abstract boolean isTransactional(); /** * Check if this command is a query. * * @return true if it is */ public abstract boolean isQuery(); /** * Get the list of parameters. * * @return the list of parameters */ public abstract ObjectArray getParameters(); /** * Check if this command is read only. * * @return true if it is */ public abstract boolean isReadOnly(); /** * Get an empty result set containing the meta data. * * @return an empty result set */ public abstract LocalResult queryMeta() throws SQLException; /** * Execute an updating statement, if this is possible. * * @return the update count * @throws SQLException if the command is not an updating statement */ public int update() throws SQLException { throw Message.getSQLException(ErrorCode.METHOD_NOT_ALLOWED_FOR_QUERY); } /** * Execute a query statement, if this is possible. * * @param maxrows the maximum number of rows returned * @return the local result set * @throws SQLException if the command is not a query */ public LocalResult query(int maxrows) throws SQLException { throw Message.getSQLException(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY); } public final LocalResult getMetaDataLocal() throws SQLException { return queryMeta(); } public final ResultInterface getMetaData() throws SQLException { return queryMeta(); } public ResultInterface executeQuery(int maxrows, boolean scrollable) throws SQLException { return executeQueryLocal(maxrows); } /** * Execute a query and return a local result set. * This method prepares everything and calls {@link #query(int)} finally. * * @param maxrows the maximum number of rows to return * @return the local result set */ public LocalResult executeQueryLocal(int maxrows) throws SQLException { startTime = System.currentTimeMillis(); Database database = session.getDatabase(); Object sync = database.getMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { try { database.checkPowerOff(); session.setCurrentCommand(this, startTime); return query(maxrows); } catch (Exception e) { SQLException s = Message.convert(e, sql); database.exceptionThrown(s, sql); throw s; } finally { stop(); } } } /** * Start the stopwatch. */ void start() { startTime = System.currentTimeMillis(); } /** * Check if this command has been cancelled, and throw an exception if yes. * * @throws SQLException if the statement has been cancelled */ public void checkCancelled() throws SQLException { if (cancel) { cancel = false; throw Message.getSQLException(ErrorCode.STATEMENT_WAS_CANCELLED); } } private void stop() throws SQLException { session.closeTemporaryResults(); session.setCurrentCommand(null, 0); if (!isTransactional()) { session.commit(true); } else if (session.getAutoCommit()) { session.commit(false); } else if (session.getDatabase().getMultiThreaded()) { Database db = session.getDatabase(); if (db != null) { if (db.getLockMode() == Constants.LOCK_MODE_READ_COMMITTED) { session.unlockReadLocks(); } } } if (trace.isInfoEnabled()) { long time = System.currentTimeMillis() - startTime; if (time > Constants.SLOW_QUERY_LIMIT_MS) { trace.info("slow query: " + time); } } } public int executeUpdate() throws SQLException { startTime = System.currentTimeMillis(); Database database = session.getDatabase(); Object sync = database.getMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { database.checkPowerOff(); - return update(); + int test; + try { + return update(); + } catch (OutOfMemoryError e) { + throw Message.convert(e); + } catch (Throwable e) { + throw Message.convert(e); + } } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); } else { session.rollbackTo(rollback); } throw e; } finally { stop(); } } } public void close() { // nothing to do } public void cancel() { this.cancel = true; } public String toString() { return TraceObject.toString(sql, getParameters()); } }
true
true
public int executeUpdate() throws SQLException { startTime = System.currentTimeMillis(); Database database = session.getDatabase(); Object sync = database.getMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { database.checkPowerOff(); return update(); } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); } else { session.rollbackTo(rollback); } throw e; } finally { stop(); } } }
public int executeUpdate() throws SQLException { startTime = System.currentTimeMillis(); Database database = session.getDatabase(); Object sync = database.getMultiThreaded() ? (Object) session : (Object) database; session.waitIfExclusiveModeEnabled(); synchronized (sync) { int rollback = session.getLogId(); session.setCurrentCommand(this, startTime); try { database.checkPowerOff(); int test; try { return update(); } catch (OutOfMemoryError e) { throw Message.convert(e); } catch (Throwable e) { throw Message.convert(e); } } catch (SQLException e) { database.exceptionThrown(e, sql); database.checkPowerOff(); if (e.getErrorCode() == ErrorCode.DEADLOCK_1) { session.rollback(); } else { session.rollbackTo(rollback); } throw e; } finally { stop(); } } }
diff --git a/src/ru/ifmo/neerc/timer/TimerGUI.java b/src/ru/ifmo/neerc/timer/TimerGUI.java index c9e6842..d2cceff 100644 --- a/src/ru/ifmo/neerc/timer/TimerGUI.java +++ b/src/ru/ifmo/neerc/timer/TimerGUI.java @@ -1,163 +1,163 @@ package ru.ifmo.neerc.timer; import java.awt.Color; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import pcms2.services.site.Clock; import ru.ifmo.neerc.framework.Settings; public abstract class TimerGUI{ public static final int BEFORE = 0; public static final int RUNNING = 1; public static final int FROZEN = 2; public static final int PAUSED = 3; public static final int LEFT5MIN = 4; public static final int LEFT1MIN = 5; public static final int OVER = 6; AtomicInteger status; AtomicReference<SynchronizedTime> cTime; private Color[] palette; class SynchronizedTime { private final long cTime, sync; private long frozen, correction; public SynchronizedTime(long time, boolean frozen) { cTime = time; sync = System.currentTimeMillis(); correction = 0; if (frozen) this.frozen = System.currentTimeMillis(); } public long get() { if (frozen == 0) { return Math.max(0, cTime + sync - System.currentTimeMillis() + correction); } else { return Math.max(0, cTime + sync - frozen + correction); } } public void freeze() { if (frozen == 0) { frozen = System.currentTimeMillis(); } } public void resume() { if (frozen != 0) { correction += System.currentTimeMillis() - frozen; frozen = 0; } } } TimerGUI() { palette = new Color[7]; palette[BEFORE] = Color.decode(Settings.instance().colorScheme.get("before")); palette[RUNNING] = Color.decode(Settings.instance().colorScheme.get("running")); palette[FROZEN] = Color.decode(Settings.instance().colorScheme.get("frozen")); palette[LEFT5MIN] = Color.decode(Settings.instance().colorScheme.get("left5min")); palette[LEFT1MIN] = Color.decode(Settings.instance().colorScheme.get("left1min")); palette[OVER] = Color.decode(Settings.instance().colorScheme.get("over")); palette[PAUSED] = Color.decode(Settings.instance().colorScheme.get("paused")); setText("0:00:00", palette[BEFORE]); cTime = new AtomicReference<SynchronizedTime>(); cTime.set(new SynchronizedTime(0, true)); status = new AtomicInteger(Clock.BEFORE); new Thread(new Runnable() { @Override public void run() { while (true) { long dtime = cTime.get().get(); dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = palette[RUNNING];; switch (status.get()) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } if (hours == 0) { - if (minutes <= 1) { + if (minutes < 1) { c = palette[LEFT1MIN]; - } else if (minutes <= 5) { + } else if (minutes < 5) { c = palette[LEFT5MIN]; } else { c = palette[FROZEN]; setFrozen(true); } } else { setFrozen(false); } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { if (seconds > 0) { text = String.format("%d", seconds); } else { text = "OVER"; } } setText(text, c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); } protected abstract void setFrozen(boolean b); protected abstract void setText(String string, Color c); protected abstract void repaint(); public void setStatus(int status) { synchronized (this.status) { this.status.set(status); if (status != Clock.RUNNING) { cTime.get().freeze(); } else { cTime.get().resume(); } repaint(); } } public void sync(long time) { cTime.set(new SynchronizedTime(time, status.get() != Clock.RUNNING)); repaint(); } }
false
true
TimerGUI() { palette = new Color[7]; palette[BEFORE] = Color.decode(Settings.instance().colorScheme.get("before")); palette[RUNNING] = Color.decode(Settings.instance().colorScheme.get("running")); palette[FROZEN] = Color.decode(Settings.instance().colorScheme.get("frozen")); palette[LEFT5MIN] = Color.decode(Settings.instance().colorScheme.get("left5min")); palette[LEFT1MIN] = Color.decode(Settings.instance().colorScheme.get("left1min")); palette[OVER] = Color.decode(Settings.instance().colorScheme.get("over")); palette[PAUSED] = Color.decode(Settings.instance().colorScheme.get("paused")); setText("0:00:00", palette[BEFORE]); cTime = new AtomicReference<SynchronizedTime>(); cTime.set(new SynchronizedTime(0, true)); status = new AtomicInteger(Clock.BEFORE); new Thread(new Runnable() { @Override public void run() { while (true) { long dtime = cTime.get().get(); dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = palette[RUNNING];; switch (status.get()) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } if (hours == 0) { if (minutes <= 1) { c = palette[LEFT1MIN]; } else if (minutes <= 5) { c = palette[LEFT5MIN]; } else { c = palette[FROZEN]; setFrozen(true); } } else { setFrozen(false); } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { if (seconds > 0) { text = String.format("%d", seconds); } else { text = "OVER"; } } setText(text, c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); }
TimerGUI() { palette = new Color[7]; palette[BEFORE] = Color.decode(Settings.instance().colorScheme.get("before")); palette[RUNNING] = Color.decode(Settings.instance().colorScheme.get("running")); palette[FROZEN] = Color.decode(Settings.instance().colorScheme.get("frozen")); palette[LEFT5MIN] = Color.decode(Settings.instance().colorScheme.get("left5min")); palette[LEFT1MIN] = Color.decode(Settings.instance().colorScheme.get("left1min")); palette[OVER] = Color.decode(Settings.instance().colorScheme.get("over")); palette[PAUSED] = Color.decode(Settings.instance().colorScheme.get("paused")); setText("0:00:00", palette[BEFORE]); cTime = new AtomicReference<SynchronizedTime>(); cTime.set(new SynchronizedTime(0, true)); status = new AtomicInteger(Clock.BEFORE); new Thread(new Runnable() { @Override public void run() { while (true) { long dtime = cTime.get().get(); dtime /= 1000; int seconds = (int) (dtime % 60); dtime /= 60; int minutes = (int) (dtime % 60); dtime /= 60; int hours = (int) dtime; String text = null; Color c = palette[RUNNING];; switch (status.get()) { case Clock.BEFORE: c = palette[BEFORE]; break; case Clock.RUNNING: c = palette[RUNNING]; break; case Clock.OVER: c = palette[OVER]; break; case Clock.PAUSED: c = palette[PAUSED]; break; } if (hours == 0) { if (minutes < 1) { c = palette[LEFT1MIN]; } else if (minutes < 5) { c = palette[LEFT5MIN]; } else { c = palette[FROZEN]; setFrozen(true); } } else { setFrozen(false); } if (hours > 0) { text = String.format("%d:%02d:%02d", hours, minutes, seconds); } else if (minutes > 0) { text = String.format("%02d:%02d", minutes, seconds); } else { if (seconds > 0) { text = String.format("%d", seconds); } else { text = "OVER"; } } setText(text, c); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } } }).start(); }
diff --git a/src/me/libraryaddict/disguise/commands/DisguisePlayerCommand.java b/src/me/libraryaddict/disguise/commands/DisguisePlayerCommand.java index ea47967..4c9e499 100644 --- a/src/me/libraryaddict/disguise/commands/DisguisePlayerCommand.java +++ b/src/me/libraryaddict/disguise/commands/DisguisePlayerCommand.java @@ -1,72 +1,68 @@ package me.libraryaddict.disguise.commands; import java.util.ArrayList; import me.libraryaddict.disguise.BaseDisguiseCommand; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.Disguise; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class DisguisePlayerCommand extends BaseDisguiseCommand { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } ArrayList<String> allowedDisguises = getAllowedDisguises(sender, "disguiseplayer"); if (allowedDisguises.isEmpty()) { sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); return true; } if (args.length == 0) { sendCommandUsage(sender); return true; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the player"); return true; } Player player = Bukkit.getPlayer(args[0]); if (player == null) { sender.sendMessage(ChatColor.RED + "Cannot find the player '" + args[0] + "'"); return true; } try { String[] newArgs = new String[args.length - 1]; for (int i = 0; i < newArgs.length; i++) { newArgs[i] = args[i + 1]; } Disguise disguise = parseDisguise(sender, newArgs); DisguiseAPI.disguiseToAll(player, disguise); sender.sendMessage(ChatColor.RED + "Successfully disguised " + player.getName() + " as a " + disguise.getType().toReadable() + "!"); } catch (Exception ex) { if (ex.getMessage() != null) { sender.sendMessage(ex.getMessage()); } } return true; } /** * Send the player the information */ protected void sendCommandUsage(CommandSender sender) { ArrayList<String> allowedDisguises = getAllowedDisguises(sender, "disguiseplayer"); sender.sendMessage(ChatColor.DARK_GREEN + "Disguise another player!"); sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); if (allowedDisguises.contains("player")) sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer <PlayerName> player <Name>"); sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer <PlayerName> <DisguiseType> <Baby>"); if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer <PlayerName> <Dropped_Item/Falling_Block> <Id> <Durability>"); } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender.getName().equals("CONSOLE")) { sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); return true; } ArrayList<String> allowedDisguises = getAllowedDisguises(sender, "disguiseplayer"); if (allowedDisguises.isEmpty()) { sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); return true; } if (args.length == 0) { sendCommandUsage(sender); return true; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the player"); return true; } Player player = Bukkit.getPlayer(args[0]); if (player == null) { sender.sendMessage(ChatColor.RED + "Cannot find the player '" + args[0] + "'"); return true; } try { String[] newArgs = new String[args.length - 1]; for (int i = 0; i < newArgs.length; i++) { newArgs[i] = args[i + 1]; } Disguise disguise = parseDisguise(sender, newArgs); DisguiseAPI.disguiseToAll(player, disguise); sender.sendMessage(ChatColor.RED + "Successfully disguised " + player.getName() + " as a " + disguise.getType().toReadable() + "!"); } catch (Exception ex) { if (ex.getMessage() != null) { sender.sendMessage(ex.getMessage()); } } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { ArrayList<String> allowedDisguises = getAllowedDisguises(sender, "disguiseplayer"); if (allowedDisguises.isEmpty()) { sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); return true; } if (args.length == 0) { sendCommandUsage(sender); return true; } if (args.length == 1) { sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the player"); return true; } Player player = Bukkit.getPlayer(args[0]); if (player == null) { sender.sendMessage(ChatColor.RED + "Cannot find the player '" + args[0] + "'"); return true; } try { String[] newArgs = new String[args.length - 1]; for (int i = 0; i < newArgs.length; i++) { newArgs[i] = args[i + 1]; } Disguise disguise = parseDisguise(sender, newArgs); DisguiseAPI.disguiseToAll(player, disguise); sender.sendMessage(ChatColor.RED + "Successfully disguised " + player.getName() + " as a " + disguise.getType().toReadable() + "!"); } catch (Exception ex) { if (ex.getMessage() != null) { sender.sendMessage(ex.getMessage()); } } return true; }
diff --git a/jgcf/src/main/java/com/jenjinstudios/net/AuthClient.java b/jgcf/src/main/java/com/jenjinstudios/net/AuthClient.java index 9fb4fb88..fa131430 100644 --- a/jgcf/src/main/java/com/jenjinstudios/net/AuthClient.java +++ b/jgcf/src/main/java/com/jenjinstudios/net/AuthClient.java @@ -1,195 +1,195 @@ package com.jenjinstudios.net; import com.jenjinstudios.message.Message; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; /** * The {@code AuthClient} class is a {@code Client} with the ability to store user information and attempt to log into a * {@code Server} using a username and password. * @author Caleb Brinkman */ public class AuthClient extends Client { /** The logger associated with this class. */ private static final Logger LOGGER = Logger.getLogger(AuthClient.class.getName()); /** The number of milliseconds before a blocking method should time out. */ public static long TIMEOUT_MILLIS = 30000; /** The username this client will use when logging in. */ private String username; /** The password this client will use when logging in. */ private String password; /** Whether the user is logged in. */ private boolean loggedIn; /** The time at which this client was successfully logged in. */ private long loggedInTime; /** flags whether the login response has been received. */ private volatile boolean receivedLoginResponse; /** flags whether the logout response has been received. */ private volatile boolean receivedLogoutResponse; /** * Construct a client connecting to the given address over the given port. * @param address The address to which this client will attempt to connect. * @param port The port over which this client will attempt to connect. * @param username The username that will be used by this client. * @param password The password that will be used by this client. * @throws java.security.NoSuchAlgorithmException If there is an error generating encryption keys. */ public AuthClient(String address, int port, String username, String password) throws NoSuchAlgorithmException { super(address, port); this.username = username; this.password = password; } /** * Queue a message to log into the server with the given username and password, and wait for the response. * @return If the login was successful. */ public boolean sendBlockingLoginRequest() { sendLoginRequest(); long startTime = System.currentTimeMillis(); long timepast = System.currentTimeMillis() - startTime; while (!hasReceivedLoginResponse() && (timepast < TIMEOUT_MILLIS)) { - try // TODO Make sure error is handled gracefully + try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e); } timepast = System.currentTimeMillis() - startTime; } return isLoggedIn(); } /** * Get whether this client is logged in. * @return true if this client has received a successful LoginResponse */ public boolean isLoggedIn() { return loggedIn; } /** * Set whether this client is logged in. * @param l Whether this client is logged in. */ public void setLoggedIn(boolean l) { loggedIn = l; } /** Send a login request to the server. */ private void sendLoginRequest() { if (username == null || password == null) { throw new IllegalStateException("Attempted to login without username or password"); } Message loginRequest = generateLoginRequest(); // Send the request, continue when the response is received. setReceivedLoginResponse(false); queueMessage(loginRequest); } /** * Generate a LoginRequest message. * @return The LoginRequest message. */ private Message generateLoginRequest() {// Create the login request. Message loginRequest = new Message("LoginRequest"); loginRequest.setArgument("username", username); loginRequest.setArgument("password", password); return loginRequest; } /** * Set whether this client has received a login response. * @param receivedLoginResponse Whether this client has received a login response. */ public void setReceivedLoginResponse(boolean receivedLoginResponse) { this.receivedLoginResponse = receivedLoginResponse; } /** * Get whether this client has received a login response. * @return Whether the client has received a login response. */ public boolean hasReceivedLoginResponse() { return receivedLoginResponse; } /** * Queue a message to log the user out of the server. * @return Whether the logout request was successful. */ public boolean sendBlockingLogoutRequest() { sendLogoutRequest(); long startTime = System.currentTimeMillis(); long timepast = System.currentTimeMillis() - startTime; while (!hasReceivedLogoutResponse() && (timepast < TIMEOUT_MILLIS)) { try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e); } timepast = System.currentTimeMillis() - startTime; } return isLoggedIn(); } /** Send a logout request to the server. */ private void sendLogoutRequest() { Message logoutRequest = new Message("LogoutRequest"); // Send the request, continue when response is received. setReceivedLogoutResponse(false); queueMessage(logoutRequest); } /** * Set whether this client has received a logout response. * @param receivedLogoutResponse Whether this client has received a logout response. */ public void setReceivedLogoutResponse(boolean receivedLogoutResponse) { this.receivedLogoutResponse = receivedLogoutResponse; } /** * Get whether this client has received a logout response. * @return Whether this client has received a logout response. */ public boolean hasReceivedLogoutResponse() { return receivedLogoutResponse; } /** * Get the username of this client. * @return The username of this client. */ public String getUsername() { return username; } /** * Get the time at which this client was successfully logged in. * @return The time of the start of the server cycle during which this client was logged in. */ public long getLoggedInTime() { return loggedInTime; } /** * Set the logged in time for this client. * @param loggedInTime The logged in time for this client. */ public void setLoggedInTime(long loggedInTime) { this.loggedInTime = loggedInTime; } }
true
true
public boolean sendBlockingLoginRequest() { sendLoginRequest(); long startTime = System.currentTimeMillis(); long timepast = System.currentTimeMillis() - startTime; while (!hasReceivedLoginResponse() && (timepast < TIMEOUT_MILLIS)) { try // TODO Make sure error is handled gracefully { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e); } timepast = System.currentTimeMillis() - startTime; } return isLoggedIn(); }
public boolean sendBlockingLoginRequest() { sendLoginRequest(); long startTime = System.currentTimeMillis(); long timepast = System.currentTimeMillis() - startTime; while (!hasReceivedLoginResponse() && (timepast < TIMEOUT_MILLIS)) { try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.", e); } timepast = System.currentTimeMillis() - startTime; } return isLoggedIn(); }
diff --git a/eXoApplication/poll/webapp/src/main/java/org/exoplatform/poll/webui/UIPoll.java b/eXoApplication/poll/webapp/src/main/java/org/exoplatform/poll/webui/UIPoll.java index f87407cdf..7a880b70d 100755 --- a/eXoApplication/poll/webapp/src/main/java/org/exoplatform/poll/webui/UIPoll.java +++ b/eXoApplication/poll/webapp/src/main/java/org/exoplatform/poll/webui/UIPoll.java @@ -1,459 +1,459 @@ /*************************************************************************** * 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.poll.webui; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.portlet.PortletPreferences; import org.exoplatform.container.PortalContainer; import org.exoplatform.ks.common.UserHelper; import org.exoplatform.ks.common.webui.BaseEventListener; import org.exoplatform.ks.common.webui.UIPopupAction; import org.exoplatform.poll.Utils; import org.exoplatform.poll.service.Poll; import org.exoplatform.poll.service.impl.PollNodeTypes; import org.exoplatform.poll.webui.popup.UIPollForm; import org.exoplatform.services.organization.Group; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.core.model.SelectItemOption; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIFormRadioBoxInput; /** * Created by The eXo Platform SARL * Author : Vu Duy Tu * tu.duy@exoplatform.com * June 26, 2010 9:48:18 AM */ @ComponentConfig( lifecycle = UIFormLifecycle.class , template = "app:/templates/poll/webui/UIPoll.gtmpl", events = { @EventConfig(listeners = UIPoll.VoteActionListener.class), @EventConfig(listeners = UIPoll.EditPollActionListener.class) , @EventConfig(listeners = UIPoll.RemovePollActionListener.class, confirm="UITopicPoll.msg.confirm-RemovePoll"), @EventConfig(listeners = UIPoll.ClosedPollActionListener.class), @EventConfig(listeners = UIPoll.VoteAgainPollActionListener.class) } ) @SuppressWarnings("unused") public class UIPoll extends BasePollForm { private Poll poll_ ; private String pollId , userId; private boolean isAgainVote = false ; private boolean isEditPoll = false ; private boolean hasPermission = true ; private String[] dateUnit = new String[]{"Never", "Closed", "day(s)", "hour(s)", "minutes"}; public UIPoll() throws Exception { userId = UserHelper.getCurrentUser() ; try { dateUnit = new String[]{getLabel("Never"), getLabel("Closed"), getLabel("day"), getLabel("hour"), getLabel("minutes")}; } catch (Exception e) {} } public void setPollId() throws Exception { if(Utils.isEmpty(pollId)) { PortletRequestContext pcontext = (PortletRequestContext)WebuiRequestContext.getCurrentInstance() ; PortletPreferences portletPref = pcontext.getRequest().getPreferences() ; pollId = portletPref.getValue("pollIdShow", ""); if(Utils.isEmpty(pollId)) { // List<String> list = getPollService().getListPollId(); // if(!list.isEmpty()){ // pollId = list.get(0); // } } this.isEditPoll = true ; } } public static boolean hasUserInGroup(String groupId, String userId) throws Exception { OrganizationService organizationService = (OrganizationService) PortalContainer.getComponent(OrganizationService.class); for (Object object : organizationService.getGroupHandler().findGroupsOfUser(userId)) { if(((Group)object).getId().equals(groupId)){ return true; } } return false ; } private boolean checkPermission() throws Exception { String path = poll_.getParentPath(); if(path.indexOf(PollNodeTypes.APPLICATION_DATA) > 0){ String group = path.substring(path.indexOf("/", 3), path.indexOf(PollNodeTypes.APPLICATION_DATA)-1); try { hasPermission = hasUserInGroup(group, userId); } catch (Exception e) {} } return hasPermission; } public void updateFormPoll(Poll poll) throws Exception { if(poll.getIsClosed()) poll.setExpire(Utils.getExpire(-1, poll.getModifiedDate(), dateUnit)); else poll.setExpire(Utils.getExpire(poll.getTimeOut(), poll.getModifiedDate(), dateUnit)); poll_ = poll; this.isEditPoll = false ; checkPermission(); } public void updatePollById(String pollId) throws Exception { this.pollId = pollId; this.isEditPoll = true ; } @SuppressWarnings("unchecked") private void init() throws Exception { if(this.hasChildren()){ this.removeChild(UIFormRadioBoxInput.class) ; int i=0; while(i<10) { if(this.hasChildren())this.removeChild(UIForumCheckBoxInput.class) ; else break ; ++i; } } if(poll_ != null) { if(!poll_.getIsMultiCheck()) { List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; for (String s : poll_.getOption()) { options.add( new SelectItemOption<String>(s, s) ) ; } UIFormRadioBoxInput input = new UIFormRadioBoxInput("vote", "vote", options); input.setAlign(1) ; addUIFormInput(input); } else { for(String s : poll_.getOption()) { addUIFormInput(new UIForumCheckBoxInput(s,s, false) ); } } } } private Poll getPoll() throws Exception { setPollId(); if(isEditPoll && pollId != null && pollId.length() > 0) { poll_ = getPollService().getPoll(pollId) ; checkPermission(); if(poll_.getIsClosed()) poll_.setExpire(Utils.getExpire(-1, poll_.getModifiedDate(), dateUnit)); else poll_.setExpire(Utils.getExpire(poll_.getTimeOut(), poll_.getModifiedDate(), dateUnit)); } this.init() ; return poll_ ; } private boolean getIsEditPoll() { return isEditPoll ; } public void setEditPoll(boolean isEditPoll) { this.isEditPoll = isEditPoll; } private boolean getCanViewEditMenu(){ return getAncestorOfType(UIPollPortlet.class).isAdmin() ; } private boolean isGuestPermission() throws Exception { if(poll_.getIsClosed()) return true ; if(Utils.isEmpty(userId)) return true ; if(poll_.getTimeOut() > 0) { Date today = new Date() ; if((today.getTime() - this.poll_.getCreatedDate().getTime()) >= poll_.getTimeOut()*86400000) return true ; } if(this.isAgainVote) { return false ; } String[] userVotes = poll_.getUserVote() ; for (String string : userVotes) { string = string.substring(0, string.indexOf(":")) ; if(string.equalsIgnoreCase(userId)) return true ; } return false ; } private String[] getInfoVote() throws Exception { Poll poll = poll_ ; String[] voteNumber = poll.getVote() ; String[] userVotes = poll.getUserVote(); long size = 0 , temp = 1; if(!poll.getIsMultiCheck()) { size = userVotes.length ; } else { for (int i = 0; i < userVotes.length; i++) { size += userVotes[i].split(":").length -1 ; } } temp = size; if(size == 0) size = 1; int l = voteNumber.length; String[] infoVote = new String[(l + 1)] ; for (int j = 0; j < l; j++) { String string = voteNumber[j]; double tmp = Double.parseDouble(string) ; double k = (tmp*size)/100 ; int t = (int)Math.round(k) ; string = "" + (double) t*100/size ; infoVote[j] = string + ":" + t ; } infoVote[l] = "" + temp ; if(poll.getIsMultiCheck()) { infoVote[l] = String.valueOf(userVotes.length) ; } return infoVote ; } static public class VoteActionListener extends EventListener<UIPoll> { @SuppressWarnings("unchecked") public void execute(Event<UIPoll> event) throws Exception { UIPoll topicPoll = event.getSource() ; Poll poll = topicPoll.poll_ ; String[] votes ; String[] setUserVote ; String userVote = topicPoll.userId ; List<UIComponent> children = topicPoll.getChildren() ; //User vote and vote number String[] temporary = topicPoll.poll_.getUserVote() ; int size = 0 ; if(temporary != null && temporary.length > 0) { size = temporary.length ; } if(!poll.getIsMultiCheck()) { UIFormRadioBoxInput radioInput = null ; for(UIComponent child : children) { if(child instanceof UIFormRadioBoxInput) { radioInput = (UIFormRadioBoxInput) child ; } } if(radioInput.getValue().equalsIgnoreCase("vote")) { topicPoll.warning("UITopicPoll.msg.notCheck") ; } else { // order number List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; options = radioInput.getOptions() ; int i = 0, j = 0 ; for (SelectItemOption<String> option : options) { if(option.getValue().equalsIgnoreCase(radioInput.getValue())){ j = i ; break ;} i = i + 1; } int index = 0 ; if(topicPoll.isAgainVote) { setUserVote = new String[size] ; for (int t = 0; t < size; t++) { String string = temporary[t].substring(0, temporary[t].length() - 2) ; if(string.equalsIgnoreCase(userVote)) { setUserVote[t] = userVote + ":" + j; index = t; } else { setUserVote[t] = temporary[t]; } } } else { setUserVote = new String[(size+1)] ; for (int t = 0; t < size; t++) { setUserVote[t] = temporary[t]; } setUserVote[size] = userVote + ":" + j; size = size + 1 ; } votes = topicPoll.poll_.getVote() ; double onePercent = (double)100/size; if(topicPoll.isAgainVote) { char tmp = temporary[index].charAt((temporary[index].length() - 1)); int k = Integer.valueOf(tmp) - 48; if( k < votes.length) votes[k] = String.valueOf((Double.parseDouble(votes[k]) - onePercent)) ; votes[j] = String.valueOf((Double.parseDouble(votes[j]) + onePercent)) ; } else { i = 0; for(String vote : votes) { double a = Double.parseDouble(vote) ; if(i == j) votes[i] = "" + ((a - a/size)+ onePercent) ; else votes[i] = "" + (a - a/size) ; i = i + 1; } } //save Poll poll.setVote(votes) ; poll.setUserVote(setUserVote) ; } // multichoice when vote } else { UIForumCheckBoxInput forumCheckBox = null ; List<String> listValue = new ArrayList<String>() ; for(UIComponent child : children) { if(child instanceof UIForumCheckBoxInput){ forumCheckBox = ((UIForumCheckBoxInput)child) ; if(forumCheckBox.isChecked()) { listValue.add(forumCheckBox.getName()) ; } } } if(!listValue.isEmpty()) { votes = topicPoll.poll_.getVote() ; double totalVote = 0 ; double doubleVote[] = new double[votes.length] ; String[] listUserVoted = topicPoll.poll_.getUserVote() ; if(listUserVoted.length > 0) { for(String us : listUserVoted) { totalVote += us.split(":").length - 1 ; } } int i = 0 ; int pos = 0 ; if( votes!= null && votes.length > 0) { for(String v : votes) { doubleVote[i++] = Double.parseDouble(v) ; } } if(totalVote > 0) { for( i = 0 ; i < doubleVote.length ; i ++) { doubleVote[i] = (doubleVote[i]*totalVote)/100 ; } } if(!topicPoll.isAgainVote) { i = 0 ; pos = size ; setUserVote = new String[size + 1] ; for(String userHaveVoted : poll.getUserVote()) setUserVote[i++] = userHaveVoted ; setUserVote[i] = userVote ; } else { setUserVote = poll.getUserVote() ; for( i = 0 ; i < setUserVote.length ; i ++) { if(setUserVote[i].split(":")[0].equals(userVote)) { pos = i ; break ; } } String[] posHaveVoted = (setUserVote[pos].substring(setUserVote[pos].indexOf(":"))).split(":") ; setUserVote[pos] = setUserVote[pos].substring(0, setUserVote[pos].indexOf(":")) ; for(String posVoted : posHaveVoted) { if(!Utils.isEmpty(posVoted)) { doubleVote[Integer.parseInt(posVoted)] -= 1 ; totalVote -= 1 ; } } } i = 0 ; for(String option : topicPoll.poll_.getOption()) { if(listValue.contains(option)) { doubleVote[i] += 1 ; totalVote += 1 ; setUserVote[pos] += ":" + i ; } i ++ ; } i = 0 ; for(double dv : doubleVote) { - if(totalVote > 0) + if(totalVote > 0 && dv > 0) votes[i] = ((dv/totalVote)*100) + "" ; else - votes[i] = "0" ; + votes[i] = "0.0" ; i ++ ; } // save votes: poll.setUserVote(setUserVote) ; poll.setVote(votes) ; } else { topicPoll.warning("UITopicPoll.msg.notCheck") ; } } topicPoll.getPollService().savePoll(poll, false, true) ; topicPoll.isAgainVote = false ; event.getRequestContext().addUIComponentToUpdateByAjax(topicPoll.getParent()) ; } } static public class EditPollActionListener extends BaseEventListener<UIPoll> { public void onEvent(Event<UIPoll> event, UIPoll topicPoll, final String objectId) throws Exception { UIPopupAction popupAction ; try { UIPollPortlet forumPortlet = topicPoll.getAncestorOfType(UIPollPortlet.class) ; popupAction = forumPortlet.getChild(UIPopupAction.class) ; } catch (Exception e) { UIPollPortlet forumPollPortlet = topicPoll.getAncestorOfType(UIPollPortlet.class) ; popupAction = forumPollPortlet.getChild(UIPopupAction.class) ; } UIPollForm pollForm = popupAction.createUIComponent(UIPollForm.class, null, null) ; topicPoll.poll_ = topicPoll.getPoll(); pollForm.setUpdatePoll(topicPoll.poll_, true) ; popupAction.activate(pollForm, 662, 466) ; topicPoll.isEditPoll = true ; } } static public class RemovePollActionListener extends EventListener<UIPoll> { public void execute(Event<UIPoll> event) throws Exception { UIPoll topicPoll = event.getSource() ; try { topicPoll.getPollService().removePoll(topicPoll.pollId) ; } catch (Exception e) { } if(topicPoll.poll_.getIsMultiCheck()) { List<UIComponent> children = topicPoll.getChildren() ; for (int i = 0; i < children.size(); i++) { topicPoll.removeChild(UIForumCheckBoxInput.class) ; } } else { topicPoll.removeChild(UIFormRadioBoxInput.class) ; } UIPollPortlet pollPortlet = topicPoll.getAncestorOfType(UIPollPortlet.class) ; topicPoll.setRendered(false); event.getRequestContext().addUIComponentToUpdateByAjax(pollPortlet) ; } } static public class VoteAgainPollActionListener extends EventListener<UIPoll> { public void execute(Event<UIPoll> event) throws Exception { UIPoll topicPoll = event.getSource() ; topicPoll.isAgainVote = true ; topicPoll.poll_= topicPoll.getPoll(); topicPoll.init() ; event.getRequestContext().addUIComponentToUpdateByAjax(topicPoll) ; } } static public class ClosedPollActionListener extends BaseEventListener<UIPoll> { public void onEvent(Event<UIPoll> event, UIPoll topicPoll, final String id) throws Exception { if(id.equals("true")) { topicPoll.poll_.setIsClosed(false) ; topicPoll.poll_.setTimeOut(0); } else { topicPoll.poll_.setIsClosed(!topicPoll.poll_.getIsClosed()) ; } try { topicPoll.getPollService().setClosedPoll(topicPoll.poll_) ; } catch (Exception e) { } topicPoll.isAgainVote = false ; event.getRequestContext().addUIComponentToUpdateByAjax(topicPoll) ; } } }
false
true
public void execute(Event<UIPoll> event) throws Exception { UIPoll topicPoll = event.getSource() ; Poll poll = topicPoll.poll_ ; String[] votes ; String[] setUserVote ; String userVote = topicPoll.userId ; List<UIComponent> children = topicPoll.getChildren() ; //User vote and vote number String[] temporary = topicPoll.poll_.getUserVote() ; int size = 0 ; if(temporary != null && temporary.length > 0) { size = temporary.length ; } if(!poll.getIsMultiCheck()) { UIFormRadioBoxInput radioInput = null ; for(UIComponent child : children) { if(child instanceof UIFormRadioBoxInput) { radioInput = (UIFormRadioBoxInput) child ; } } if(radioInput.getValue().equalsIgnoreCase("vote")) { topicPoll.warning("UITopicPoll.msg.notCheck") ; } else { // order number List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; options = radioInput.getOptions() ; int i = 0, j = 0 ; for (SelectItemOption<String> option : options) { if(option.getValue().equalsIgnoreCase(radioInput.getValue())){ j = i ; break ;} i = i + 1; } int index = 0 ; if(topicPoll.isAgainVote) { setUserVote = new String[size] ; for (int t = 0; t < size; t++) { String string = temporary[t].substring(0, temporary[t].length() - 2) ; if(string.equalsIgnoreCase(userVote)) { setUserVote[t] = userVote + ":" + j; index = t; } else { setUserVote[t] = temporary[t]; } } } else { setUserVote = new String[(size+1)] ; for (int t = 0; t < size; t++) { setUserVote[t] = temporary[t]; } setUserVote[size] = userVote + ":" + j; size = size + 1 ; } votes = topicPoll.poll_.getVote() ; double onePercent = (double)100/size; if(topicPoll.isAgainVote) { char tmp = temporary[index].charAt((temporary[index].length() - 1)); int k = Integer.valueOf(tmp) - 48; if( k < votes.length) votes[k] = String.valueOf((Double.parseDouble(votes[k]) - onePercent)) ; votes[j] = String.valueOf((Double.parseDouble(votes[j]) + onePercent)) ; } else { i = 0; for(String vote : votes) { double a = Double.parseDouble(vote) ; if(i == j) votes[i] = "" + ((a - a/size)+ onePercent) ; else votes[i] = "" + (a - a/size) ; i = i + 1; } } //save Poll poll.setVote(votes) ; poll.setUserVote(setUserVote) ; } // multichoice when vote } else { UIForumCheckBoxInput forumCheckBox = null ; List<String> listValue = new ArrayList<String>() ; for(UIComponent child : children) { if(child instanceof UIForumCheckBoxInput){ forumCheckBox = ((UIForumCheckBoxInput)child) ; if(forumCheckBox.isChecked()) { listValue.add(forumCheckBox.getName()) ; } } } if(!listValue.isEmpty()) { votes = topicPoll.poll_.getVote() ; double totalVote = 0 ; double doubleVote[] = new double[votes.length] ; String[] listUserVoted = topicPoll.poll_.getUserVote() ; if(listUserVoted.length > 0) { for(String us : listUserVoted) { totalVote += us.split(":").length - 1 ; } } int i = 0 ; int pos = 0 ; if( votes!= null && votes.length > 0) { for(String v : votes) { doubleVote[i++] = Double.parseDouble(v) ; } } if(totalVote > 0) { for( i = 0 ; i < doubleVote.length ; i ++) { doubleVote[i] = (doubleVote[i]*totalVote)/100 ; } } if(!topicPoll.isAgainVote) { i = 0 ; pos = size ; setUserVote = new String[size + 1] ; for(String userHaveVoted : poll.getUserVote()) setUserVote[i++] = userHaveVoted ; setUserVote[i] = userVote ; } else { setUserVote = poll.getUserVote() ; for( i = 0 ; i < setUserVote.length ; i ++) { if(setUserVote[i].split(":")[0].equals(userVote)) { pos = i ; break ; } } String[] posHaveVoted = (setUserVote[pos].substring(setUserVote[pos].indexOf(":"))).split(":") ; setUserVote[pos] = setUserVote[pos].substring(0, setUserVote[pos].indexOf(":")) ; for(String posVoted : posHaveVoted) { if(!Utils.isEmpty(posVoted)) { doubleVote[Integer.parseInt(posVoted)] -= 1 ; totalVote -= 1 ; } } } i = 0 ; for(String option : topicPoll.poll_.getOption()) { if(listValue.contains(option)) { doubleVote[i] += 1 ; totalVote += 1 ; setUserVote[pos] += ":" + i ; } i ++ ; } i = 0 ; for(double dv : doubleVote) { if(totalVote > 0) votes[i] = ((dv/totalVote)*100) + "" ; else votes[i] = "0" ; i ++ ; } // save votes: poll.setUserVote(setUserVote) ; poll.setVote(votes) ; } else { topicPoll.warning("UITopicPoll.msg.notCheck") ; } } topicPoll.getPollService().savePoll(poll, false, true) ; topicPoll.isAgainVote = false ; event.getRequestContext().addUIComponentToUpdateByAjax(topicPoll.getParent()) ; }
public void execute(Event<UIPoll> event) throws Exception { UIPoll topicPoll = event.getSource() ; Poll poll = topicPoll.poll_ ; String[] votes ; String[] setUserVote ; String userVote = topicPoll.userId ; List<UIComponent> children = topicPoll.getChildren() ; //User vote and vote number String[] temporary = topicPoll.poll_.getUserVote() ; int size = 0 ; if(temporary != null && temporary.length > 0) { size = temporary.length ; } if(!poll.getIsMultiCheck()) { UIFormRadioBoxInput radioInput = null ; for(UIComponent child : children) { if(child instanceof UIFormRadioBoxInput) { radioInput = (UIFormRadioBoxInput) child ; } } if(radioInput.getValue().equalsIgnoreCase("vote")) { topicPoll.warning("UITopicPoll.msg.notCheck") ; } else { // order number List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ; options = radioInput.getOptions() ; int i = 0, j = 0 ; for (SelectItemOption<String> option : options) { if(option.getValue().equalsIgnoreCase(radioInput.getValue())){ j = i ; break ;} i = i + 1; } int index = 0 ; if(topicPoll.isAgainVote) { setUserVote = new String[size] ; for (int t = 0; t < size; t++) { String string = temporary[t].substring(0, temporary[t].length() - 2) ; if(string.equalsIgnoreCase(userVote)) { setUserVote[t] = userVote + ":" + j; index = t; } else { setUserVote[t] = temporary[t]; } } } else { setUserVote = new String[(size+1)] ; for (int t = 0; t < size; t++) { setUserVote[t] = temporary[t]; } setUserVote[size] = userVote + ":" + j; size = size + 1 ; } votes = topicPoll.poll_.getVote() ; double onePercent = (double)100/size; if(topicPoll.isAgainVote) { char tmp = temporary[index].charAt((temporary[index].length() - 1)); int k = Integer.valueOf(tmp) - 48; if( k < votes.length) votes[k] = String.valueOf((Double.parseDouble(votes[k]) - onePercent)) ; votes[j] = String.valueOf((Double.parseDouble(votes[j]) + onePercent)) ; } else { i = 0; for(String vote : votes) { double a = Double.parseDouble(vote) ; if(i == j) votes[i] = "" + ((a - a/size)+ onePercent) ; else votes[i] = "" + (a - a/size) ; i = i + 1; } } //save Poll poll.setVote(votes) ; poll.setUserVote(setUserVote) ; } // multichoice when vote } else { UIForumCheckBoxInput forumCheckBox = null ; List<String> listValue = new ArrayList<String>() ; for(UIComponent child : children) { if(child instanceof UIForumCheckBoxInput){ forumCheckBox = ((UIForumCheckBoxInput)child) ; if(forumCheckBox.isChecked()) { listValue.add(forumCheckBox.getName()) ; } } } if(!listValue.isEmpty()) { votes = topicPoll.poll_.getVote() ; double totalVote = 0 ; double doubleVote[] = new double[votes.length] ; String[] listUserVoted = topicPoll.poll_.getUserVote() ; if(listUserVoted.length > 0) { for(String us : listUserVoted) { totalVote += us.split(":").length - 1 ; } } int i = 0 ; int pos = 0 ; if( votes!= null && votes.length > 0) { for(String v : votes) { doubleVote[i++] = Double.parseDouble(v) ; } } if(totalVote > 0) { for( i = 0 ; i < doubleVote.length ; i ++) { doubleVote[i] = (doubleVote[i]*totalVote)/100 ; } } if(!topicPoll.isAgainVote) { i = 0 ; pos = size ; setUserVote = new String[size + 1] ; for(String userHaveVoted : poll.getUserVote()) setUserVote[i++] = userHaveVoted ; setUserVote[i] = userVote ; } else { setUserVote = poll.getUserVote() ; for( i = 0 ; i < setUserVote.length ; i ++) { if(setUserVote[i].split(":")[0].equals(userVote)) { pos = i ; break ; } } String[] posHaveVoted = (setUserVote[pos].substring(setUserVote[pos].indexOf(":"))).split(":") ; setUserVote[pos] = setUserVote[pos].substring(0, setUserVote[pos].indexOf(":")) ; for(String posVoted : posHaveVoted) { if(!Utils.isEmpty(posVoted)) { doubleVote[Integer.parseInt(posVoted)] -= 1 ; totalVote -= 1 ; } } } i = 0 ; for(String option : topicPoll.poll_.getOption()) { if(listValue.contains(option)) { doubleVote[i] += 1 ; totalVote += 1 ; setUserVote[pos] += ":" + i ; } i ++ ; } i = 0 ; for(double dv : doubleVote) { if(totalVote > 0 && dv > 0) votes[i] = ((dv/totalVote)*100) + "" ; else votes[i] = "0.0" ; i ++ ; } // save votes: poll.setUserVote(setUserVote) ; poll.setVote(votes) ; } else { topicPoll.warning("UITopicPoll.msg.notCheck") ; } } topicPoll.getPollService().savePoll(poll, false, true) ; topicPoll.isAgainVote = false ; event.getRequestContext().addUIComponentToUpdateByAjax(topicPoll.getParent()) ; }
diff --git a/plugins/appfuse-maven-plugin/src/test/java/org/appfuse/mojo/exporter/GenerateSpringTest.java b/plugins/appfuse-maven-plugin/src/test/java/org/appfuse/mojo/exporter/GenerateSpringTest.java index 22894b3b..6376152e 100644 --- a/plugins/appfuse-maven-plugin/src/test/java/org/appfuse/mojo/exporter/GenerateSpringTest.java +++ b/plugins/appfuse-maven-plugin/src/test/java/org/appfuse/mojo/exporter/GenerateSpringTest.java @@ -1,52 +1,52 @@ package org.appfuse.mojo.exporter; import org.appfuse.mojo.AbstractAppFuseMojoTestCase; import org.appfuse.mojo.HibernateExporterMojo; public final class GenerateSpringTest extends AbstractAppFuseMojoTestCase { public void testGenerateSpring() throws Exception { deleteDirectory("target/appfuse/generated"); HibernateExporterMojo mojo = getHibernateMojo("gen", "annotationconfiguration"); mojo.getProject().getProperties().setProperty("web.framework", "spring"); mojo.execute(); assertTrue("can't find PersonFormControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonFormControllerTest.java")); assertTrue("can't find /PersonFormController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonFormController.java")); assertTrue("can't find PersonControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonControllerTest.java")); assertTrue("can't find /PersonController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonController.java")); assertTrue("can't find Persons.jsp", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/Persons.jsp")); - assertTrue("can't find PersonForm.jsp", - checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/PersonForm.jsp")); + assertTrue("can't find Personform.jsp", + checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/Personform.jsp")); assertTrue("can't find Person-beans.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-beans.xml")); assertTrue("can't find Person-validation.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-validation.xml")); assertTrue("can't find ApplicationResources.properties", checkExists("target/appfuse/generated/src/main/resources/Person-ApplicationResources.properties")); assertTrue("can't find web-tests.xml", checkExists("target/appfuse/generated/src/test/resources/Person-web-tests.xml")); } @Override protected void setUp() throws Exception { System.setProperty("entity", "Person"); System.setProperty("type", "pojo"); super.setUp(); } }
true
true
public void testGenerateSpring() throws Exception { deleteDirectory("target/appfuse/generated"); HibernateExporterMojo mojo = getHibernateMojo("gen", "annotationconfiguration"); mojo.getProject().getProperties().setProperty("web.framework", "spring"); mojo.execute(); assertTrue("can't find PersonFormControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonFormControllerTest.java")); assertTrue("can't find /PersonFormController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonFormController.java")); assertTrue("can't find PersonControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonControllerTest.java")); assertTrue("can't find /PersonController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonController.java")); assertTrue("can't find Persons.jsp", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/Persons.jsp")); assertTrue("can't find PersonForm.jsp", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/PersonForm.jsp")); assertTrue("can't find Person-beans.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-beans.xml")); assertTrue("can't find Person-validation.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-validation.xml")); assertTrue("can't find ApplicationResources.properties", checkExists("target/appfuse/generated/src/main/resources/Person-ApplicationResources.properties")); assertTrue("can't find web-tests.xml", checkExists("target/appfuse/generated/src/test/resources/Person-web-tests.xml")); }
public void testGenerateSpring() throws Exception { deleteDirectory("target/appfuse/generated"); HibernateExporterMojo mojo = getHibernateMojo("gen", "annotationconfiguration"); mojo.getProject().getProperties().setProperty("web.framework", "spring"); mojo.execute(); assertTrue("can't find PersonFormControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonFormControllerTest.java")); assertTrue("can't find /PersonFormController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonFormController.java")); assertTrue("can't find PersonControllerTest.java", checkExists("target/appfuse/generated/src/test/java/annotationconfiguration/webapp/controller/PersonControllerTest.java")); assertTrue("can't find /PersonController.java", checkExists("target/appfuse/generated/src/main/java/annotationconfiguration/webapp/controller/PersonController.java")); assertTrue("can't find Persons.jsp", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/Persons.jsp")); assertTrue("can't find Personform.jsp", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/pages/Personform.jsp")); assertTrue("can't find Person-beans.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-beans.xml")); assertTrue("can't find Person-validation.xml", checkExists("target/appfuse/generated/src/main/webapp/WEB-INF/Person-validation.xml")); assertTrue("can't find ApplicationResources.properties", checkExists("target/appfuse/generated/src/main/resources/Person-ApplicationResources.properties")); assertTrue("can't find web-tests.xml", checkExists("target/appfuse/generated/src/test/resources/Person-web-tests.xml")); }
diff --git a/src/ua/in/leopard/androidCoocooAfisha/SeanceAdapterView.java b/src/ua/in/leopard/androidCoocooAfisha/SeanceAdapterView.java index 94bd290..1e57bbf 100644 --- a/src/ua/in/leopard/androidCoocooAfisha/SeanceAdapterView.java +++ b/src/ua/in/leopard/androidCoocooAfisha/SeanceAdapterView.java @@ -1,61 +1,63 @@ package ua.in.leopard.androidCoocooAfisha; import android.content.Context; import android.graphics.Bitmap; import android.text.Html; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class SeanceAdapterView extends LinearLayout { public SeanceAdapterView(Context context, CinemaDB entry) { super(context); this.setOrientation(VERTICAL); this.setTag(entry); View v = inflate(context, R.layout.seance_row, null); ImageView cinemaPoster = (ImageView)v.findViewById(R.id.cinema_poster); Bitmap poster = entry.getPosterImg(); if (poster != null){ cinemaPoster.setImageBitmap(poster); } else { cinemaPoster.setImageResource(R.drawable.poster); } TextView cinemaTitle = (TextView)v.findViewById(R.id.cinema_title); cinemaTitle.setText(entry.getTitle()); TextView origTitle = (TextView)v.findViewById(R.id.cinema_orig_title); origTitle.setText(Html.fromHtml(entry.getOrigTitle())); TextView zalTitle = (TextView)v.findViewById(R.id.cinema_zal_title); if (entry.getZalTitle() == null){ zalTitle.setText(R.string.not_set); } else { zalTitle.setText(Html.fromHtml(entry.getZalTitle())); } TextView cinemaTimes = (TextView)v.findViewById(R.id.cinema_times); if (entry.getTimes() == null){ cinemaTimes.setText(R.string.not_set); } else { - cinemaTimes.setText(entry.getTimes()); + String cinema_times = entry.getTimes(); + cinema_times = cinema_times.replaceAll("(?i)([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]);", "$1:$2;"); + cinemaTimes.setText(cinema_times); } TextView cinemaPrices = (TextView)v.findViewById(R.id.cinema_prices); if (entry.getPrices() == null){ cinemaPrices.setText(R.string.not_set); } else { cinemaPrices.setText(entry.getPrices()); } addView(v); } }
true
true
public SeanceAdapterView(Context context, CinemaDB entry) { super(context); this.setOrientation(VERTICAL); this.setTag(entry); View v = inflate(context, R.layout.seance_row, null); ImageView cinemaPoster = (ImageView)v.findViewById(R.id.cinema_poster); Bitmap poster = entry.getPosterImg(); if (poster != null){ cinemaPoster.setImageBitmap(poster); } else { cinemaPoster.setImageResource(R.drawable.poster); } TextView cinemaTitle = (TextView)v.findViewById(R.id.cinema_title); cinemaTitle.setText(entry.getTitle()); TextView origTitle = (TextView)v.findViewById(R.id.cinema_orig_title); origTitle.setText(Html.fromHtml(entry.getOrigTitle())); TextView zalTitle = (TextView)v.findViewById(R.id.cinema_zal_title); if (entry.getZalTitle() == null){ zalTitle.setText(R.string.not_set); } else { zalTitle.setText(Html.fromHtml(entry.getZalTitle())); } TextView cinemaTimes = (TextView)v.findViewById(R.id.cinema_times); if (entry.getTimes() == null){ cinemaTimes.setText(R.string.not_set); } else { cinemaTimes.setText(entry.getTimes()); } TextView cinemaPrices = (TextView)v.findViewById(R.id.cinema_prices); if (entry.getPrices() == null){ cinemaPrices.setText(R.string.not_set); } else { cinemaPrices.setText(entry.getPrices()); } addView(v); }
public SeanceAdapterView(Context context, CinemaDB entry) { super(context); this.setOrientation(VERTICAL); this.setTag(entry); View v = inflate(context, R.layout.seance_row, null); ImageView cinemaPoster = (ImageView)v.findViewById(R.id.cinema_poster); Bitmap poster = entry.getPosterImg(); if (poster != null){ cinemaPoster.setImageBitmap(poster); } else { cinemaPoster.setImageResource(R.drawable.poster); } TextView cinemaTitle = (TextView)v.findViewById(R.id.cinema_title); cinemaTitle.setText(entry.getTitle()); TextView origTitle = (TextView)v.findViewById(R.id.cinema_orig_title); origTitle.setText(Html.fromHtml(entry.getOrigTitle())); TextView zalTitle = (TextView)v.findViewById(R.id.cinema_zal_title); if (entry.getZalTitle() == null){ zalTitle.setText(R.string.not_set); } else { zalTitle.setText(Html.fromHtml(entry.getZalTitle())); } TextView cinemaTimes = (TextView)v.findViewById(R.id.cinema_times); if (entry.getTimes() == null){ cinemaTimes.setText(R.string.not_set); } else { String cinema_times = entry.getTimes(); cinema_times = cinema_times.replaceAll("(?i)([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]);", "$1:$2;"); cinemaTimes.setText(cinema_times); } TextView cinemaPrices = (TextView)v.findViewById(R.id.cinema_prices); if (entry.getPrices() == null){ cinemaPrices.setText(R.string.not_set); } else { cinemaPrices.setText(entry.getPrices()); } addView(v); }
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java index 9dd7121..8a20205 100644 --- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java +++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java @@ -1,186 +1,186 @@ package uk.ac.gla.dcs.tp3.w.algorithm; import java.util.LinkedList; import uk.ac.gla.dcs.tp3.w.league.League; import uk.ac.gla.dcs.tp3.w.league.Match; import uk.ac.gla.dcs.tp3.w.league.Team; public class Graph { private Vertex[] vertices; private int[][] matrix; private Vertex source; private Vertex sink; public Graph() { this(null, null); } public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; - for (int i = 0; i < teamsReal.length; i++) { - vertices[pos] = new TeamVertex(teamsReal[i], pos); + for (int i = 0; i < teams.length; i++) { + vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( - new AdjListNode(teamsReal[i].getUpcomingMatches().length, + new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; int infinity = Integer.MAX_VALUE; for (int i = 0; i < teamTotal + 1; i++) { for (int j = 1; j < teamTotal; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. } public Vertex[] getV() { return vertices; } public void setV(Vertex[] v) { this.vertices = v; } public int[][] getMatrix() { return matrix; } public int getSize() { return vertices.length; } public void setMatrix(int[][] matrix) { this.matrix = matrix; } public Vertex getSource() { return source; } public void setSource(Vertex source) { this.source = source; } public Vertex getSink() { return sink; } public void setSink(Vertex sink) { this.sink = sink; } private static int fact(int s) { // For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1) return (s < 2) ? 1 : s * fact(s - 1); } private static int comb(int n, int r) { // r-combination of size n is n!/r!(n-r)! return (fact(n) / (fact(r) * fact(n - r))); } /** * carry out a breadth first search/traversal of the graph */ public void bfs() { // TODO Read over this code, I (GR) just dropped this in here from // bfs-example. for (Vertex v : vertices) v.setVisited(false); LinkedList<Vertex> queue = new LinkedList<Vertex>(); for (Vertex v : vertices) { if (!v.getVisited()) { v.setVisited(true); v.setPredecessor(v.getIndex()); queue.add(v); while (!queue.isEmpty()) { Vertex u = queue.removeFirst(); LinkedList<AdjListNode> list = u.getAdjList(); for (AdjListNode node : list) { Vertex w = node.getVertex(); if (!w.getVisited()) { w.setVisited(true); w.setPredecessor(u.getIndex()); queue.add(w); } } } } } } }
false
true
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teamsReal.length; i++) { vertices[pos] = new TeamVertex(teamsReal[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teamsReal[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; int infinity = Integer.MAX_VALUE; for (int i = 0; i < teamTotal + 1; i++) { for (int j = 1; j < teamTotal; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; int infinity = Integer.MAX_VALUE; for (int i = 0; i < teamTotal + 1; i++) { for (int j = 1; j < teamTotal; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java index 41b56685..7b8d6986 100644 --- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java +++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/servlet/AjaxServlet.java @@ -1,2523 +1,2523 @@ package gov.nih.nci.evs.browser.servlet; import org.json.*; import gov.nih.nci.evs.browser.utils.*; import gov.nih.nci.evs.browser.common.*; import java.io.*; import java.util.*; import java.net.URI; import javax.servlet.*; import javax.servlet.http.*; import org.apache.log4j.*; import gov.nih.nci.evs.browser.properties.*; import static gov.nih.nci.evs.browser.common.Constants.*; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.LexBIG.DataModel.Collections.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.LexBIGService.*; import org.LexGrid.LexBIG.Utility.*; import org.LexGrid.codingSchemes.*; import org.LexGrid.naming.*; import org.LexGrid.LexBIG.Impl.Extensions.GenericExtensions.*; import org.apache.log4j.*; import javax.faces.event.ValueChangeEvent; import org.LexGrid.LexBIG.caCore.interfaces.LexEVSDistributed; import org.lexgrid.valuesets.LexEVSValueSetDefinitionServices; import org.LexGrid.valueSets.ValueSetDefinition; import org.LexGrid.commonTypes.Source; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.lexgrid.valuesets.dto.ResolvedValueSetDefinition; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; import javax.servlet.ServletOutputStream; import org.LexGrid.concepts.*; import org.lexgrid.valuesets.dto.ResolvedValueSetCodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.concepts.Definition; import org.LexGrid.commonTypes.PropertyQualifier; import org.LexGrid.commonTypes.Property; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * 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 disclaimer of Article 3, * below. 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. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED 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 NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation kim.ong@ngc.com * */ public final class AjaxServlet extends HttpServlet { private static Logger _logger = Logger.getLogger(AjaxServlet.class); /** * local constants */ private static final long serialVersionUID = 1L; //private static final int STANDARD_VIEW = 1; //private static final int TERMINOLOGY_VIEW = 2; /** * Validates the Init and Context parameters, configures authentication URL * * @throws ServletException if the init parameters are invalid or any other * problems occur during initialisation */ public void init() throws ServletException { } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } /** * Route the user to the execute method * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a Servlet exception occurs */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { execute(request, response); } private static void debugJSONString(String msg, String jsonString) { boolean debug = false; //DYEE_DEBUG (default: false) if (! debug) return; _logger.debug(Utils.SEPARATOR); if (msg != null && msg.length() > 0) _logger.debug(msg); _logger.debug("jsonString: " + jsonString); _logger.debug("jsonString length: " + jsonString.length()); Utils.debugJSONString(jsonString); } public static void search_tree(HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { try { String jsonString = search_tree(node_id, ontology_display_name, ontology_version); if (jsonString == null) return; JSONObject json = new JSONObject(); JSONArray rootsArray = new JSONArray(jsonString); json.put("root_nodes", rootsArray); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(json.toString()); response.getWriter().flush(); } catch (Exception e) { e.printStackTrace(); } } public static String search_tree(String node_id, String ontology_display_name, String ontology_version) throws Exception { if (node_id == null || ontology_display_name == null) return null; Utils.StopWatch stopWatch = new Utils.StopWatch(); // String max_tree_level_str = // NCItBrowserProperties.getProperty( // NCItBrowserProperties.MAXIMUM_TREE_LEVEL); // int maxLevel = Integer.parseInt(max_tree_level_str); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (ontology_version != null) versionOrTag.setVersion(ontology_version); String jsonString = CacheController.getTree( ontology_display_name, versionOrTag, node_id); debugJSONString("Section: search_tree", jsonString); _logger.debug("search_tree: " + stopWatch.getResult()); return jsonString; } /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * * @param request The HTTP request we are processing * @param response The HTTP response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet exception occurs */ public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Determine request by attributes String action = request.getParameter("action");// DataConstants.ACTION); String node_id = request.getParameter("ontology_node_id");// DataConstants.ONTOLOGY_NODE_ID); String ontology_display_name = request.getParameter("ontology_display_name");// DataConstants.ONTOLOGY_DISPLAY_NAME); String ontology_version = request.getParameter("version"); if (ontology_version == null) { ontology_version = DataUtils.getVocabularyVersionByTag(ontology_display_name, "PRODUCTION"); } long ms = System.currentTimeMillis(); if (action.equals("expand_tree")) { if (node_id != null && ontology_display_name != null) { System.out.println("(*) EXPAND TREE NODE: " + node_id); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { /* // for HL7 (temporary fix) ontology_display_name = DataUtils.searchFormalName(ontology_display_name); */ nodesArray = CacheController.getInstance().getSubconcepts( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } debugJSONString("Section: expand_tree", json.toString()); response.getWriter().write(json.toString()); /* _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); */ } } /* * else if (action.equals("search_tree")) { * * * if (node_id != null && ontology_display_name != null) { * response.setContentType("text/html"); * response.setHeader("Cache-Control", "no-cache"); JSONObject json = * new JSONObject(); try { // testing // JSONArray rootsArray = // * CacheController.getInstance().getPathsToRoots(ontology_display_name, * // null, node_id, true); * * String max_tree_level_str = null; int maxLevel = -1; try { * max_tree_level_str = NCItBrowserProperties .getInstance() * .getProperty( NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxLevel = * Integer.parseInt(max_tree_level_str); * * } catch (Exception ex) { * * } * * JSONArray rootsArray = CacheController.getInstance() * .getPathsToRoots(ontology_display_name, null, node_id, true, * maxLevel); * * if (rootsArray.length() == 0) { rootsArray = * CacheController.getInstance() .getRootConcepts(ontology_display_name, * null); * * boolean is_root = isRoot(rootsArray, node_id); if (!is_root) { * //rootsArray = null; json.put("dummy_root_nodes", rootsArray); * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } * json.put("root_nodes", rootsArray); } catch (Exception e) { * e.printStackTrace(); } * * response.getWriter().write(json.toString()); * response.getWriter().flush(); * * _logger.debug("Run time (milliseconds): " + * (System.currentTimeMillis() - ms)); return; } } */ if (action.equals("search_value_set")) { search_value_set(request, response); } else if (action.equals("create_src_vs_tree")) { create_src_vs_tree(request, response); } else if (action.equals("create_cs_vs_tree")) { create_cs_vs_tree(request, response); } else if (action.equals("search_hierarchy")) { search_hierarchy(request, response, node_id, ontology_display_name, ontology_version); } else if (action.equals("search_tree")) { search_tree(response, node_id, ontology_display_name, ontology_version); } else if (action.equals("build_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { nodesArray = CacheController.getInstance().getRootConcepts( ontology_display_name, ontology_version); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } debugJSONString("Section: build_tree", json.toString()); response.getWriter().write(json.toString()); // response.getWriter().flush(); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("build_vs_tree")) { if (ontology_display_name == null) ontology_display_name = CODING_SCHEME_NAME; response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets( ontology_display_name, codingSchemeVersion); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSubValueSets( ontology_display_name, ontology_version, node_id); if (nodesArray != null) { System.out.println("expand_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getSourceValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("expand_entire_cs_vs_tree")) { //if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; try { nodesArray = CacheController.getInstance().getCodingSchemeValueSetTree( ontology_display_name, ontology_version, true); if (nodesArray != null) { System.out.println("expand_entire_vs_tree nodesArray != null"); json.put("root_nodes", nodesArray); } else { System.out.println("expand_entire_vs_tree nodesArray == null???"); } } catch (Exception e) { } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); //} } else if (action.equals("build_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = CacheController.getInstance().getRootValueSets(true); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_cs_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; String vsd_uri = ValueSetHierarchy.getValueSetURI(node_id); node_id = ValueSetHierarchy.getCodingSchemeName(node_id); //if (node_id != null && ontology_display_name != null) { if (node_id != null) { ValueSetDefinition vsd = ValueSetHierarchy.findValueSetDefinitionByURI(vsd_uri); if (vsd == null) { System.out.println("(****) coding scheme name: " + node_id); try { // nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //nodesArray = CacheController.getInstance().getRootValueSets(node_id, null); //find roots (by source) if (nodesArray != null) { json.put("nodes", nodesArray); } else { System.out.println("expand_vs_tree nodesArray == null???"); } } catch (Exception e) { } } else { try { nodesArray = CacheController.getInstance().getSubValueSets( node_id, null, vsd_uri); if (nodesArray != null) { json.put("nodes", nodesArray); } } catch (Exception e) { } } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } else if (action.equals("build_src_vs_tree")) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null;// new JSONArray(); try { //HashMap getRootValueSets(String codingSchemeURN) String codingSchemeVersion = null; nodesArray = //CacheController.getInstance().getRootValueSets(true, true); CacheController.getInstance().build_src_vs_tree(); if (nodesArray != null) { json.put("root_nodes", nodesArray); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); //System.out.println(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); return; } else if (action.equals("expand_src_vs_tree")) { if (node_id != null && ontology_display_name != null) { response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); JSONArray nodesArray = null; nodesArray = CacheController.getInstance().expand_src_vs_tree(node_id); if (nodesArray == null) { System.out.println("(*) CacheController returns nodesArray == null"); } try { if (nodesArray != null) { System.out.println("expand_src_vs_tree nodesArray != null"); json.put("nodes", nodesArray); } else { System.out.println("expand_src_vs_tree nodesArray == null???"); } } catch (Exception e) { e.printStackTrace(); } response.getWriter().write(json.toString()); _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms)); } } } private boolean isRoot(JSONArray rootsArray, String code) { for (int i = 0; i < rootsArray.length(); i++) { String node_id = null; try { JSONObject node = rootsArray.getJSONObject(i); node_id = (String) node.get(CacheController.ONTOLOGY_NODE_ID); if (node_id.compareTo(code) == 0) return true; } catch (Exception e) { e.printStackTrace(); } } return false; } private static boolean _debug = false; // DYEE_DEBUG (default: false) private static StringBuffer _debugBuffer = null; public static void println(PrintWriter out, String text) { if (_debug) { _logger.debug("DBG: " + text); _debugBuffer.append(text + "\n"); } out.println(text); } public static void search_hierarchy(HttpServletRequest request, HttpServletResponse response, String node_id, String ontology_display_name, String ontology_version) { Enumeration parameters = request.getParameterNames(); String param = null; while (parameters.hasMoreElements()) { param = (String) parameters.nextElement(); String paramValue = request.getParameter(param); } response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } if (_debug) { _debugBuffer = new StringBuffer(); } String localName = DataUtils.getLocalName(ontology_display_name); String formalName = DataUtils.getFormalName(localName); String term_browser_version = DataUtils.getMetadataValue(formalName, ontology_version, "term_browser_version"); String display_name = DataUtils.getMetadataValue(formalName, ontology_version, "display_name"); println(out, ""); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/yahoo-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/event-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/dom-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/animation-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/container-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/connection-min.js\" ></script>"); //println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/autocomplete-min.js\" ></script>"); println(out, "<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); println(out, ""); println(out, ""); println(out, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); println(out, "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">"); println(out, " <head>"); println(out, " <title>Vocabulary Hierarchy</title>"); println(out, " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); println(out, " <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/fonts.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/grids.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/code.css\" />"); println(out, " <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/yui/tree.css\" />"); println(out, " <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); println(out, ""); println(out, " <script language=\"JavaScript\">"); println(out, ""); println(out, " var tree;"); println(out, " var nodeIndex;"); println(out, " var rootDescDiv;"); println(out, " var emptyRootDiv;"); println(out, " var treeStatusDiv;"); println(out, " var nodes = [];"); println(out, " var currOpener;"); println(out, ""); println(out, " function load(url,target) {"); println(out, " if (target != '')"); println(out, " target.window.location.href = url;"); println(out, " else"); println(out, " window.location.href = url;"); println(out, " }"); println(out, ""); println(out, " function init() {"); println(out, ""); println(out, " rootDescDiv = new YAHOO.widget.Module(\"rootDesc\", {visible:false} );"); println(out, " resetRootDesc();"); println(out, ""); println(out, " emptyRootDiv = new YAHOO.widget.Module(\"emptyRoot\", {visible:true} );"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " treeStatusDiv = new YAHOO.widget.Module(\"treeStatus\", {visible:true} );"); println(out, " resetTreeStatus();"); println(out, ""); println(out, " currOpener = opener;"); println(out, " initTree();"); println(out, " }"); println(out, ""); println(out, " function addTreeNode(rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, false);"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function buildTree(ontology_node_id, ontology_display_name) {"); println(out, " var handleBuildTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_nodes) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " if (respObj.root_nodes.length == 0) {"); println(out, " showEmptyRoot();"); println(out, " }"); println(out, " else {"); println(out, " for (var i=0; i < respObj.root_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.root_nodes[i];"); println(out, " var expand = false;"); println(out, " addTreeNode(root, nodeInfo, expand);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleBuildTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " resetEmptyRoot();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var buildTreeCallback ="); println(out, " {"); println(out, " success:handleBuildTreeSuccess,"); println(out, " failure:handleBuildTreeFailure"); println(out, " };"); println(out, ""); println(out, " if (ontology_display_name!='') {"); println(out, " resetEmptyRoot();"); println(out, ""); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function resetTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var handleResetTreeSuccess = function(o) {"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " if ( typeof(respObj) != \"undefined\") {"); println(out, " if ( typeof(respObj.root_node) != \"undefined\") {"); println(out, " var root = tree.getRoot();"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); println(out, " var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); println(out, " var expand = false;"); println(out, " if (respObj.root_node.ontology_node_child_count > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var ontRoot = new YAHOO.widget.TextNode(rootNodeData, root, expand);"); println(out, ""); println(out, " if ( typeof(respObj.child_nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.child_nodes.length; i++) {"); println(out, " var nodeInfo = respObj.child_nodes[i];"); println(out, " addTreeNode(ontRoot, nodeInfo);"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " setRootDesc(respObj.root_node.ontology_node_name, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, " resetTreeStatus();"); println(out, " }"); println(out, ""); println(out, " var handleResetTreeFailure = function(o) {"); println(out, " resetTreeStatus();"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var resetTreeCallback ="); println(out, " {"); println(out, " success:handleResetTreeSuccess,"); println(out, " failure:handleResetTreeFailure"); println(out, " };"); println(out, " if (ontology_node_id!= '') {"); println(out, " showTreeLoadingStatus();"); println(out, " var ontology_source = null;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function onClickTreeNode(ontology_node_id) {"); out.println(" if (ontology_node_id.indexOf(\"_dot_\") != -1) return;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); println(out, " load('/ncitbrowser/ConceptReport.jsp?dictionary='+ ontology_display_name + '&version='+ ontology_version + '&code=' + ontology_node_id, currOpener);"); println(out, " }"); println(out, ""); println(out, " function onClickViewEntireOntology(ontology_display_name) {"); println(out, " var ontology_display_name = document.pg_form.ontology_display_name.value;"); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " tree.draw();"); println(out, " resetRootDesc();"); println(out, " buildTree('', ontology_display_name);"); println(out, " }"); println(out, ""); println(out, " function initTree() {"); println(out, ""); println(out, " tree = new YAHOO.widget.TreeView(\"treecontainer\");"); println(out, " var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, ""); println(out, " if (ontology_node_id == null || ontology_node_id == \"null\")"); println(out, " {"); println(out, " buildTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " else"); println(out, " {"); println(out, " searchTree(ontology_node_id, ontology_display_name);"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " function initRootDesc() {"); println(out, " rootDescDiv.setBody('');"); println(out, " initRootDesc.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetRootDesc() {"); println(out, " rootDescDiv.hide();"); println(out, " rootDescDiv.setBody('');"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetEmptyRoot() {"); println(out, " emptyRootDiv.hide();"); println(out, " emptyRootDiv.setBody('');"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function resetTreeStatus() {"); println(out, " treeStatusDiv.hide();"); println(out, " treeStatusDiv.setBody('');"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showEmptyRoot() {"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>No root nodes available.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showNodeNotFound(node_id) {"); println(out, " //emptyRootDiv.setBody(\"<span class='instruction_text'>Concept with code \" + node_id + \" not found in the hierarchy.</span>\");"); println(out, " emptyRootDiv.setBody(\"<span class='instruction_text'>Concept not part of the parent-child hierarchy in this source; check other relationships.</span>\");"); println(out, " emptyRootDiv.show();"); println(out, " emptyRootDiv.render();"); println(out, " }"); println(out, " "); println(out, " function showPartialHierarchy() {"); println(out, " rootDescDiv.setBody(\"<span class='instruction_text'>(Note: This tree only shows partial hierarchy.)</span>\");"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeLoadingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Building tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showTreeDrawingStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Drawing tree ...</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showSearchingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Searching tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); println(out, " function showConstructingTreeStatus() {"); println(out, " treeStatusDiv.setBody(\"<img src='/ncitbrowser/images/loading.gif'/> <span class='instruction_text'>Constructing tree... Please wait.</span>\");"); println(out, " treeStatusDiv.show();"); println(out, " treeStatusDiv.render();"); println(out, " }"); println(out, ""); /* println(out, " function loadNodeData(node, fnLoadComplete) {"); println(out, " var id = node.data.id;"); println(out, ""); println(out, " var responseSuccess = function(o)"); println(out, " {"); println(out, " var path;"); println(out, " var dirs;"); println(out, " var files;"); println(out, " var respTxt = o.responseText;"); println(out, " var respObj = eval('(' + respTxt + ')');"); println(out, " var fileNum = 0;"); println(out, " var categoryNum = 0;"); println(out, " if ( typeof(respObj.nodes) != \"undefined\") {"); println(out, " for (var i=0; i < respObj.nodes.length; i++) {"); println(out, " var name = respObj.nodes[i].ontology_node_name;"); println(out, " var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); println(out, " if (respObj.nodes[i].ontology_node_child_count > 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, " tree.draw();"); println(out, " fnLoadComplete();"); println(out, " }"); */ out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" var pos = id.indexOf(\"_dot_\");"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" if (pos == -1) {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(""); out.println(" var parent = node.parent;"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(""); out.println(" var newNode = new YAHOO.widget.TextNode(newNodeData, parent, true);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" tree.removeNode(node,true);"); out.println(" }"); out.println(" }"); out.println(" fnLoadComplete();"); out.println(" }"); println(out, ""); println(out, " var responseFailure = function(o){"); println(out, " alert('responseFailure: ' + o.statusText);"); println(out, " }"); println(out, ""); println(out, " var callback ="); println(out, " {"); println(out, " success:responseSuccess,"); println(out, " failure:responseFailure"); println(out, " };"); println(out, ""); println(out, " var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); println(out, " var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); //println(out, " var ontology_display_name = " + "\"" + ontology_display_name + "\";"); //println(out, " var ontology_version = " + "\"" + ontology_version + "\";"); println(out, " var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); println(out, " }"); println(out, ""); println(out, " function setRootDesc(rootNodeName, ontology_display_name) {"); println(out, " var newDesc = \"<span class='instruction_text'>Root set to <b>\" + rootNodeName + \"</b></span>\";"); println(out, " rootDescDiv.setBody(newDesc);"); println(out, " var footer = \"<a onClick='javascript:onClickViewEntireOntology();' href='#' class='link_text'>view full ontology}</a>\";"); println(out, " rootDescDiv.setFooter(footer);"); println(out, " rootDescDiv.show();"); println(out, " rootDescDiv.render();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function searchTree(ontology_node_id, ontology_display_name) {"); println(out, ""); println(out, " var root = tree.getRoot();"); //new ViewInHierarchyUtil().printTree(out, ontology_display_name, ontology_version, node_id); new ViewInHierarchyUtils().printTree(out, ontology_display_name, ontology_version, node_id); println(out, " showPartialHierarchy();"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, ""); println(out, " function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); println(out, " var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); println(out, " var newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); println(out, ""); println(out, " var expand = false;"); println(out, " var childNodes = nodeInfo.children_nodes;"); println(out, ""); println(out, " if (childNodes.length > 0) {"); println(out, " expand = true;"); println(out, " }"); println(out, " var newNode = new YAHOO.widget.TextNode(newNodeData, rootNode, expand);"); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.labelStyle = \"ygtvlabel_highlight\";"); println(out, " }"); println(out, ""); println(out, " if (nodeInfo.ontology_node_id == ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " if (nodeInfo.ontology_node_child_count > 0) {"); println(out, " newNode.isLeaf = false;"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " } else {"); println(out, " tree.draw();"); println(out, " }"); println(out, ""); println(out, " } else {"); println(out, " if (nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); println(out, " newNode.isLeaf = true;"); println(out, " } else if (childNodes.length == 0) {"); println(out, " newNode.setDynamicLoad(loadNodeData);"); println(out, " }"); println(out, " }"); println(out, " }"); println(out, ""); println(out, " tree.draw();"); println(out, " for (var i=0; i < childNodes.length; i++) {"); println(out, " var childnodeInfo = childNodes[i];"); println(out, " addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); println(out, " }"); println(out, " }"); println(out, " YAHOO.util.Event.addListener(window, \"load\", init);"); println(out, ""); println(out, " </script>"); println(out, "</head>"); println(out, "<body>"); println(out, " "); println(out, " <!-- Begin Skip Top Navigation -->"); println(out, " <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); println(out, " <!-- End Skip Top Navigation --> "); println(out, " <div id=\"popupContainer\">"); println(out, " <!-- nci popup banner -->"); println(out, " <div class=\"ncipopupbanner\">"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/nci-banner-1.gif\" width=\"440\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" /></a>"); println(out, " <a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\"><img src=\"/ncitbrowser/images/spacer.gif\" width=\"48\" height=\"39\" border=\"0\" alt=\"National Cancer Institute\" class=\"print-header\" /></a>"); println(out, " </div>"); println(out, " <!-- end nci popup banner -->"); println(out, " <div id=\"popupMainArea\">"); println(out, " <a name=\"evs-content\" id=\"evs-content\"></a>"); println(out, " <table class=\"evsLogoBg\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); println(out, " <tr>"); println(out, " <td valign=\"top\">"); println(out, " <a href=\"http://evs.nci.nih.gov/\" target=\"_blank\" alt=\"Enterprise Vocabulary Services\">"); println(out, " <img src=\"/ncitbrowser/images/evs-popup-logo.gif\" width=\"213\" height=\"26\" alt=\"EVS: Enterprise Vocabulary Services\" title=\"EVS: Enterprise Vocabulary Services\" border=\"0\" />"); println(out, " </a>"); println(out, " </td>"); println(out, " <td valign=\"top\"><div id=\"closeWindow\"><a href=\"javascript:window.close();\"><img src=\"/ncitbrowser/images/thesaurus_close_icon.gif\" width=\"10\" height=\"10\" border=\"0\" alt=\"Close Window\" />&nbsp;CLOSE WINDOW</a></div></td>"); println(out, " </tr>"); println(out, " </table>"); println(out, ""); println(out, ""); String release_date = DataUtils.getVersionReleaseDate(ontology_display_name, ontology_version); if (ontology_display_name.compareTo("NCI Thesaurus") == 0 || ontology_display_name.compareTo("NCI_Thesaurus") == 0) { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/thesaurus_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"NCI Thesaurus\" title=\"\" border=\"0\" />"); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust-2\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, ""); println(out, " </div>"); } else { println(out, " <div>"); println(out, " <img src=\"/ncitbrowser/images/other_popup_banner.gif\" width=\"612\" height=\"56\" alt=\"" + display_name + "\" title=\"\" border=\"0\" />"); println(out, " <div class=\"vocabularynamepopupshort\">" + display_name ); println(out, " "); println(out, " "); println(out, " <span class=\"texttitle-blue-rightjust\">" + ontology_version + " (Release date: " + release_date + ")</span>"); println(out, " "); println(out, " "); println(out, " </div>"); println(out, " </div>"); } println(out, ""); println(out, " <div id=\"popupContentArea\">"); println(out, " <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); println(out, " <tr class=\"textbody\">"); println(out, " <td class=\"pageTitle\" align=\"left\">"); println(out, " " + display_name + " Hierarchy"); println(out, " </td>"); println(out, " <td class=\"pageTitle\" align=\"right\">"); println(out, " <font size=\"1\" color=\"red\" align=\"right\">"); println(out, " <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); println(out, " </font>"); println(out, " </td>"); println(out, " </tr>"); println(out, " </table>"); if (! ServerMonitorThread.getInstance().isRunning()) { println(out, " <div class=\"textbodyredsmall\">" + ServerMonitorThread.getInstance().getMessage() + "</div>"); } else { println(out, " <!-- Tree content -->"); println(out, " <div id=\"rootDesc\">"); println(out, " <div id=\"bd\"></div>"); println(out, " <div id=\"ft\"></div>"); println(out, " </div>"); println(out, " <div id=\"treeStatus\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"emptyRoot\">"); println(out, " <div id=\"bd\"></div>"); println(out, " </div>"); println(out, " <div id=\"treecontainer\"></div>"); } println(out, ""); println(out, " <form id=\"pg_form\">"); println(out, " "); String ontology_node_id_value = HTTPUtils.cleanXSS(node_id); String ontology_display_name_value = HTTPUtils.cleanXSS(ontology_display_name); String ontology_version_value = HTTPUtils.cleanXSS(ontology_version); println(out, " <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"" + ontology_node_id_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"" + ontology_display_name_value + "\" />"); //println(out, " <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"" + scheme_value + "\" />"); println(out, " <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"" + ontology_version_value + "\" />"); println(out, ""); println(out, " </form>"); println(out, " <!-- End of Tree control content -->"); println(out, " </div>"); println(out, " </div>"); println(out, " </div>"); println(out, " "); println(out, "</body>"); println(out, "</html>"); if (_debug) { _logger.debug(Utils.SEPARATOR); _logger.debug("VIH HTML:\n" + _debugBuffer); _debugBuffer = null; _logger.debug(Utils.SEPARATOR); } } public static void create_src_vs_tree(HttpServletRequest request, HttpServletResponse response) { create_vs_tree(request, response, Constants.STANDARD_VIEW); } public static void create_cs_vs_tree(HttpServletRequest request, HttpServletResponse response) { create_vs_tree(request, response, Constants.TERMINOLOGY_VIEW); } public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); if (view == Constants.STANDARD_VIEW) { out.println(" <title>NCI Term Browser - Value Set Source View</title>"); } else { out.println(" <title>NCI Term Browser - Value Set Terminology View</title>"); } //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); //Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982 out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982) //GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); // out.println(" buildTree('', ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = null; if (view == Constants.STANDARD_VIEW) { value_set_tree_hmap = DataUtils.getSourceValueSetTree(); } else { value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); } TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); //new ValueSetUtils().printTree(out, root); new ValueSetUtils().printTree(out, root, view); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //[#31914] Search option and algorithm in value set search box are not preserved in session. String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); System.out.println("*** OPTION: " + option); System.out.println("*** ALGORITHM: " + algorithm); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); //Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982 out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); - out.println(" <a href=\"<%=basePath%>/start.jsf\" style=\"text-decoration: none;\">"); + out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); //out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); //KLO, 022612 out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); // Visited concepts -- to be implemented. // out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio &#40;NCI Thesaurus 11.09d&#41;</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); /* out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>"); out.println(" </td>"); out.println(" <td width=\"7\"></td>"); out.println(" </tr>"); out.println("</table>"); */ out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); } public static void search_value_set(HttpServletRequest request, HttpServletResponse response) { String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); request.getSession().setAttribute("valueset_search_algorithm", algorithm); // check if any checkbox is checked. String contextPath = request.getContextPath(); String view_str = (String) request.getParameter("view"); int view = Integer.parseInt(view_str); String msg = null; String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); if (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0) { msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); create_vs_tree(request, response, view); } else { String destination = contextPath + "/pages/value_set_search_results.jsf"; try { String retstr = valueSetSearchAction(request); System.out.println("(*) redirecting to: " + destination); response.sendRedirect(response.encodeRedirectURL(destination)); } catch (Exception ex) { System.out.println("response.sendRedirect failed???"); } } } public static String valueSetSearchAction(HttpServletRequest request) { java.lang.String valueSetDefinitionRevisionId = null; String msg = null; String selectValueSetSearchOption = (String) request.getParameter("selectValueSetSearchOption"); if (DataUtils.isNull(selectValueSetSearchOption)) { selectValueSetSearchOption = "Name"; } request.getSession().setAttribute("selectValueSetSearchOption", selectValueSetSearchOption); String algorithm = (String) request.getParameter("valueset_search_algorithm"); if (DataUtils.isNull(algorithm)) { algorithm = "exactMatch"; } request.getSession().setAttribute("valueset_search_algorithm", algorithm); String checked_vocabularies = (String) request.getParameter("checked_vocabularies"); System.out.println("checked_vocabularies: " + checked_vocabularies); if (checked_vocabularies != null && checked_vocabularies.compareTo("") == 0) { msg = "No value set definition is selected."; System.out.println(msg); request.getSession().setAttribute("message", msg); return "message"; } Vector selected_vocabularies = new Vector(); selected_vocabularies = DataUtils.parseData(checked_vocabularies, ","); System.out.println("selected_vocabularies count: " + selected_vocabularies.size()); String VSD_view = (String) request.getParameter("view"); request.getSession().setAttribute("view", VSD_view); String matchText = (String) request.getParameter("matchText"); Vector v = new Vector(); LexEVSValueSetDefinitionServices vsd_service = null; vsd_service = RemoteServerUtil.getLexEVSValueSetDefinitionServices(); if (matchText != null) matchText = matchText.trim(); if (selectValueSetSearchOption.compareTo("Code") == 0) { String uri = null; try { String versionTag = null;//"PRODUCTION"; if (checked_vocabularies != null) { for (int k=0; k<selected_vocabularies.size(); k++) { String vsd_name = (String) selected_vocabularies.elementAt(k); String vsd_uri = DataUtils.getValueSetDefinitionURIByName(vsd_name); System.out.println("vsd_name: " + vsd_name + " (vsd_uri: " + vsd_uri + ")"); try { //ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); if (vsd_uri != null) { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(vsd_uri), null); AbsoluteCodingSchemeVersionReference acsvr = vsd_service.isEntityInValueSet(matchText, new URI(vsd_uri), null, versionTag); if (acsvr != null) { String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } } else { System.out.println("WARNING: Unable to find vsd_uri for " + vsd_name); } } catch (Exception ex) { System.out.println("WARNING: vsd_service.getValueSetDefinition threw exception: " + vsd_name); } } } else { AbsoluteCodingSchemeVersionReferenceList csVersionList = null;//ValueSetHierarchy.getAbsoluteCodingSchemeVersionReferenceList(); List list = vsd_service.listValueSetsWithEntityCode(matchText, null, csVersionList, versionTag); if (list != null) { for (int j=0; j<list.size(); j++) { uri = (String) list.get(j); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (selected_vocabularies.contains(vsd_name)) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with URI " + uri + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { ex.printStackTrace(); System.out.println("vsd_service.listValueSetsWithEntityCode throws exceptions???"); } msg = "Unexpected errors encountered; search by code failed."; request.getSession().setAttribute("message", msg); return "message"; } else if (selectValueSetSearchOption.compareTo("Name") == 0) { String uri = null; try { Vector uri_vec = DataUtils.getValueSetURIs(); for (int i=0; i<uri_vec.size(); i++) { uri = (String) uri_vec.elementAt(i); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); if (checked_vocabularies == null || selected_vocabularies.contains(vsd_name)) { //System.out.println("Searching " + vsd_name + "..."); AbsoluteCodingSchemeVersionReferenceList csVersionList = null; /* Vector cs_ref_vec = DataUtils.getCodingSchemeReferencesInValueSetDefinition(uri, "PRODUCTION"); if (cs_ref_vec != null) { csVersionList = DataUtils.vector2CodingSchemeVersionReferenceList(cs_ref_vec); } */ ResolvedValueSetCodedNodeSet rvs_cns = null; SortOptionList sortOptions = null; LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; try { rvs_cns = vsd_service.getValueSetDefinitionEntitiesForTerm(matchText, algorithm, new URI(uri), csVersionList, null); if (rvs_cns != null) { CodedNodeSet cns = rvs_cns.getCodedNodeSet(); ResolvedConceptReferencesIterator itr = cns.resolve(sortOptions, propertyNames, propertyTypes); if (itr != null && itr.numberRemaining() > 0) { AbsoluteCodingSchemeVersionReferenceList ref_list = rvs_cns.getCodingSchemeVersionRefList(); if (ref_list.getAbsoluteCodingSchemeVersionReferenceCount() > 0) { try { ValueSetDefinition vsd = vsd_service.getValueSetDefinition(new URI(uri), null); if (vsd == null) { msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } String metadata = DataUtils.getValueSetDefinitionMetadata(vsd); if (metadata != null) { v.add(metadata); } } catch (Exception ex) { ex.printStackTrace(); msg = "Unable to find any value set with name " + matchText + "."; request.getSession().setAttribute("message", msg); return "message"; } } } } } catch (Exception ex) { //System.out.println("WARNING: getValueSetDefinitionEntitiesForTerm throws exception???"); msg = "getValueSetDefinitionEntitiesForTerm throws exception -- search by \"" + matchText + "\" failed. (VSD URI: " + uri + ")"; System.out.println(msg); request.getSession().setAttribute("message", msg); return "message"; } } } request.getSession().setAttribute("matched_vsds", v); if (v.size() == 0) { msg = "No match found."; request.getSession().setAttribute("message", msg); return "message"; } else if (v.size() == 1) { request.getSession().setAttribute("vsd_uri", uri); } return "value_set"; } catch (Exception ex) { //ex.printStackTrace(); System.out.println("vsd_service.getValueSetDefinitionEntitiesForTerm throws exceptions???"); } msg = "Unexpected errors encountered; search by name failed."; request.getSession().setAttribute("message", msg); return "message"; } return "value_set"; } }
true
true
public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); if (view == Constants.STANDARD_VIEW) { out.println(" <title>NCI Term Browser - Value Set Source View</title>"); } else { out.println(" <title>NCI Term Browser - Value Set Terminology View</title>"); } //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); //Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982 out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982) //GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); // out.println(" buildTree('', ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = null; if (view == Constants.STANDARD_VIEW) { value_set_tree_hmap = DataUtils.getSourceValueSetTree(); } else { value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); } TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); //new ValueSetUtils().printTree(out, root); new ValueSetUtils().printTree(out, root, view); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //[#31914] Search option and algorithm in value set search box are not preserved in session. String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); System.out.println("*** OPTION: " + option); System.out.println("*** ALGORITHM: " + algorithm); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); //Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982 out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); out.println(" <a href=\"<%=basePath%>/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); //out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); //KLO, 022612 out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); // Visited concepts -- to be implemented. // out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio &#40;NCI Thesaurus 11.09d&#41;</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); /* out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>"); out.println(" </td>"); out.println(" <td width=\"7\"></td>"); out.println(" </tr>"); out.println("</table>"); */ out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); }
public static void create_vs_tree(HttpServletRequest request, HttpServletResponse response, int view) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (Exception ex) { ex.printStackTrace(); return; } String message = (String) request.getSession().getAttribute("message"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html xmlns:c=\"http://java.sun.com/jsp/jstl/core\">"); out.println("<head>"); if (view == Constants.STANDARD_VIEW) { out.println(" <title>NCI Term Browser - Value Set Source View</title>"); } else { out.println(" <title>NCI Term Browser - Value Set Terminology View</title>"); } //out.println(" <title>NCI Thesaurus</title>"); out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); out.println(""); out.println("<style type=\"text/css\">"); out.println("/*margin and padding on body element"); out.println(" can introduce errors in determining"); out.println(" element position and are not recommended;"); out.println(" we turn them off as a foundation for YUI"); out.println(" CSS treatments. */"); out.println("body {"); out.println(" margin:0;"); out.println(" padding:0;"); out.println("}"); out.println("</style>"); out.println(""); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/fonts/fonts-min.css\" />"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.9.0/build/treeview/assets/skins/sam/treeview.css\" />"); out.println(""); out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js\"></script>"); //Before(GF31982): out.println("<script type=\"text/javascript\" src=\"http://yui.yahooapis.com/2.9.0/build/treeview/treeview-min.js\"></script>"); out.println("<script type=\"text/javascript\" src=\"/ncitbrowser/js/yui/treeview-min.js\" ></script>"); //GF31982 out.println(""); out.println(""); out.println("<!-- Dependency -->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js\"></script>"); out.println(""); out.println("<!-- Source file -->"); out.println("<!--"); out.println(" If you require only basic HTTP transaction support, use the"); out.println(" connection_core.js file."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js\"></script>"); out.println(""); out.println("<!--"); out.println(" Use the full connection.js if you require the following features:"); out.println(" - Form serialization."); out.println(" - File Upload using the iframe transport."); out.println(" - Cross-domain(XDR) transactions."); out.println("-->"); out.println("<script src=\"http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println("<!--begin custom header content for this example-->"); out.println("<!--Additional custom style rules for this example:-->"); out.println("<style type=\"text/css\">"); out.println(""); out.println(""); out.println(".ygtvcheck0 { background: url(/ncitbrowser/images/yui/treeview/check0.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck1 { background: url(/ncitbrowser/images/yui/treeview/check1.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(".ygtvcheck2 { background: url(/ncitbrowser/images/yui/treeview/check2.gif) 0 0 no-repeat; width:16px; height:20px; float:left; cursor:pointer; }"); out.println(""); out.println(""); out.println(".ygtv-edit-TaskNode { width: 190px;}"); out.println(".ygtv-edit-TaskNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border:none;}"); out.println(".ygtv-edit-TaskNode .ygtv-button-container { float: right;}"); out.println(".ygtv-edit-TaskNode .ygtv-input input{ width: 140px;}"); out.println(".whitebg {"); out.println(" background-color:white;"); out.println("}"); out.println("</style>"); out.println(""); out.println(" <link rel=\"stylesheet\" type=\"text/css\" href=\"/ncitbrowser/css/styleSheet.css\" />"); out.println(" <link rel=\"shortcut icon\" href=\"/ncitbrowser/favicon.ico\" type=\"image/x-icon\" />"); out.println(""); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/script.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tasknode.js\"></script>"); out.println(""); out.println(" <script type=\"text/javascript\">"); out.println(""); out.println(" function refresh() {"); out.println(""); out.println(" var selectValueSetSearchOptionObj = document.forms[\"valueSetSearchForm\"].selectValueSetSearchOption;"); out.println(""); out.println(" for (var i=0; i<selectValueSetSearchOptionObj.length; i++) {"); out.println(" if (selectValueSetSearchOptionObj[i].checked) {"); out.println(" selectValueSetSearchOption = selectValueSetSearchOptionObj[i].value;"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(" window.location.href=\"/ncitbrowser/pages/value_set_source_view.jsf?refresh=1\""); //Before(GF31982) //GF31982(Not Sure): out.println(" window.location.href=\"/ncitbrowser/ajax?action=create_src_vs_tree?refresh=1\""); out.println(" + \"&nav_type=valuesets\" + \"&opt=\"+ selectValueSetSearchOption;"); out.println(""); out.println(" }"); out.println(" </script>"); out.println(""); out.println(" <script language=\"JavaScript\">"); out.println(""); out.println(" var tree;"); out.println(" var nodeIndex;"); out.println(" var nodes = [];"); out.println(""); out.println(" function load(url,target) {"); out.println(" if (target != '')"); out.println(" target.window.location.href = url;"); out.println(" else"); out.println(" window.location.href = url;"); out.println(" }"); out.println(""); out.println(" function init() {"); out.println(" //initTree();"); out.println(" }"); out.println(""); out.println(" //handler for expanding all nodes"); out.println(" YAHOO.util.Event.on(\"expand_all\", \"click\", function(e) {"); out.println(" //expandEntireTree();"); out.println(""); out.println(" tree.expandAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for collapsing all nodes"); out.println(" YAHOO.util.Event.on(\"collapse_all\", \"click\", function(e) {"); out.println(" tree.collapseAll();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for checking all nodes"); out.println(" YAHOO.util.Event.on(\"check_all\", \"click\", function(e) {"); out.println(" check_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(" //handler for unchecking all nodes"); out.println(" YAHOO.util.Event.on(\"uncheck_all\", \"click\", function(e) {"); out.println(" uncheck_all();"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" YAHOO.util.Event.on(\"getchecked\", \"click\", function(e) {"); out.println(" //alert(\"Checked nodes: \" + YAHOO.lang.dump(getCheckedNodes()), \"info\", \"example\");"); out.println(" //YAHOO.util.Event.preventDefault(e);"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(" function addTreeNode(rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" if (nodeInfo.ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, false);"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function buildTree(ontology_node_id, ontology_display_name) {"); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" var expand = false;"); out.println(" //addTreeNode(root, nodeInfo, expand);"); out.println(""); out.println(" addTreeNode(root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=build_src_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function resetTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleResetTreeSuccess = function(o) {"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(" if ( typeof(respObj.root_node) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.root_node.ontology_node_id + \"');\";"); out.println(" var rootNodeData = { label:respObj.root_node.ontology_node_name, id:respObj.root_node.ontology_node_id, href:nodeDetails };"); out.println(" var expand = false;"); out.println(" if (respObj.root_node.ontology_node_child_count > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var ontRoot = new YAHOO.widget.TaskNode(rootNodeData, root, expand);"); out.println(""); out.println(" if ( typeof(respObj.child_nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.child_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.child_nodes[i];"); out.println(" addTreeNode(ontRoot, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleResetTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var resetTreeCallback ="); out.println(" {"); out.println(" success:handleResetTreeSuccess,"); out.println(" failure:handleResetTreeFailure"); out.println(" };"); out.println(" if (ontology_node_id!= '') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=reset_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name + '&version='+ ontology_version +'&ontology_source='+ontology_source,resetTreeCallback);"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function onClickTreeNode(ontology_node_id) {"); out.println(" //alert(\"onClickTreeNode \" + ontology_node_id);"); out.println(" window.location = '/ncitbrowser/pages/value_set_treenode_redirect.jsf?ontology_node_id=' + ontology_node_id;"); out.println(" }"); out.println(""); out.println(""); out.println(" function onClickViewEntireOntology(ontology_display_name) {"); out.println(" var ontology_display_name = document.pg_form.ontology_display_name.value;"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.draw();"); // out.println(" buildTree('', ontology_display_name);"); out.println(" }"); out.println(""); out.println(" function initTree() {"); out.println(""); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" tree.setNodesProperty('propagateHighlightUp',true);"); out.println(" tree.setNodesProperty('propagateHighlightDown',true);"); out.println(" tree.subscribe('keydown',tree._onKeyDownEvent);"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"expand\", function(node) {"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 39 });"); out.println(""); out.println(" });"); out.println(""); out.println(""); out.println(""); out.println(" tree.subscribe(\"collapse\", function(node) {"); out.println(" //alert(\"Collapsing \" + node.label );"); out.println(""); out.println(" YAHOO.util.UserAction.keydown(document.body, { keyCode: 109 });"); out.println(" });"); out.println(""); out.println(" // By default, trees with TextNodes will fire an event for when the label is clicked:"); out.println(" tree.subscribe(\"checkClick\", function(node) {"); out.println(" //alert(node.data.myNodeId + \" label was checked\");"); out.println(" });"); out.println(""); out.println(""); println(out, " var root = tree.getRoot();"); HashMap value_set_tree_hmap = null; if (view == Constants.STANDARD_VIEW) { value_set_tree_hmap = DataUtils.getSourceValueSetTree(); } else { value_set_tree_hmap = DataUtils.getCodingSchemeValueSetTree(); } TreeItem root = (TreeItem) value_set_tree_hmap.get("<Root>"); //new ValueSetUtils().printTree(out, root); new ValueSetUtils().printTree(out, root, view); String contextPath = request.getContextPath(); String view_str = new Integer(view).toString(); //[#31914] Search option and algorithm in value set search box are not preserved in session. String option = (String) request.getSession().getAttribute("selectValueSetSearchOption"); String algorithm = (String) request.getSession().getAttribute("valueset_search_algorithm"); System.out.println("*** OPTION: " + option); System.out.println("*** ALGORITHM: " + algorithm); String option_code = ""; String option_name = ""; if (DataUtils.isNull(option)) { option_code = "checked"; } else { if (option.compareToIgnoreCase("Code") == 0) { option_code = "checked"; } if (option.compareToIgnoreCase("Name") == 0) { option_name = "checked"; } } String algorithm_exactMatch = ""; String algorithm_startsWith = ""; String algorithm_contains = ""; if (DataUtils.isNull(algorithm)) { algorithm_exactMatch = "checked"; } else { if (algorithm.compareToIgnoreCase("exactMatch") == 0) { algorithm_exactMatch = "checked"; } if (algorithm.compareToIgnoreCase("startsWith") == 0) { algorithm_startsWith = "checked"; } if (algorithm.compareToIgnoreCase("contains") == 0) { algorithm_contains = "checked"; } } out.println(""); if (message == null) { out.println(" tree.collapseAll();"); } out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(""); out.println(" function onCheckClick(node) {"); out.println(" YAHOO.log(node.label + \" check was clicked, new state: \" + node.checkState, \"info\", \"example\");"); out.println(" }"); out.println(""); out.println(" function check_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].check();"); out.println(" }"); out.println(" }"); out.println(""); out.println(" function uncheck_all() {"); out.println(" var topNodes = tree.getRoot().children;"); out.println(" for(var i=0; i<topNodes.length; ++i) {"); out.println(" topNodes[i].uncheck();"); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expand_all() {"); out.println(" //alert(\"expand_all\");"); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" onClickViewEntireOntology(ontology_display_name);"); out.println(" }"); out.println(""); out.println(""); // 0=unchecked, 1=some children checked, 2=all children checked out.println(" // Gets the labels of all of the fully checked nodes"); out.println(" // Could be updated to only return checked leaf nodes by evaluating"); out.println(" // the children collection first."); out.println(" function getCheckedNodes(nodes) {"); out.println(" nodes = nodes || tree.getRoot().children;"); out.println(" checkedNodes = [];"); out.println(" for(var i=0, l=nodes.length; i<l; i=i+1) {"); out.println(" var n = nodes[i];"); out.println(" if (n.checkState > 0) { // if we were interested in the nodes that have some but not all children checked"); out.println(" //if (n.checkState == 2) {"); out.println(" checkedNodes.push(n.label); // just using label for simplicity"); out.println(""); out.println(" if (n.hasChildren()) {"); out.println(" checkedNodes = checkedNodes.concat(getCheckedNodes(n.children));"); out.println(" }"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(" var checked_vocabularies = document.forms[\"valueSetSearchForm\"].checked_vocabularies;"); out.println(" checked_vocabularies.value = checkedNodes;"); out.println(""); out.println(" return checkedNodes;"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function loadNodeData(node, fnLoadComplete) {"); out.println(" var id = node.data.id;"); out.println(""); out.println(" var responseSuccess = function(o)"); out.println(" {"); out.println(" var path;"); out.println(" var dirs;"); out.println(" var files;"); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" var fileNum = 0;"); out.println(" var categoryNum = 0;"); out.println(" if ( typeof(respObj.nodes) != \"undefined\") {"); out.println(" for (var i=0; i < respObj.nodes.length; i++) {"); out.println(" var name = respObj.nodes[i].ontology_node_name;"); out.println(" var nodeDetails = \"javascript:onClickTreeNode('\" + respObj.nodes[i].ontology_node_id + \"');\";"); out.println(" var newNodeData = { label:name, id:respObj.nodes[i].ontology_node_id, href:nodeDetails };"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, node, false);"); out.println(" if (respObj.nodes[i].ontology_node_child_count > 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" tree.draw();"); out.println(" fnLoadComplete();"); out.println(" }"); out.println(""); out.println(" var responseFailure = function(o){"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var callback ="); out.println(" {"); out.println(" success:responseSuccess,"); out.println(" failure:responseFailure"); out.println(" };"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var cObj = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_src_vs_tree&ontology_node_id=' +id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version,callback);"); out.println(" }"); out.println(""); out.println(""); out.println(" function searchTree(ontology_node_id, ontology_display_name) {"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.dummy_root_nodes) != \"undefined\") {"); out.println(" showNodeNotFound(ontology_node_id);"); out.println(" }"); out.println(""); out.println(" else if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" }"); out.println(" else {"); out.println(" showPartialHierarchy();"); out.println(" showConstructingTreeStatus();"); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //var expand = false;"); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;//document.pg_form.ontology_source.value;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=search_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(" function expandEntireTree() {"); out.println(" tree = new YAHOO.widget.TreeView(\"treecontainer\");"); out.println(" //tree.draw();"); out.println(""); out.println(" var ontology_display_name = document.forms[\"pg_form\"].ontology_display_name.value;"); out.println(" var ontology_node_id = document.forms[\"pg_form\"].ontology_node_id.value;"); out.println(""); out.println(" var handleBuildTreeSuccess = function(o) {"); out.println(""); out.println(" var respTxt = o.responseText;"); out.println(" var respObj = eval('(' + respTxt + ')');"); out.println(" if ( typeof(respObj) != \"undefined\") {"); out.println(""); out.println(" if ( typeof(respObj.root_nodes) != \"undefined\") {"); out.println(""); out.println(" //alert(respObj.root_nodes.length);"); out.println(""); out.println(" var root = tree.getRoot();"); out.println(" if (respObj.root_nodes.length == 0) {"); out.println(" //showEmptyRoot();"); out.println(" } else {"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" for (var i=0; i < respObj.root_nodes.length; i++) {"); out.println(" var nodeInfo = respObj.root_nodes[i];"); out.println(" //alert(\"calling addTreeBranch \");"); out.println(""); out.println(" addTreeBranch(ontology_node_id, root, nodeInfo);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" var handleBuildTreeFailure = function(o) {"); out.println(" alert('responseFailure: ' + o.statusText);"); out.println(" }"); out.println(""); out.println(" var buildTreeCallback ="); out.println(" {"); out.println(" success:handleBuildTreeSuccess,"); out.println(" failure:handleBuildTreeFailure"); out.println(" };"); out.println(""); out.println(" if (ontology_display_name!='') {"); out.println(" var ontology_source = null;"); out.println(" var ontology_version = document.forms[\"pg_form\"].ontology_version.value;"); out.println(" var request = YAHOO.util.Connect.asyncRequest('GET','/ncitbrowser/ajax?action=expand_entire_vs_tree&ontology_node_id=' +ontology_node_id+'&ontology_display_name='+ontology_display_name+'&version='+ontology_version+'&ontology_source='+ontology_source,buildTreeCallback);"); out.println(""); out.println(" }"); out.println(" }"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" function addTreeBranch(ontology_node_id, rootNode, nodeInfo) {"); out.println(" var newNodeDetails = \"javascript:onClickTreeNode('\" + nodeInfo.ontology_node_id + \"');\";"); out.println(""); out.println(" var newNodeData;"); out.println(" if (ontology_node_id.indexOf(\"TVS_\") >= 0) {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id };"); out.println(" } else {"); out.println(" newNodeData = { label:nodeInfo.ontology_node_name, id:nodeInfo.ontology_node_id, href:newNodeDetails };"); out.println(" }"); out.println(""); out.println(" var expand = false;"); out.println(" var childNodes = nodeInfo.children_nodes;"); out.println(""); out.println(" if (childNodes.length > 0) {"); out.println(" expand = true;"); out.println(" }"); out.println(" var newNode = new YAHOO.widget.TaskNode(newNodeData, rootNode, expand);"); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.labelStyle = \"ygtvlabel_highlight\";"); out.println(" }"); out.println(""); out.println(" if (nodeInfo.ontology_node_id == ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" if (nodeInfo.ontology_node_child_count > 0) {"); out.println(" newNode.isLeaf = false;"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" } else {"); out.println(" tree.draw();"); out.println(" }"); out.println(""); out.println(" } else {"); out.println(" if (nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" if (nodeInfo.ontology_node_child_count == 0 && nodeInfo.ontology_node_id != ontology_node_id) {"); out.println(" newNode.isLeaf = true;"); out.println(" } else if (childNodes.length == 0) {"); out.println(" newNode.setDynamicLoad(loadNodeData);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(""); out.println(" tree.draw();"); out.println(" for (var i=0; i < childNodes.length; i++) {"); out.println(" var childnodeInfo = childNodes[i];"); out.println(" addTreeBranch(ontology_node_id, newNode, childnodeInfo);"); out.println(" }"); out.println(" }"); out.println(" YAHOO.util.Event.addListener(window, \"load\", init);"); out.println(""); out.println(" YAHOO.util.Event.onDOMReady(initTree);"); out.println(""); out.println(""); out.println(" </script>"); out.println(""); out.println("</head>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println("<body onLoad=\"document.forms.valueSetSearchForm.matchText.focus();\">"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/wz_tooltip.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_centerwindow.js\"></script>"); out.println(" <script type=\"text/javascript\" src=\"/ncitbrowser/js/tip_followscroll.js\"></script>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <!-- Begin Skip Top Navigation -->"); out.println(" <a href=\"#evs-content\" class=\"hideLink\" accesskey=\"1\" title=\"Skip repetitive navigation links\">skip navigation links</A>"); out.println(" <!-- End Skip Top Navigation -->"); out.println(""); out.println("<!-- nci banner -->"); out.println("<div class=\"ncibanner\">"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/logotype.gif\""); out.println(" width=\"440\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/spacer.gif\""); out.println(" width=\"48\" height=\"39\" border=\"0\""); out.println(" alt=\"National Cancer Institute\" class=\"print-header\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.nih.gov\" target=\"_blank\" >"); out.println(" <img src=\"/ncitbrowser/images/tagline_nologo.gif\""); out.println(" width=\"173\" height=\"39\" border=\"0\""); out.println(" alt=\"U.S. National Institutes of Health\"/>"); out.println(" </a>"); out.println(" <a href=\"http://www.cancer.gov\" target=\"_blank\">"); out.println(" <img src=\"/ncitbrowser/images/cancer-gov.gif\""); out.println(" width=\"99\" height=\"39\" border=\"0\""); out.println(" alt=\"www.cancer.gov\"/>"); out.println(" </a>"); out.println("</div>"); out.println("<!-- end nci banner -->"); out.println(""); out.println(" <div class=\"center-page\">"); out.println(" <!-- EVS Logo -->"); out.println("<div>"); out.println(" <img src=\"/ncitbrowser/images/evs-logo-swapped.gif\" alt=\"EVS Logo\""); out.println(" width=\"745\" height=\"26\" border=\"0\""); out.println(" usemap=\"#external-evs\" />"); out.println(" <map id=\"external-evs\" name=\"external-evs\">"); out.println(" <area shape=\"rect\" coords=\"0,0,140,26\""); out.println(" href=\"/ncitbrowser/start.jsf\" target=\"_self\""); out.println(" alt=\"NCI Term Browser\" />"); out.println(" <area shape=\"rect\" coords=\"520,0,745,26\""); out.println(" href=\"http://evs.nci.nih.gov/\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\" />"); out.println(" </map>"); out.println("</div>"); out.println(""); out.println(""); out.println("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"); out.println(" <tr>"); out.println(" <td width=\"5\"></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/multiple_search.jsf?nav_type=terminologies\">"); out.println(" <img name=\"tab_terms\" src=\"/ncitbrowser/images/tab_terms.gif\""); out.println(" border=\"0\" alt=\"Terminologies\" title=\"Terminologies\" /></a></td>"); //Before(GF31982): out.println(" <td><a href=\"/ncitbrowser/pages/value_set_source_view.jsf?nav_type=valuesets\">"); out.println(" <td><a href=\"/ncitbrowser/ajax?action=create_src_vs_tree\">"); //GF31982 out.println(" <img name=\"tab_valuesets\" src=\"/ncitbrowser/images/tab_valuesets_clicked.gif\""); out.println(" border=\"0\" alt=\"Value Sets\" title=\"ValueSets\" /></a></td>"); out.println(" <td><a href=\"/ncitbrowser/pages/mapping_search.jsf?nav_type=mappings\">"); out.println(" <img name=\"tab_map\" src=\"/ncitbrowser/images/tab_map.gif\""); out.println(" border=\"0\" alt=\"Mappings\" title=\"Mappings\" /></a></td>"); out.println(" </tr>"); out.println("</table>"); out.println(""); out.println("<div class=\"mainbox-top\"><img src=\"/ncitbrowser/images/mainbox-top.gif\" width=\"745\" height=\"5\" alt=\"\"/></div>"); out.println("<!-- end EVS Logo -->"); out.println(" <!-- Main box -->"); out.println(" <div id=\"main-area\">"); out.println(""); out.println(" <!-- Thesaurus, banner search area -->"); out.println(" <div class=\"bannerarea\">"); out.println(" <a href=\"/ncitbrowser/start.jsf\" style=\"text-decoration: none;\">"); out.println(" <div class=\"vocabularynamebanner_tb\">"); out.println(" <span class=\"vocabularynamelong_tb\">" + JSPUtils.getApplicationVersionDisplay() + "</span>"); out.println(" </div>"); out.println(" </a>"); out.println(" <div class=\"search-globalnav\">"); out.println(" <!-- Search box -->"); out.println(" <div class=\"searchbox-top\"><img src=\"/ncitbrowser/images/searchbox-top.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Top\" /></div>"); out.println(" <div class=\"searchbox\">"); out.println(""); out.println(""); //out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + + "/ajax?action=saerch_value_set_tree\"> "/pages/value_set_source_view.jsf\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<form id=\"valueSetSearchForm\" name=\"valueSetSearchForm\" method=\"post\" action=\"" + contextPath + "/ajax?action=search_value_set\" class=\"search-form-main-area\" enctype=\"application/x-www-form-urlencoded\">"); out.println("<input type=\"hidden\" name=\"valueSetSearchForm\" value=\"valueSetSearchForm\" />"); out.println("<input type=\"hidden\" name=\"view\" value=\"" + view_str + "\" />"); out.println(""); out.println(""); out.println(""); out.println(" <input type=\"hidden\" id=\"checked_vocabularies\" name=\"checked_vocabularies\" value=\"\" />"); out.println(""); out.println(""); out.println(""); out.println("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 2px\" >"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(""); out.println(" <input CLASS=\"searchbox-input-2\""); out.println(" name=\"matchText\""); out.println(" value=\"\""); out.println(" onFocus=\"active = true\""); out.println(" onBlur=\"active = false\""); out.println(" onkeypress=\"return submitEnter('valueSetSearchForm:valueset_search',event)\""); out.println(" tabindex=\"1\"/>"); out.println(""); out.println(""); out.println(" <input id=\"valueSetSearchForm:valueset_search\" type=\"image\" src=\"/ncitbrowser/images/search.gif\" name=\"valueSetSearchForm:valueset_search\" alt=\"Search\" onclick=\"javascript:getCheckedNodes();\" tabindex=\"2\" class=\"searchbox-btn\" /><a href=\"/ncitbrowser/pages/help.jsf#searchhelp\" tabindex=\"3\"><img src=\"/ncitbrowser/images/search-help.gif\" alt=\"Search Help\" style=\"border-width:0;\" class=\"searchbox-btn\" /></a>"); out.println(""); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td>"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin: 0px\">"); out.println(""); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"exactMatch\" alt=\"Exact Match\" " + algorithm_exactMatch + " tabindex=\"3\">Exact Match&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"startsWith\" alt=\"Begins With\" " + algorithm_startsWith + " tabindex=\"3\">Begins With&nbsp;"); out.println(" <input type=\"radio\" name=\"valueset_search_algorithm\" value=\"contains\" alt=\"Contains\" " + algorithm_contains + " tabindex=\"3\">Contains"); out.println(" </td>"); out.println(" </tr>"); out.println(""); out.println(" <tr align=\"left\">"); out.println(" <td height=\"1px\" bgcolor=\"#2F2F5F\" align=\"left\"></td>"); out.println(" </tr>"); out.println(" <tr valign=\"top\" align=\"left\">"); out.println(" <td align=\"left\" class=\"textbody\">"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Code\" " + option_code + " alt=\"Code\" tabindex=\"1\" >Code&nbsp;"); out.println(" <input type=\"radio\" id=\"selectValueSetSearchOption\" name=\"selectValueSetSearchOption\" value=\"Name\" " + option_name + " alt=\"Name\" tabindex=\"1\" >Name"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </td>"); out.println(" </tr>"); out.println("</table>"); out.println(" <input type=\"hidden\" name=\"referer\" id=\"referer\" value=\"http%3A%2F%2Flocalhost%3A8080%2Fncitbrowser%2Fpages%2Fresolved_value_set_search_results.jsf\">"); out.println(" <input type=\"hidden\" id=\"nav_type\" name=\"nav_type\" value=\"valuesets\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(""); out.println("<input type=\"hidden\" name=\"javax.faces.ViewState\" id=\"javax.faces.ViewState\" value=\"j_id22:j_id23\" />"); out.println("</form>"); out.println(" </div> <!-- searchbox -->"); out.println(""); out.println(" <div class=\"searchbox-bottom\"><img src=\"/ncitbrowser/images/searchbox-bottom.gif\" width=\"352\" height=\"2\" alt=\"SearchBox Bottom\" /></div>"); out.println(" <!-- end Search box -->"); out.println(" <!-- Global Navigation -->"); out.println(""); out.println("<table class=\"global-nav\" border=\"0\" width=\"100%\" height=\"37px\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <tr>"); out.println(" <td align=\"left\" valign=\"bottom\">"); out.println(" <a href=\"#\" onclick=\"javascript:window.open('/ncitbrowser/pages/source_help_info-termbrowser.jsf',"); out.println(" '_blank','top=100, left=100, height=740, width=780, status=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no');\" tabindex=\"13\">"); out.println(" Sources</a>"); out.println(""); //KLO, 022612 out.println(" \r\n"); out.println(" "); out.print( VisitedConceptUtils.getDisplayLink(request, true) ); out.println(" \r\n"); // Visited concepts -- to be implemented. // out.println(" | <A href=\"#\" onmouseover=\"Tip('<ul><li><a href=\'/ncitbrowser/ConceptReport.jsp?dictionary=NCI Thesaurus&version=11.09d&code=C44256\'>Ratio &#40;NCI Thesaurus 11.09d&#41;</a><br></li></ul>',WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\" onmouseout=UnTip() >Visited Concepts</A>"); out.println(" </td>"); out.println(" <td align=\"right\" valign=\"bottom\">"); out.println(" <a href=\""); out.print( request.getContextPath() ); out.println("/pages/help.jsf\" tabindex=\"16\">Help</a>\r\n"); out.println(" </td>\r\n"); out.println(" <td width=\"7\"></td>\r\n"); out.println(" </tr>\r\n"); out.println("</table>"); /* out.println(" <a href=\"/ncitbrowser/pages/help.jsf\" tabindex=\"16\">Help</a>"); out.println(" </td>"); out.println(" <td width=\"7\"></td>"); out.println(" </tr>"); out.println("</table>"); */ out.println(" <!-- end Global Navigation -->"); out.println(""); out.println(" </div> <!-- search-globalnav -->"); out.println(" </div> <!-- bannerarea -->"); out.println(""); out.println(" <!-- end Thesaurus, banner search area -->"); out.println(" <!-- Quick links bar -->"); out.println(""); out.println("<div class=\"bluebar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td><div class=\"quicklink-status\">&nbsp;</div></td>"); out.println(" <td>"); out.println(""); out.println(" <div id=\"quicklinksholder\">"); out.println(" <ul id=\"quicklinks\""); out.println(" onmouseover=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-active.gif';\""); out.println(" onmouseout=\"document.quicklinksimg.src='/ncitbrowser/images/quicklinks-inactive.gif';\">"); out.println(" <li>"); out.println(" <a href=\"#\" tabindex=\"-1\"><img src=\"/ncitbrowser/images/quicklinks-inactive.gif\" width=\"162\""); out.println(" height=\"18\" border=\"0\" name=\"quicklinksimg\" alt=\"Quick Links\" />"); out.println(" </a>"); out.println(" <ul>"); out.println(" <li><a href=\"http://evs.nci.nih.gov/\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"Enterprise Vocabulary Services\">EVS Home</a></li>"); out.println(" <li><a href=\"http://localhost/ncimbrowserncimbrowser\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Metathesaurus\">NCI Metathesaurus Browser</a></li>"); out.println(""); out.println(" <li><a href=\"/ncitbrowser/start.jsf\" tabindex=\"-1\""); out.println(" alt=\"NCI Term Browser\">NCI Term Browser</a></li>"); out.println(" <li><a href=\"http://www.cancer.gov/cancertopics/terminologyresources\" tabindex=\"-1\" target=\"_blank\""); out.println(" alt=\"NCI Terminology Resources\">NCI Terminology Resources</a></li>"); out.println(""); out.println(" <li><a href=\"http://ncitermform.nci.nih.gov/ncitermform/?dictionary=NCI%20Thesaurus\" tabindex=\"-1\" target=\"_blank\" alt=\"Term Suggestion\">Term Suggestion</a></li>"); out.println(""); out.println(""); out.println(" </ul>"); out.println(" </li>"); out.println(" </ul>"); out.println(" </div>"); out.println(""); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println("</div>"); if (! ServerMonitorThread.getInstance().isRunning()) { out.println(" <div class=\"redbar\">"); out.println(" <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); out.println(" <tr>"); out.println(" <td class=\"lexevs-status\">"); out.println(" " + ServerMonitorThread.getInstance().getMessage()); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(" </div>"); } out.println(" <!-- end Quick links bar -->"); out.println(""); out.println(" <!-- Page content -->"); out.println(" <div class=\"pagecontent\">"); out.println(""); if (message != null) { out.println("\r\n"); out.println(" <p class=\"textbodyred\">"); out.print(message); out.println("</p>\r\n"); out.println(" "); request.getSession().removeAttribute("message"); } out.println("<p class=\"textbody\">"); out.println("View value sets organized by standards category or source terminology."); out.println("Standards categories group the value sets supporting them; all other labels lead to the home pages of actual value sets or source terminologies."); out.println("Search or browse a value set from its home page, or search all value sets at once from this page (very slow) to find which ones contain a particular code or term."); out.println("</p>"); out.println(""); out.println(" <div id=\"popupContentArea\">"); out.println(" <a name=\"evs-content\" id=\"evs-content\"></a>"); out.println(""); out.println(" <table width=\"580px\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\">"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(" <tr class=\"textbody\">"); out.println(" <td class=\"textbody\" align=\"left\">"); out.println(""); if (view == Constants.STANDARD_VIEW) { out.println(" Standards View"); out.println(" &nbsp;|"); out.println(" <a href=\"" + contextPath + "/ajax?action=create_cs_vs_tree\">Terminology View</a>"); } else { out.println(" <a href=\"" + contextPath + "/ajax?action=create_src_vs_tree\">Standards View</a>"); out.println(" &nbsp;|"); out.println(" Terminology View"); } out.println(" </td>"); out.println(""); out.println(" <td align=\"right\">"); out.println(" <font size=\"1\" color=\"red\" align=\"right\">"); out.println(" <a href=\"javascript:printPage()\"><img src=\"/ncitbrowser/images/printer.bmp\" border=\"0\" alt=\"Send to Printer\"><i>Send to Printer</i></a>"); out.println(" </font>"); out.println(" </td>"); out.println(" </tr>"); out.println(" </table>"); out.println(""); out.println(" <hr/>"); out.println(""); out.println(""); out.println(""); out.println("<style>"); out.println("#expandcontractdiv {border:1px solid #336600; background-color:#FFFFCC; margin:0 0 .5em 0; padding:0.2em;}"); out.println("#treecontainer { background: #fff }"); out.println("</style>"); out.println(""); out.println(""); out.println("<div id=\"expandcontractdiv\">"); out.println(" <a id=\"expand_all\" href=\"#\">Expand all</a>"); out.println(" <a id=\"collapse_all\" href=\"#\">Collapse all</a>"); out.println(" <a id=\"check_all\" href=\"#\">Check all</a>"); out.println(" <a id=\"uncheck_all\" href=\"#\">Uncheck all</a>"); out.println("</div>"); out.println(""); out.println(""); out.println(""); out.println(" <!-- Tree content -->"); out.println(""); out.println(" <div id=\"treecontainer\" class=\"ygtv-checkbox\"></div>"); out.println(""); out.println(" <form id=\"pg_form\">"); out.println(""); out.println(" <input type=\"hidden\" id=\"ontology_node_id\" name=\"ontology_node_id\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_display_name\" name=\"ontology_display_name\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"schema\" name=\"schema\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"ontology_version\" name=\"ontology_version\" value=\"null\" />"); out.println(" <input type=\"hidden\" id=\"view\" name=\"view\" value=\"source\" />"); out.println(" </form>"); out.println(""); out.println(""); out.println(" </div> <!-- popupContentArea -->"); out.println(""); out.println(""); out.println("<div class=\"textbody\">"); out.println("<!-- footer -->"); out.println("<div class=\"footer\" style=\"width:720px\">"); out.println(" <ul>"); out.println(" <li><a href=\"http://www.cancer.gov\" target=\"_blank\" alt=\"National Cancer Institute\">NCI Home</a> |</li>"); out.println(" <li><a href=\"/ncitbrowser/pages/contact_us.jsf\">Contact Us</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies\" target=\"_blank\" alt=\"National Cancer Institute Policies\">Policies</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page3\" target=\"_blank\" alt=\"National Cancer Institute Accessibility\">Accessibility</a> |</li>"); out.println(" <li><a href=\"http://www.cancer.gov/policies/page6\" target=\"_blank\" alt=\"National Cancer Institute FOIA\">FOIA</a></li>"); out.println(" </ul>"); out.println(" <p>"); out.println(" A Service of the National Cancer Institute<br />"); out.println(" <img src=\"/ncitbrowser/images/external-footer-logos.gif\""); out.println(" alt=\"External Footer Logos\" width=\"238\" height=\"34\" border=\"0\""); out.println(" usemap=\"#external-footer\" />"); out.println(" </p>"); out.println(" <map id=\"external-footer\" name=\"external-footer\">"); out.println(" <area shape=\"rect\" coords=\"0,0,46,34\""); out.println(" href=\"http://www.cancer.gov\" target=\"_blank\""); out.println(" alt=\"National Cancer Institute\" />"); out.println(" <area shape=\"rect\" coords=\"55,1,99,32\""); out.println(" href=\"http://www.hhs.gov/\" target=\"_blank\""); out.println(" alt=\"U.S. Health &amp; Human Services\" />"); out.println(" <area shape=\"rect\" coords=\"103,1,147,31\""); out.println(" href=\"http://www.nih.gov/\" target=\"_blank\""); out.println(" alt=\"National Institutes of Health\" />"); out.println(" <area shape=\"rect\" coords=\"148,1,235,33\""); out.println(" href=\"http://www.usa.gov/\" target=\"_blank\""); out.println(" alt=\"USA.gov\" />"); out.println(" </map>"); out.println("</div>"); out.println("<!-- end footer -->"); out.println("</div>"); out.println(""); out.println(""); out.println(" </div> <!-- pagecontent -->"); out.println(" </div> <!-- main-area -->"); out.println(" <div class=\"mainbox-bottom\"><img src=\"/ncitbrowser/images/mainbox-bottom.gif\" width=\"745\" height=\"5\" alt=\"Mainbox Bottom\" /></div>"); out.println(""); out.println(" </div> <!-- center-page -->"); out.println(""); out.println("</body>"); out.println("</html>"); out.println(""); }
diff --git a/src/com/gbayer/basicblackjack/Hand.java b/src/com/gbayer/basicblackjack/Hand.java index 4f5fe3d..cbdf6cf 100644 --- a/src/com/gbayer/basicblackjack/Hand.java +++ b/src/com/gbayer/basicblackjack/Hand.java @@ -1,153 +1,153 @@ /** * Project: BasicBlackJack * Package: com.gbayer.basicblackjack * File: Hand.java * Author: Greg Bayer <greg@gbayer.com> * Date: Jul 19, 2010 */ package com.gbayer.basicblackjack; import java.util.ArrayList; import org.apache.log4j.Logger; /** * A <code>Hand</code> contains <code>Cards</code> currently held by a * <code>Player</code> */ public class Hand { /** The Log4J logger. */ private static Logger log = Logger.getLogger(Hand.class); /** Constant - Highest value a hand can have before busting. */ public static final int MAX_HAND_VALUE = 21; /** Constant - Difference between low and high value of an ace. */ public static final int ACE_UPGRADE_VALUE = Card.HIGH_ACE_VALUE - Card.LOW_ACE_VALUE; /** * The Enum Result. */ public enum Result { PlayerWins, DealerWins, Push } /** The cards in the hand. */ private ArrayList<Card> cards; /** * Instantiates a new hand. */ public Hand() { cards = new ArrayList<Card>(); } /** * Adds a card to the hand. * * @param card * the card */ public void addCard(Card card) { cards.add(card); } /** * Clear all cards in hand. Hand will be empty. Underlying data structure is * reused. */ public void clear() { cards.clear(); } /** * Calculates total hand value. Counts ace as 11 when possible without * causing hand to bust. * * @return the total hand value */ public int getTotalHandValue() { log.debug("Calculating hand value..."); int totalWithAcesLow = 0; int numberOfAces = 0; // Sum up value of all cards. Aces are 1 by default. Allow one ace to be // 11 if it will not cause bust. for (Card card : cards) { int cardValue = card.getCardValue(true); totalWithAcesLow += cardValue; if (cardValue == Card.LOW_ACE_VALUE) { numberOfAces++; } } log.debug("Hand value with all aces low: " + totalWithAcesLow); int total = totalWithAcesLow; // Upgrade ace if can do so without causing player to bust if (numberOfAces > 0 - && (totalWithAcesLow + ACE_UPGRADE_VALUE) < MAX_HAND_VALUE) + && (totalWithAcesLow + ACE_UPGRADE_VALUE) <= MAX_HAND_VALUE) { total += ACE_UPGRADE_VALUE; log.debug("Updrading one ace"); } log.info("Hand value: " + total); return total; } /** * Generates string representing all cards in the hand. */ public String toString() { StringBuilder sb = new StringBuilder(); for (Card card : cards) { sb.append(card + " "); } String hand = sb.toString(); log.debug("Printing hand: " + hand); return hand; } /** * Generates string showing top card in hand openly and all others as X * (face down). * * @return the string */ public String toStringShowingTopCardOnly() { StringBuilder sb = new StringBuilder(); boolean firstCard = true; for (Card card : cards) { if (firstCard) { sb.append(card + " "); // First card is face-up firstCard = false; } else { sb.append("X "); // Face-down card } } String hand = sb.toString(); log.debug("Printing hand showing top card only: " + hand); return hand; } }
true
true
public int getTotalHandValue() { log.debug("Calculating hand value..."); int totalWithAcesLow = 0; int numberOfAces = 0; // Sum up value of all cards. Aces are 1 by default. Allow one ace to be // 11 if it will not cause bust. for (Card card : cards) { int cardValue = card.getCardValue(true); totalWithAcesLow += cardValue; if (cardValue == Card.LOW_ACE_VALUE) { numberOfAces++; } } log.debug("Hand value with all aces low: " + totalWithAcesLow); int total = totalWithAcesLow; // Upgrade ace if can do so without causing player to bust if (numberOfAces > 0 && (totalWithAcesLow + ACE_UPGRADE_VALUE) < MAX_HAND_VALUE) { total += ACE_UPGRADE_VALUE; log.debug("Updrading one ace"); } log.info("Hand value: " + total); return total; }
public int getTotalHandValue() { log.debug("Calculating hand value..."); int totalWithAcesLow = 0; int numberOfAces = 0; // Sum up value of all cards. Aces are 1 by default. Allow one ace to be // 11 if it will not cause bust. for (Card card : cards) { int cardValue = card.getCardValue(true); totalWithAcesLow += cardValue; if (cardValue == Card.LOW_ACE_VALUE) { numberOfAces++; } } log.debug("Hand value with all aces low: " + totalWithAcesLow); int total = totalWithAcesLow; // Upgrade ace if can do so without causing player to bust if (numberOfAces > 0 && (totalWithAcesLow + ACE_UPGRADE_VALUE) <= MAX_HAND_VALUE) { total += ACE_UPGRADE_VALUE; log.debug("Updrading one ace"); } log.info("Hand value: " + total); return total; }
diff --git a/src/main/java/edu/ntnu/adaboost/ensemblelearning/Adaboost.java b/src/main/java/edu/ntnu/adaboost/ensemblelearning/Adaboost.java index 931ec4a..a384169 100644 --- a/src/main/java/edu/ntnu/adaboost/ensemblelearning/Adaboost.java +++ b/src/main/java/edu/ntnu/adaboost/ensemblelearning/Adaboost.java @@ -1,135 +1,135 @@ package edu.ntnu.adaboost.ensemblelearning; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import edu.ntnu.adaboost.classifier.Classifier; import edu.ntnu.adaboost.classifier.ClassifierStatistics; import edu.ntnu.adaboost.model.Instance; import edu.ntnu.adaboost.utils.FractionalMultiSet; import java.util.HashMap; import java.util.List; import java.util.Map; public class Adaboost { private final Map<Classifier, ClassifierStatistics> weightedClassifiers = new HashMap<Classifier, ClassifierStatistics>(); public Adaboost(List<Classifier> classifiers) { for (Classifier classifier : classifiers) { weightedClassifiers.put(classifier, new ClassifierStatistics()); } } public void train(List<Instance> trainingSet) { initializeUniformWeights(trainingSet); int numberOfDifferentLabels = getNumberOfDifferentLabels(trainingSet); for (Map.Entry<Classifier, ClassifierStatistics> entry : weightedClassifiers.entrySet()) { Classifier classifier = entry.getKey(); ClassifierStatistics classifierStatistics = entry.getValue(); boolean isValid = false; while (!isValid) { classifier.train(trainingSet); isValid = updateWeights(classifier, classifierStatistics, trainingSet, numberOfDifferentLabels); } } } public int predict(List<Double> features) { FractionalMultiSet<Integer> classVoting = new FractionalMultiSet<Integer>(); for (Map.Entry<Classifier, ClassifierStatistics> entry : weightedClassifiers.entrySet()) { Classifier classifier = entry.getKey(); double weight = entry.getValue().getWeight(); int predictedClass = classifier.predict(features); classVoting.add(predictedClass, weight); } int predictedClass = -1; double bestVote = 0; for (Map.Entry<Integer, Double> entry : classVoting.entrySet()) { int clazz = entry.getKey(); Double vote = entry.getValue(); if (vote > bestVote) { bestVote = vote; predictedClass = clazz; } } return predictedClass; } public Map<Classifier, ClassifierStatistics> getWeightedClassifiers() { return weightedClassifiers; } private boolean updateWeights(Classifier classifier, ClassifierStatistics classifierStatistics, List<Instance> trainingSet, int numberOfDifferentLabels) { double error = 0; int errorCount = 0; for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { error += trainingInstance.getWeight(); errorCount++; } } // We must update the weight before tossing bad classifier to avoid infinite loop for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { trainingInstance.setWeight(trainingInstance.getWeight() * ((1 - error) / error) * (numberOfDifferentLabels - 1)); } } - if (error > (numberOfDifferentLabels - 1) / numberOfDifferentLabels) { + if (error >= (numberOfDifferentLabels - 1) / (double) numberOfDifferentLabels) { // Bad classifier, so toss it out return false; } normalizeWeights(trainingSet); double classifierWeight = Math.log((1 - error) / error); double trainingError = (double) errorCount / trainingSet.size(); classifierStatistics.setWeight(classifierWeight); classifierStatistics.setTrainingError(trainingError); return true; } private void initializeUniformWeights(List<Instance> trainingSet) { double weight = 1.0d / trainingSet.size(); for (Instance trainingInstance : trainingSet) { trainingInstance.setWeight(weight); } } private void normalizeWeights(List<Instance> trainingSet) { double totalWeight = 0; for (Instance trainingInstance : trainingSet) { totalWeight += trainingInstance.getWeight(); } for (Instance trainingInstance : trainingSet) { trainingInstance.setWeight(trainingInstance.getWeight() / totalWeight); } } private int getNumberOfDifferentLabels(List<Instance> trainingSet) { Multiset<Integer> classMultiset = HashMultiset.create(); for(Instance trainingInstance : trainingSet){ classMultiset.add(trainingInstance.getClazz()); } return classMultiset.elementSet().size(); } }
true
true
private boolean updateWeights(Classifier classifier, ClassifierStatistics classifierStatistics, List<Instance> trainingSet, int numberOfDifferentLabels) { double error = 0; int errorCount = 0; for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { error += trainingInstance.getWeight(); errorCount++; } } // We must update the weight before tossing bad classifier to avoid infinite loop for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { trainingInstance.setWeight(trainingInstance.getWeight() * ((1 - error) / error) * (numberOfDifferentLabels - 1)); } } if (error > (numberOfDifferentLabels - 1) / numberOfDifferentLabels) { // Bad classifier, so toss it out return false; } normalizeWeights(trainingSet); double classifierWeight = Math.log((1 - error) / error); double trainingError = (double) errorCount / trainingSet.size(); classifierStatistics.setWeight(classifierWeight); classifierStatistics.setTrainingError(trainingError); return true; }
private boolean updateWeights(Classifier classifier, ClassifierStatistics classifierStatistics, List<Instance> trainingSet, int numberOfDifferentLabels) { double error = 0; int errorCount = 0; for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { error += trainingInstance.getWeight(); errorCount++; } } // We must update the weight before tossing bad classifier to avoid infinite loop for (Instance trainingInstance : trainingSet) { int predictLabel = classifier.predict(trainingInstance.getFeatures()); if (predictLabel != trainingInstance.getClazz()) { trainingInstance.setWeight(trainingInstance.getWeight() * ((1 - error) / error) * (numberOfDifferentLabels - 1)); } } if (error >= (numberOfDifferentLabels - 1) / (double) numberOfDifferentLabels) { // Bad classifier, so toss it out return false; } normalizeWeights(trainingSet); double classifierWeight = Math.log((1 - error) / error); double trainingError = (double) errorCount / trainingSet.size(); classifierStatistics.setWeight(classifierWeight); classifierStatistics.setTrainingError(trainingError); return true; }
diff --git a/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java b/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java index acac911..4bf2ee8 100644 --- a/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java +++ b/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java @@ -1,347 +1,347 @@ /* * * Copyright 2001-2006 The Ant-Contrib 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 net.sf.antcontrib.cpptasks.types; import java.io.File; import net.sf.antcontrib.cpptasks.CUtil; import net.sf.antcontrib.cpptasks.FileVisitor; import net.sf.antcontrib.cpptasks.compiler.Linker; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.DataType; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.PatternSet; /** * A set of library names. Libraries can also be added to a link by specifying * them in a fileset. * * For most Unix-like compilers, libset will result in a series of -l and -L * linker arguments. For Windows compilers, the library names will be used to * locate the appropriate library files which will be added to the linkers * input file list as if they had been specified in a fileset. * * @author Mark A Russell <a * href="mailto:mark_russell@csgsystems.com">mark_russell@csg_systems.com * </a> * @author Adam Murdoch * @author Curt Arnold */ public class LibrarySet extends DataType { private String dataset; private boolean explicitCaseSensitive; private String ifCond; private String[] libnames; private final FileSet set = new FileSet(); private String unlessCond; private LibraryTypeEnum libraryType; public LibrarySet() { libnames = new String[0]; } public void execute() throws org.apache.tools.ant.BuildException { throw new org.apache.tools.ant.BuildException( "Not an actual task, but looks like one for documentation purposes"); } /** * Gets the dataset. Used on OS390 if the libs are in a dataset. * * @return Returns a String */ public String getDataset() { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.getDataset(); } return dataset; } public File getDir(final Project project) { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.getDir(project); } return set.getDir(project); } protected FileSet getFileSet() { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.getFileSet(); } return set; } public String[] getLibs() { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.getLibs(); } String[] retval = (String[]) libnames.clone(); return retval; } /** * Gets preferred library type * * @return library type, may be null. */ public LibraryTypeEnum getType() { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.getType(); } return libraryType; } /** * Returns true if the define's if and unless conditions (if any) are * satisfied. */ public boolean isActive(final org.apache.tools.ant.Project p) { if (p == null) { throw new NullPointerException("p"); } if (ifCond != null) { String ifValue = p.getProperty(ifCond); if (ifValue != null) { if (ifValue.equals("no") || ifValue.equals("false")) { throw new BuildException( "property " + ifCond + " used as if condition has value " + ifValue + " which suggests a misunderstanding of if attributes"); } } else { return false; } } if (unlessCond != null) { String unlessValue = p.getProperty(unlessCond); if (unlessValue != null) { if (unlessValue.equals("no") || unlessValue.equals("false")) { throw new BuildException( "property " + unlessCond + " used as unless condition has value " + unlessValue + " which suggests a misunderstanding of unless attributes"); } return false; } } if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); return master.isActive(project); } if (libnames.length == 0) { p.log("libnames not specified or empty.", Project.MSG_WARN); return false; } return true; } /** * Sets case sensitivity of the file system. If not set, will default to * the linker's case sensitivity. * * @param isCaseSensitive * "true"|"on"|"yes" if file system is case sensitive, * "false"|"off"|"no" when not. */ public void setCaseSensitive(final boolean isCaseSensitive) { if (isReference()) { throw tooManyAttributes(); } explicitCaseSensitive = true; set.setCaseSensitive(isCaseSensitive); } /** * Sets the dataset. Used on OS390 if the libs are in a dataset. * * @param dataset * The dataset to set */ public void setDataset(final String dataset) { if (isReference()) { throw tooManyAttributes(); } this.dataset = dataset; } /** * Library directory. * * @param dir * library directory * */ public void setDir(final File dir) throws BuildException { if (isReference()) { throw tooManyAttributes(); } set.setDir(dir); } /** * Sets the property name for the 'if' condition. * * The library set will be ignored unless the property is defined. * * The value of the property is insignificant, but values that would imply * misinterpretation ("false", "no") will throw an exception when * evaluated. * * @param propName * property name */ public void setIf(String propName) { ifCond = propName; } /** * Comma-separated list of library names without leading prefixes, such as * "lib", or extensions, such as ".so" or ".a". * */ public void setLibs(final CUtil.StringArrayBuilder libs) throws BuildException { if (isReference()) { throw tooManyAttributes(); } libnames = libs.getValue(); // // earlier implementations would warn of suspicious library names // (like libpthread for pthread or kernel.lib for kernel). // visitLibraries now provides better feedback and ld type linkers // should provide adequate feedback so the check here is not necessary. } public void setProject(final Project project) { set.setProject(project); super.setProject(project); } /** * Set the property name for the 'unless' condition. * * If named property is set, the library set will be ignored. * * The value of the property is insignificant, but values that would imply * misinterpretation ("false", "no") of the behavior will throw an * exception when evaluated. * * @param propName * name of property */ public void setUnless(String propName) { unlessCond = propName; } /** * Sets the preferred library type. Supported values "shared", "static", and * "framework". "framework" is equivalent to "shared" on non-Darwin platforms. */ public void setType(final LibraryTypeEnum type) { if (isReference()) { throw tooManyAttributes(); } this.libraryType = type; } public void visitLibraries(final Project project, final Linker linker, final File[] libpath, final FileVisitor visitor) throws BuildException { if (isReference()) { - LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); + LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); master.visitLibraries(project, linker, libpath, visitor); } // // if there was a libs attribute then // add the corresponding patterns to the FileSet // if (libnames != null) { for (int i = 0; i < libnames.length; i++) { String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType); if (patterns.length > 0) { FileSet localSet = (FileSet) set.clone(); // // unless explicitly set // will default to the linker case sensitivity // if (!explicitCaseSensitive) { boolean linkerCaseSensitive = linker.isCaseSensitive(); localSet.setCaseSensitive(linkerCaseSensitive); } // // add all the patterns for this libname // for (int j = 0; j < patterns.length; j++) { PatternSet.NameEntry entry = localSet.createInclude(); entry.setName(patterns[j]); } int matches = 0; // // if there was no specified directory then // run through the libpath backwards // if (localSet.getDir(project) == null) { // // scan libpath in reverse order // to give earlier entries priority // for (int j = libpath.length - 1; j >= 0; j--) { FileSet clone = (FileSet) localSet.clone(); clone.setDir(libpath[j]); DirectoryScanner scanner = clone.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } } else { DirectoryScanner scanner = localSet.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } // // TODO: following section works well for Windows // style linkers but unnecessary fails // Unix style linkers. Will need to revisit. // - if (matches == 0 && false) { + if (matches == 0) { StringBuffer msg = new StringBuffer("No file matching "); if (patterns.length == 1) { msg.append("pattern ("); msg.append(patterns[0]); msg.append(")"); } else { msg.append("patterns (\""); msg.append(patterns[0]); for (int k = 1; k < patterns.length; k++) { msg.append(", "); msg.append(patterns[k]); } msg.append(")"); } msg.append(" for library name \""); msg.append(libnames[i]); msg.append("\" was found."); throw new BuildException(msg.toString()); } } } } } }
false
true
public void visitLibraries(final Project project, final Linker linker, final File[] libpath, final FileVisitor visitor) throws BuildException { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); master.visitLibraries(project, linker, libpath, visitor); } // // if there was a libs attribute then // add the corresponding patterns to the FileSet // if (libnames != null) { for (int i = 0; i < libnames.length; i++) { String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType); if (patterns.length > 0) { FileSet localSet = (FileSet) set.clone(); // // unless explicitly set // will default to the linker case sensitivity // if (!explicitCaseSensitive) { boolean linkerCaseSensitive = linker.isCaseSensitive(); localSet.setCaseSensitive(linkerCaseSensitive); } // // add all the patterns for this libname // for (int j = 0; j < patterns.length; j++) { PatternSet.NameEntry entry = localSet.createInclude(); entry.setName(patterns[j]); } int matches = 0; // // if there was no specified directory then // run through the libpath backwards // if (localSet.getDir(project) == null) { // // scan libpath in reverse order // to give earlier entries priority // for (int j = libpath.length - 1; j >= 0; j--) { FileSet clone = (FileSet) localSet.clone(); clone.setDir(libpath[j]); DirectoryScanner scanner = clone.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } } else { DirectoryScanner scanner = localSet.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } // // TODO: following section works well for Windows // style linkers but unnecessary fails // Unix style linkers. Will need to revisit. // if (matches == 0 && false) { StringBuffer msg = new StringBuffer("No file matching "); if (patterns.length == 1) { msg.append("pattern ("); msg.append(patterns[0]); msg.append(")"); } else { msg.append("patterns (\""); msg.append(patterns[0]); for (int k = 1; k < patterns.length; k++) { msg.append(", "); msg.append(patterns[k]); } msg.append(")"); } msg.append(" for library name \""); msg.append(libnames[i]); msg.append("\" was found."); throw new BuildException(msg.toString()); } } } } }
public void visitLibraries(final Project project, final Linker linker, final File[] libpath, final FileVisitor visitor) throws BuildException { if (isReference()) { LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet")); master.visitLibraries(project, linker, libpath, visitor); } // // if there was a libs attribute then // add the corresponding patterns to the FileSet // if (libnames != null) { for (int i = 0; i < libnames.length; i++) { String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType); if (patterns.length > 0) { FileSet localSet = (FileSet) set.clone(); // // unless explicitly set // will default to the linker case sensitivity // if (!explicitCaseSensitive) { boolean linkerCaseSensitive = linker.isCaseSensitive(); localSet.setCaseSensitive(linkerCaseSensitive); } // // add all the patterns for this libname // for (int j = 0; j < patterns.length; j++) { PatternSet.NameEntry entry = localSet.createInclude(); entry.setName(patterns[j]); } int matches = 0; // // if there was no specified directory then // run through the libpath backwards // if (localSet.getDir(project) == null) { // // scan libpath in reverse order // to give earlier entries priority // for (int j = libpath.length - 1; j >= 0; j--) { FileSet clone = (FileSet) localSet.clone(); clone.setDir(libpath[j]); DirectoryScanner scanner = clone.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } } else { DirectoryScanner scanner = localSet.getDirectoryScanner(project); File basedir = scanner.getBasedir(); String[] files = scanner.getIncludedFiles(); matches += files.length; for (int k = 0; k < files.length; k++) { visitor.visit(basedir, files[k]); } } // // TODO: following section works well for Windows // style linkers but unnecessary fails // Unix style linkers. Will need to revisit. // if (matches == 0) { StringBuffer msg = new StringBuffer("No file matching "); if (patterns.length == 1) { msg.append("pattern ("); msg.append(patterns[0]); msg.append(")"); } else { msg.append("patterns (\""); msg.append(patterns[0]); for (int k = 1; k < patterns.length; k++) { msg.append(", "); msg.append(patterns[k]); } msg.append(")"); } msg.append(" for library name \""); msg.append(libnames[i]); msg.append("\" was found."); throw new BuildException(msg.toString()); } } } } }
diff --git a/core/java/src/net/i2p/client/RequestLeaseSetMessageHandler.java b/core/java/src/net/i2p/client/RequestLeaseSetMessageHandler.java index 7a8bd200e..e662f6572 100644 --- a/core/java/src/net/i2p/client/RequestLeaseSetMessageHandler.java +++ b/core/java/src/net/i2p/client/RequestLeaseSetMessageHandler.java @@ -1,153 +1,153 @@ package net.i2p.client; /* * free (adj.): unencumbered; not under the control of others * Written by jrandom in 2003 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. * */ import java.util.HashMap; import java.util.Map; import net.i2p.I2PAppContext; import net.i2p.crypto.KeyGenerator; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.data.Lease; import net.i2p.data.LeaseSet; import net.i2p.data.PrivateKey; import net.i2p.data.PublicKey; import net.i2p.data.SessionKey; import net.i2p.data.SigningPrivateKey; import net.i2p.data.SigningPublicKey; import net.i2p.data.i2cp.I2CPMessage; import net.i2p.data.i2cp.RequestLeaseSetMessage; import net.i2p.util.Log; /** * Handle I2CP RequestLeaseSetMessage from the router by granting all leases * * @author jrandom */ class RequestLeaseSetMessageHandler extends HandlerImpl { private Map _existingLeaseSets; public RequestLeaseSetMessageHandler(I2PAppContext context) { super(context, RequestLeaseSetMessage.MESSAGE_TYPE); _existingLeaseSets = new HashMap(32); } public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message; LeaseSet leaseSet = new LeaseSet(); for (int i = 0; i < msg.getEndpoints(); i++) { Lease lease = new Lease(); lease.setGateway(msg.getRouter(i)); lease.setTunnelId(msg.getTunnelId(i)); lease.setEndDate(msg.getEndDate()); //lease.setStartDate(msg.getStartDate()); leaseSet.addLease(lease); } // also, if this session is connected to multiple routers, include other leases here leaseSet.setDestination(session.getMyDestination()); // reuse the old keys for the client LeaseInfo li = null; synchronized (_existingLeaseSets) { if (_existingLeaseSets.containsKey(session.getMyDestination())) li = (LeaseInfo) _existingLeaseSets.get(session.getMyDestination()); } if (li == null) { li = new LeaseInfo(session.getMyDestination()); synchronized (_existingLeaseSets) { _existingLeaseSets.put(session.getMyDestination(), li); } if (_log.shouldLog(Log.DEBUG)) _log.debug("Creating new leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Caching the old leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } leaseSet.setEncryptionKey(li.getPublicKey()); leaseSet.setSigningKey(li.getSigningPublicKey()); - boolean encrypt = Boolean.valueOf(session.getOptions().getProperty("i2cp.encryptLeaseset")).booleanValue(); + boolean encrypt = Boolean.valueOf(session.getOptions().getProperty("i2cp.encryptLeaseSet")).booleanValue(); String sk = session.getOptions().getProperty("i2cp.leaseSetKey"); if (encrypt && sk != null) { SessionKey key = new SessionKey(); try { key.fromBase64(sk); leaseSet.encrypt(key); _context.keyRing().put(session.getMyDestination().calculateHash(), key); } catch (DataFormatException dfe) { _log.error("Bad leaseset key: " + sk); } } try { leaseSet.sign(session.getPrivateKey()); session.getProducer().createLeaseSet(session, leaseSet, li.getSigningPrivateKey(), li.getPrivateKey()); session.setLeaseSet(leaseSet); } catch (DataFormatException dfe) { session.propogateError("Error signing the leaseSet", dfe); } catch (I2PSessionException ise) { session.propogateError("Error sending the signed leaseSet", ise); } } private static class LeaseInfo { private PublicKey _pubKey; private PrivateKey _privKey; private SigningPublicKey _signingPubKey; private SigningPrivateKey _signingPrivKey; private Destination _dest; public LeaseInfo(Destination dest) { _dest = dest; Object encKeys[] = KeyGenerator.getInstance().generatePKIKeypair(); Object signKeys[] = KeyGenerator.getInstance().generateSigningKeypair(); _pubKey = (PublicKey) encKeys[0]; _privKey = (PrivateKey) encKeys[1]; _signingPubKey = (SigningPublicKey) signKeys[0]; _signingPrivKey = (SigningPrivateKey) signKeys[1]; } public PublicKey getPublicKey() { return _pubKey; } public PrivateKey getPrivateKey() { return _privKey; } public SigningPublicKey getSigningPublicKey() { return _signingPubKey; } public SigningPrivateKey getSigningPrivateKey() { return _signingPrivKey; } @Override public int hashCode() { return DataHelper.hashCode(_pubKey) + 7 * DataHelper.hashCode(_privKey) + 7 * 7 * DataHelper.hashCode(_signingPubKey) + 7 * 7 * 7 * DataHelper.hashCode(_signingPrivKey); } @Override public boolean equals(Object obj) { if ((obj == null) || !(obj instanceof LeaseInfo)) return false; LeaseInfo li = (LeaseInfo) obj; return DataHelper.eq(_pubKey, li.getPublicKey()) && DataHelper.eq(_privKey, li.getPrivateKey()) && DataHelper.eq(_signingPubKey, li.getSigningPublicKey()) && DataHelper.eq(_signingPrivKey, li.getSigningPrivateKey()); } } }
true
true
public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message; LeaseSet leaseSet = new LeaseSet(); for (int i = 0; i < msg.getEndpoints(); i++) { Lease lease = new Lease(); lease.setGateway(msg.getRouter(i)); lease.setTunnelId(msg.getTunnelId(i)); lease.setEndDate(msg.getEndDate()); //lease.setStartDate(msg.getStartDate()); leaseSet.addLease(lease); } // also, if this session is connected to multiple routers, include other leases here leaseSet.setDestination(session.getMyDestination()); // reuse the old keys for the client LeaseInfo li = null; synchronized (_existingLeaseSets) { if (_existingLeaseSets.containsKey(session.getMyDestination())) li = (LeaseInfo) _existingLeaseSets.get(session.getMyDestination()); } if (li == null) { li = new LeaseInfo(session.getMyDestination()); synchronized (_existingLeaseSets) { _existingLeaseSets.put(session.getMyDestination(), li); } if (_log.shouldLog(Log.DEBUG)) _log.debug("Creating new leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Caching the old leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } leaseSet.setEncryptionKey(li.getPublicKey()); leaseSet.setSigningKey(li.getSigningPublicKey()); boolean encrypt = Boolean.valueOf(session.getOptions().getProperty("i2cp.encryptLeaseset")).booleanValue(); String sk = session.getOptions().getProperty("i2cp.leaseSetKey"); if (encrypt && sk != null) { SessionKey key = new SessionKey(); try { key.fromBase64(sk); leaseSet.encrypt(key); _context.keyRing().put(session.getMyDestination().calculateHash(), key); } catch (DataFormatException dfe) { _log.error("Bad leaseset key: " + sk); } } try { leaseSet.sign(session.getPrivateKey()); session.getProducer().createLeaseSet(session, leaseSet, li.getSigningPrivateKey(), li.getPrivateKey()); session.setLeaseSet(leaseSet); } catch (DataFormatException dfe) { session.propogateError("Error signing the leaseSet", dfe); } catch (I2PSessionException ise) { session.propogateError("Error sending the signed leaseSet", ise); } }
public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); RequestLeaseSetMessage msg = (RequestLeaseSetMessage) message; LeaseSet leaseSet = new LeaseSet(); for (int i = 0; i < msg.getEndpoints(); i++) { Lease lease = new Lease(); lease.setGateway(msg.getRouter(i)); lease.setTunnelId(msg.getTunnelId(i)); lease.setEndDate(msg.getEndDate()); //lease.setStartDate(msg.getStartDate()); leaseSet.addLease(lease); } // also, if this session is connected to multiple routers, include other leases here leaseSet.setDestination(session.getMyDestination()); // reuse the old keys for the client LeaseInfo li = null; synchronized (_existingLeaseSets) { if (_existingLeaseSets.containsKey(session.getMyDestination())) li = (LeaseInfo) _existingLeaseSets.get(session.getMyDestination()); } if (li == null) { li = new LeaseInfo(session.getMyDestination()); synchronized (_existingLeaseSets) { _existingLeaseSets.put(session.getMyDestination(), li); } if (_log.shouldLog(Log.DEBUG)) _log.debug("Creating new leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } else { if (_log.shouldLog(Log.DEBUG)) _log.debug("Caching the old leaseInfo keys for " + session.getMyDestination().calculateHash().toBase64()); } leaseSet.setEncryptionKey(li.getPublicKey()); leaseSet.setSigningKey(li.getSigningPublicKey()); boolean encrypt = Boolean.valueOf(session.getOptions().getProperty("i2cp.encryptLeaseSet")).booleanValue(); String sk = session.getOptions().getProperty("i2cp.leaseSetKey"); if (encrypt && sk != null) { SessionKey key = new SessionKey(); try { key.fromBase64(sk); leaseSet.encrypt(key); _context.keyRing().put(session.getMyDestination().calculateHash(), key); } catch (DataFormatException dfe) { _log.error("Bad leaseset key: " + sk); } } try { leaseSet.sign(session.getPrivateKey()); session.getProducer().createLeaseSet(session, leaseSet, li.getSigningPrivateKey(), li.getPrivateKey()); session.setLeaseSet(leaseSet); } catch (DataFormatException dfe) { session.propogateError("Error signing the leaseSet", dfe); } catch (I2PSessionException ise) { session.propogateError("Error sending the signed leaseSet", ise); } }
diff --git a/src/com/axelby/podax/SubscriptionProvider.java b/src/com/axelby/podax/SubscriptionProvider.java index bf34a0f..a463537 100644 --- a/src/com/axelby/podax/SubscriptionProvider.java +++ b/src/com/axelby/podax/SubscriptionProvider.java @@ -1,169 +1,169 @@ package com.axelby.podax; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class SubscriptionProvider extends ContentProvider { public static String AUTHORITY = "com.axelby.podax.subscriptionprovider"; public static Uri URI = Uri.parse("content://" + AUTHORITY + "/subscriptions"); public static final String ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.axelby.subscription"; public static final String DIR_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.axelby.subscription"; public static final String PODCAST_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.axelby.podcast"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_URL = "url"; public static final String COLUMN_LAST_MODIFIED = "lastModified"; public static final String COLUMN_LAST_UPDATE = "lastUpdate"; public static final String COLUMN_ETAG = "eTag"; public static final String COLUMN_THUMBNAIL = "thumbnail"; static final int SUBSCRIPTIONS = 1; static final int SUBSCRIPTION_ID = 2; static final int PODCASTS = 3; static UriMatcher _uriMatcher; static HashMap<String, String> _columnMap; static { _uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); _uriMatcher.addURI(AUTHORITY, "subscriptions", SUBSCRIPTIONS); _uriMatcher.addURI(AUTHORITY, "subscriptions/#", SUBSCRIPTION_ID); _uriMatcher.addURI(AUTHORITY, "subscriptions/#/podcasts", PODCASTS); _columnMap = new HashMap<String, String>(); _columnMap.put(COLUMN_ID, "_id"); _columnMap.put(COLUMN_TITLE, "title"); _columnMap.put(COLUMN_URL, "url"); _columnMap.put(COLUMN_LAST_MODIFIED, "lastModified"); _columnMap.put(COLUMN_LAST_UPDATE, "id"); _columnMap.put(COLUMN_ETAG, "eTag"); _columnMap.put(COLUMN_THUMBNAIL, "thumbnail"); } DBAdapter _dbAdapter; @Override public boolean onCreate() { _dbAdapter = new DBAdapter(getContext()); return true; } @Override public String getType(Uri uri) { switch (_uriMatcher.match(uri)) { case SUBSCRIPTIONS: return DIR_TYPE; case SUBSCRIPTION_ID: return ITEM_TYPE; case PODCASTS: return PODCAST_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI"); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int uriMatch = _uriMatcher.match(uri); if (uriMatch == PODCASTS) { return getContext().getContentResolver().query(PodcastProvider.URI, projection, "subscriptionId = ?", new String[] { uri.getPathSegments().get(1) }, - PodcastProvider.COLUMN_PUB_DATE); + PodcastProvider.COLUMN_PUB_DATE + " DESC"); } SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setProjectionMap(_columnMap); sqlBuilder.setTables("subscriptions"); switch (uriMatch) { case SUBSCRIPTIONS: if (sortOrder == null) sortOrder = "title IS NULL, title"; break; case SUBSCRIPTION_ID: sqlBuilder.appendWhere("_id = " + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unknown URI"); } Cursor c = sqlBuilder.query(_dbAdapter.getRawDB(), projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { switch (_uriMatcher.match(uri)) { case SUBSCRIPTION_ID: String extraWhere = COLUMN_ID + " = " + uri.getLastPathSegment(); if (where != null) where = extraWhere + " AND " + where; else where = extraWhere; break; default: throw new IllegalArgumentException("Unknown URI"); } int count = 0; count += _dbAdapter.getRawDB().update("subscriptions", values, where, whereArgs); getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(URI, null); return count; } @Override public Uri insert(Uri uri, ContentValues values) { if (values.size() == 0) return null; switch (_uriMatcher.match(uri)) { case SUBSCRIPTIONS: break; default: throw new IllegalArgumentException("Unknown URI"); } long id = _dbAdapter.getRawDB().insert("subscriptions", null, values); getContext().getContentResolver().notifyChange(URI, null); return ContentUris.withAppendedId(URI, id); } @Override public int delete(Uri uri, String where, String[] whereArgs) { switch (_uriMatcher.match(uri)) { case SUBSCRIPTIONS: break; case SUBSCRIPTION_ID: String extraWhere = COLUMN_ID + " = " + uri.getLastPathSegment(); if (where != null) where = extraWhere + " AND " + where; else where = extraWhere; break; default: throw new IllegalArgumentException("Unknown URI"); } getContext().getContentResolver().notifyChange(URI, null); return _dbAdapter.getRawDB().delete("subscriptions", where, whereArgs); } }
true
true
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int uriMatch = _uriMatcher.match(uri); if (uriMatch == PODCASTS) { return getContext().getContentResolver().query(PodcastProvider.URI, projection, "subscriptionId = ?", new String[] { uri.getPathSegments().get(1) }, PodcastProvider.COLUMN_PUB_DATE); } SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setProjectionMap(_columnMap); sqlBuilder.setTables("subscriptions"); switch (uriMatch) { case SUBSCRIPTIONS: if (sortOrder == null) sortOrder = "title IS NULL, title"; break; case SUBSCRIPTION_ID: sqlBuilder.appendWhere("_id = " + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unknown URI"); } Cursor c = sqlBuilder.query(_dbAdapter.getRawDB(), projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; }
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int uriMatch = _uriMatcher.match(uri); if (uriMatch == PODCASTS) { return getContext().getContentResolver().query(PodcastProvider.URI, projection, "subscriptionId = ?", new String[] { uri.getPathSegments().get(1) }, PodcastProvider.COLUMN_PUB_DATE + " DESC"); } SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setProjectionMap(_columnMap); sqlBuilder.setTables("subscriptions"); switch (uriMatch) { case SUBSCRIPTIONS: if (sortOrder == null) sortOrder = "title IS NULL, title"; break; case SUBSCRIPTION_ID: sqlBuilder.appendWhere("_id = " + uri.getLastPathSegment()); break; default: throw new IllegalArgumentException("Unknown URI"); } Cursor c = sqlBuilder.query(_dbAdapter.getRawDB(), projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; }
diff --git a/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestStatement.java b/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestStatement.java index d982259ed..1f10d424a 100644 --- a/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestStatement.java +++ b/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestStatement.java @@ -1,1006 +1,1006 @@ package it.unibz.krdb.obda.owlrefplatform.core; import it.unibz.krdb.obda.codec.DatalogProgramToTextCodec; import it.unibz.krdb.obda.model.Atom; import it.unibz.krdb.obda.model.BuiltinPredicate; import it.unibz.krdb.obda.model.CQIE; import it.unibz.krdb.obda.model.DatalogProgram; import it.unibz.krdb.obda.model.Function; import it.unibz.krdb.obda.model.GraphResultSet; import it.unibz.krdb.obda.model.NewLiteral; import it.unibz.krdb.obda.model.OBDAConnection; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDAException; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.OBDAQuery; import it.unibz.krdb.obda.model.OBDAResultSet; import it.unibz.krdb.obda.model.OBDAStatement; import it.unibz.krdb.obda.model.Predicate; import it.unibz.krdb.obda.model.Variable; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.ontology.Assertion; import it.unibz.krdb.obda.owlrefplatform.core.abox.EquivalentTriplePredicateIterator; import it.unibz.krdb.obda.owlrefplatform.core.abox.RDBMSDataRepositoryManager; import it.unibz.krdb.obda.owlrefplatform.core.basicoperations.DatalogNormalizer; import it.unibz.krdb.obda.owlrefplatform.core.basicoperations.QueryVocabularyValidator; import it.unibz.krdb.obda.owlrefplatform.core.basicoperations.Unifier; import it.unibz.krdb.obda.owlrefplatform.core.reformulation.QueryRewriter; import it.unibz.krdb.obda.owlrefplatform.core.resultset.BooleanOWLOBDARefResultSet; import it.unibz.krdb.obda.owlrefplatform.core.resultset.ConstructGraphResultSet; import it.unibz.krdb.obda.owlrefplatform.core.resultset.DescribeGraphResultSet; import it.unibz.krdb.obda.owlrefplatform.core.resultset.EmptyQueryResultSet; import it.unibz.krdb.obda.owlrefplatform.core.resultset.QuestResultset; import it.unibz.krdb.obda.owlrefplatform.core.srcquerygeneration.SQLQueryGenerator; import it.unibz.krdb.obda.owlrefplatform.core.translator.SparqlAlgebraToDatalogTranslator; import it.unibz.krdb.obda.owlrefplatform.core.unfolding.DatalogUnfolder; import it.unibz.krdb.obda.owlrefplatform.core.unfolding.ExpressionEvaluator; import it.unibz.krdb.obda.owlrefplatform.core.unfolding.UnfoldingMechanism; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.sparql.syntax.Template; /** * The obda statement provides the implementations necessary to query the * reformulation platform reasoner from outside, i.e. Protege */ public class QuestStatement implements OBDAStatement { private QueryRewriter rewriter = null; private UnfoldingMechanism unfoldingmechanism = null; private SQLQueryGenerator querygenerator = null; private QueryVocabularyValidator validator = null; private OBDAModel unfoldingOBDAModel = null; private boolean canceled = false; private Statement sqlstatement; private RDBMSDataRepositoryManager repository; private QuestConnection conn; protected Quest questInstance; private static Logger log = LoggerFactory.getLogger(QuestStatement.class); private static OBDADataFactory ofac = OBDADataFactoryImpl.getInstance(); Thread runningThread = null; private QueryExecutionThread executionthread; private DatalogProgram programAfterRewriting; private DatalogProgram programAfterUnfolding; final Map<String, String> querycache; final Map<String, List<String>> signaturecache; final Map<String, Boolean> isbooleancache; final Map<String, Boolean> isconstructcache; final Map<String, Boolean> isdescribecache; final SparqlAlgebraToDatalogTranslator translator; /* * For benchmark purpose */ private long queryProcessingTime = 0; private long rewritingTime = 0; private long unfoldingTime = 0; public QuestStatement(Quest questinstance, QuestConnection conn, Statement st) { this.questInstance = questinstance; this.translator = new SparqlAlgebraToDatalogTranslator( this.questInstance.getUriTemplateMatcher()); this.querycache = questinstance.getSQLCache(); this.signaturecache = questinstance.getSignatureCache(); this.isbooleancache = questinstance.getIsBooleanCache(); this.isconstructcache = questinstance.getIsConstructCache(); this.isdescribecache = questinstance.getIsDescribeCache(); this.repository = questinstance.dataRepository; this.conn = conn; this.rewriter = questinstance.rewriter; this.unfoldingmechanism = questinstance.unfolder; this.querygenerator = questinstance.datasourceQueryGenerator; this.sqlstatement = st; this.validator = questinstance.vocabularyValidator; this.unfoldingOBDAModel = questinstance.unfoldingOBDAModel; } private class QueryExecutionThread extends Thread { private final CountDownLatch monitor; private final String strquery; private OBDAResultSet tupleResult; private GraphResultSet graphResult; private Exception exception; private boolean error = false; private boolean executingSQL = false; public QueryExecutionThread(String strquery, CountDownLatch monitor) { this.monitor = monitor; this.strquery = strquery; } public boolean errorStatus() { return error; } public Exception getException() { return exception; } public OBDAResultSet getTupleResult() { return tupleResult; } public GraphResultSet getGraphResult() { return graphResult; } public void cancel() throws SQLException { if (!executingSQL) { this.stop(); } else { sqlstatement.cancel(); } } @Override public void run() { try { if (!querycache.containsKey(strquery)) { final long startTime = System.currentTimeMillis(); String sqlQuery = getUnfolding(strquery); final long endTime = System.currentTimeMillis(); queryProcessingTime = endTime - startTime; // Cache the sql for better performance cacheQueryAndProperties(strquery, sqlQuery); } String sql = querycache.get(strquery); List<String> signature = signaturecache.get(strquery); boolean isBoolean = isbooleancache.get(strquery); boolean isConstruct = isconstructcache.get(strquery); boolean isDescribe = isdescribecache.get(strquery); log.debug("Executing the query and get the result..."); if (sql.equals("") && !isBoolean) { tupleResult = new EmptyQueryResultSet(signature, QuestStatement.this); } else if (sql.equals("")) { tupleResult = new BooleanOWLOBDARefResultSet(false, QuestStatement.this); } else { try { // Check pre-condition for DESCRIBE if (isDescribe && signature.size() > 1) { throw new OBDAException( "Only support query with one variable in DESCRIBE"); } // Execute the SQL query string executingSQL = true; ResultSet set = null; try { set = sqlstatement.executeQuery(sql); } catch(SQLException e) { //bring back operation //statement was created, but in the meantime connection broke down //recover connection if (e.getMessage().startsWith("This statement")) { conn = questInstance.getConnection(); log.debug("Query execution interrupted. Recovering connection to db: "+!conn.isClosed()); sqlstatement = conn.createStatement().sqlstatement; set = sqlstatement.executeQuery(sql); log.debug("Recovery finished successfully: "+!set.isClosed()); } else { throw e; } } // Store the SQL result to application result set. if (isBoolean) { tupleResult = new BooleanOWLOBDARefResultSet(set, QuestStatement.this); } else if (isConstruct) { Query query = QueryFactory.create(strquery); Template template = query.getConstructTemplate(); OBDAResultSet tuples = new QuestResultset(set, signature, QuestStatement.this); graphResult = new ConstructGraphResultSet(tuples, template); } else if (isDescribe) { Query query = QueryFactory.create(strquery); PrefixMapping pm = query.getPrefixMapping(); OBDAResultSet tuples = new QuestResultset(set, signature, QuestStatement.this); graphResult = new DescribeGraphResultSet(tuples, pm); } else { // is tuple-based results tupleResult = new QuestResultset(set, signature, QuestStatement.this); } } catch (SQLException e) { throw new OBDAException("Error executing SQL query: \n" + e.getMessage() + "\nSQL query:\n " + sql); } } log.debug("Finish.\n"); } catch (Exception e) { exception = e; error = true; } finally { monitor.countDown(); } } } /** * Returns the result set for the given query */ @Override public OBDAResultSet execute(String strquery) throws OBDAException { if (strquery.isEmpty()) { throw new OBDAException("Cannot execute an empty query"); } return executeSelectQuery(strquery); } @Override public GraphResultSet executeConstruct(String strquery) throws OBDAException { if (strquery.isEmpty()) { throw new OBDAException("Cannot execute an empty query"); } return executeConstructQuery(strquery); } @Override public GraphResultSet executeDescribe(String strquery) throws OBDAException { if (strquery.isEmpty()) { throw new OBDAException("Cannot execute an empty query"); } return executeDescribeQuery(strquery); } /** * Translates a SPARQL query into Datalog dealing with equivalences and * verifying that the vocabulary of the query matches the one in the * ontology. If there are equivalences to handle, this is where its done * (i.e., renaming atoms that use predicates that have been replaced by a * canonical one. * * @param query * @return */ private DatalogProgram translateAndPreProcess(Query query) throws OBDAException { // Contruct the datalog program object from the query string DatalogProgram program = null; try { program = translator.translate(query); log.debug("Translated query: \n{}", program.toString()); DatalogUnfolder unfolder = new DatalogUnfolder(program.clone(), new HashMap<Predicate, List<Integer>>()); removeNonAnswerQueries(program); program = unfolder.unfold(program, "ans1"); log.debug("Flattened query: \n{}", program.toString()); } catch (Exception e) { e.printStackTrace(); OBDAException ex = new OBDAException(e.getMessage()); ex.setStackTrace(e.getStackTrace()); throw ex; } log.debug("Replacing equivalences..."); program = validator.replaceEquivalences(program); return program; } private DatalogProgram getUnfolding(DatalogProgram query) throws OBDAException { log.debug("Start the partial evaluation process..."); DatalogProgram unfolding = unfoldingmechanism.unfold( (DatalogProgram) query, "ans1"); log.debug("Partial evaluation: {}\n", unfolding); removeNonAnswerQueries(unfolding); log.debug("After target rules removed: \n{}", unfolding); ExpressionEvaluator evaluator = new ExpressionEvaluator(); evaluator.setUriTemplateMatcher(questInstance.getUriTemplateMatcher()); evaluator.evaluateExpressions(unfolding); log.debug("Boolean expression evaluated: \n{}", unfolding); log.debug("Partial evaluation ended."); return unfolding; } private void removeNonAnswerQueries(DatalogProgram program) { List<CQIE> toRemove = new LinkedList<CQIE>(); for (CQIE rule : program.getRules()) { Predicate headPredicate = rule.getHead().getPredicate(); if (!headPredicate.getName().toString().equals("ans1")) { toRemove.add(rule); } } program.removeRules(toRemove); } private String getSQL(DatalogProgram query, List<String> signature) throws OBDAException { if (((DatalogProgram) query).getRules().size() == 0) { return ""; } log.debug("Producing the SQL string..."); // query = DatalogNormalizer.normalizeDatalogProgram(query); String sql = querygenerator.generateSourceQuery((DatalogProgram) query, signature); log.debug("Resulting sql: \n{}", sql); return sql; } private OBDAResultSet executeSelectQuery(String strquery) throws OBDAException { CountDownLatch monitor = new CountDownLatch(1); executionthread = new QueryExecutionThread(strquery, monitor); executionthread.start(); try { monitor.await(); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } if (executionthread.errorStatus()) { throw new RuntimeException(executionthread.getException()); // OBDAException ex = new // OBDAException(executionthread.getException().getMessage()); // ex.setStackTrace(executionthread.getStackTrace()); // throw ex; } if (canceled == true) { canceled = false; throw new OBDAException("Query execution was cancelled"); } OBDAResultSet result = executionthread.getTupleResult(); if (result == null) throw new RuntimeException("Error, the result set was null"); return executionthread.getTupleResult(); } private GraphResultSet executeConstructQuery(String strquery) throws OBDAException { CountDownLatch monitor = new CountDownLatch(1); executionthread = new QueryExecutionThread(strquery, monitor); executionthread.start(); try { monitor.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (executionthread.errorStatus()) { OBDAException ex = new OBDAException(executionthread.getException() .getMessage()); ex.setStackTrace(executionthread.getStackTrace()); throw ex; } if (canceled == true) { canceled = false; throw new OBDAException("Query execution was cancelled"); } return executionthread.getGraphResult(); } private GraphResultSet executeDescribeQuery(String strquery) throws OBDAException { CountDownLatch monitor = new CountDownLatch(1); executionthread = new QueryExecutionThread(strquery, monitor); executionthread.start(); try { monitor.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (executionthread.errorStatus()) { OBDAException ex = new OBDAException(executionthread.getException() .getMessage()); ex.setStackTrace(executionthread.getStackTrace()); throw ex; } if (canceled == true) { canceled = false; throw new OBDAException("Query execution was cancelled"); } return executionthread.getGraphResult(); } /** * Returns the final rewriting of the given query */ public String getRewriting(String strquery) throws Exception { // TODO FIX to limit to SPARQL input and output log.debug("Input user query:\n" + strquery); Query query = QueryFactory.create(strquery); DatalogProgram program = translateAndPreProcess(query); OBDAQuery rewriting = rewriter.rewrite(program); DatalogProgramToTextCodec codec = new DatalogProgramToTextCodec( unfoldingOBDAModel); return codec.encode((DatalogProgram) rewriting); } /** * Returns the final rewriting of the given query */ public DatalogProgram getRewriting(DatalogProgram program) throws OBDAException { OBDAQuery rewriting = rewriter.rewrite(program); return (DatalogProgram) rewriting; } /** * Returns the final rewriting of the given query */ public String getUnfolding(String strquery) throws Exception { String sql = ""; List<String> signature; Map<Predicate, List<CQIE>> rulesIndex = questInstance.sigmaRulesIndex; // Check the cache first if the system has processed the query string before if (querycache.containsKey(strquery)) { // Obtain immediately the SQL string from cache sql = querycache.get(strquery); } else { Query query = QueryFactory.create(strquery); DatalogProgram program = translateAndPreProcess(query); try { log.debug("Input user query:\n" + strquery); for (CQIE q : program.getRules()) { DatalogNormalizer.unfoldJoinTrees(q, false); } log.debug("Normalized program: \n{}", program); /* * Empty unfolding, constructing an empty result set */ if (program.getRules().size() < 1) { throw new OBDAException("Error, invalid query"); } /* * Query optimization w.r.t Sigma rules */ optimizeQueryWithSigmaRules(program, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException(e1); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } log.debug("Start the rewriting process..."); try { final long startTime = System.currentTimeMillis(); programAfterRewriting = getRewriting(program); final long endTime = System.currentTimeMillis(); rewritingTime = endTime - startTime; - optimizeQueryWithSigmaRules(program, rulesIndex); + optimizeQueryWithSigmaRules(programAfterRewriting, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error rewriting query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { final long startTime = System.currentTimeMillis(); programAfterUnfolding = getUnfolding(programAfterRewriting); final long endTime = System.currentTimeMillis(); unfoldingTime = endTime - startTime; } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error unfolding query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { signature = getSignature(query); sql = getSQL(programAfterUnfolding, signature); cacheQueryAndProperties(strquery, sql); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error generating SQL. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } } return sql; } /** * * @param program * @param rules */ private void optimizeQueryWithSigmaRules(DatalogProgram program, Map<Predicate, List<CQIE>> rulesIndex) { List<CQIE> unionOfQueries = new LinkedList<CQIE>(program.getRules()); //for each rule in the query for (int qi = 0; qi < unionOfQueries.size() ; qi++) { CQIE query = unionOfQueries.get(qi); //get query head, body Atom queryHead = query.getHead(); List<Atom> queryBody = query.getBody(); //for each atom in query body for (int i = 0; i < queryBody.size(); i++) { Set<Atom> removedAtom = new HashSet<Atom>(); Atom atomQuery = queryBody.get(i); Predicate predicate = atomQuery.getPredicate(); //for each tbox rule List<CQIE> rules = rulesIndex.get(predicate); if (rules == null || rules.isEmpty()) { continue; } for (CQIE rule : rules) { //try to unify current query body atom with tbox rule body atom Atom ruleBody = rule.getBody().get(0); Map<Variable, NewLiteral> theta = Unifier.getMGU(ruleBody, atomQuery); // TODO optimize index if (theta == null || theta.isEmpty()) { continue; } // if unifiable, apply to head of tbox rule Atom ruleHead = rule.getHead(); Atom copyRuleHead = ruleHead.clone(); Unifier.applyUnifier(copyRuleHead, theta); removedAtom.add(copyRuleHead); } for (int j = 0; j < queryBody.size(); j++) { if (j == i) { continue; } Atom toRemove = queryBody.get(j); if (removedAtom.contains(toRemove)) { queryBody.remove(j); j -= 1; if (j < i) { i -= 1; } } } } //update query datalog program unionOfQueries.remove(qi); unionOfQueries.add(qi, ofac.getCQIE(queryHead, queryBody)); } program.removeAllRules(); program.appendRule(unionOfQueries); } private void cacheQueryAndProperties(String sparqlQuery, String sqlQuery) { // Store the query querycache.put(sparqlQuery, sqlQuery); // Store the query properties Query query = QueryFactory.create(sparqlQuery); List<String> signature = getSignature(query); signaturecache.put(sparqlQuery, signature); boolean isBoolean = isBoolean(query); isbooleancache.put(sparqlQuery, isBoolean); boolean isConstruct = isConstruct(query); isconstructcache.put(sparqlQuery, isConstruct); boolean isDescribe = isDescribe(query); isdescribecache.put(sparqlQuery, isDescribe); } /** * Returns the number of tuples returned by the query */ public int getTupleCount(String query) throws Exception { String unf = getUnfolding(query); String newsql = "SELECT count(*) FROM (" + unf + ") t1"; if (!canceled) { ResultSet set = sqlstatement.executeQuery(newsql); if (set.next()) { return set.getInt(1); } else { throw new Exception( "Tuple count faild due to empty result set."); } } else { throw new Exception("Action canceled."); } } @Override public void close() throws OBDAException { try { sqlstatement.close(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } // private DatalogProgram getDatalogQuery(String query) throws OBDAException // { // SPARQLDatalogTranslator sparqlTranslator = new SPARQLDatalogTranslator(); // // DatalogProgram queryProgram = null; // try { // queryProgram = sparqlTranslator.parse(query); // } catch (QueryException e) { // log.warn(e.getMessage()); // } // // if (queryProgram == null) { // if the SPARQL translator doesn't work, // // use the Datalog parser. // DatalogProgramParser datalogParser = new DatalogProgramParser(); // try { // queryProgram = datalogParser.parse(query); // } catch (RecognitionException e) { // log.warn(e.getMessage()); // queryProgram = null; // } catch (IllegalArgumentException e2) { // log.warn(e2.getMessage()); // } // } // // if (queryProgram == null) // if it is still null // throw new OBDAException("Unsupported syntax"); // // return queryProgram; // } private List<String> getSignature(Query query) { List<String> signature = translator.getSignature(query); return signature; } private boolean isBoolean(Query query) { return query.isAskType(); } private boolean isConstruct(Query query) { return query.isConstructType(); } public boolean isDescribe(Query query) { return query.isDescribeType(); } @Override public void cancel() throws OBDAException { try { QuestStatement.this.executionthread.cancel(); } catch (SQLException e) { OBDAException o = new OBDAException(e); o.setStackTrace(e.getStackTrace()); throw o; } } @Override public int executeUpdate(String query) throws OBDAException { // TODO Auto-generated method stub return 0; } @Override public int getFetchSize() throws OBDAException { try { return sqlstatement.getFetchSize(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public int getMaxRows() throws OBDAException { try { return sqlstatement.getMaxRows(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public void getMoreResults() throws OBDAException { try { sqlstatement.getMoreResults(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public void setFetchSize(int rows) throws OBDAException { try { sqlstatement.setFetchSize(rows); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public void setMaxRows(int max) throws OBDAException { try { sqlstatement.setMaxRows(max); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public void setQueryTimeout(int seconds) throws OBDAException { try { sqlstatement.setQueryTimeout(seconds); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public OBDAConnection getConnection() throws OBDAException { return conn; } @Override public OBDAResultSet getResultSet() throws OBDAException { return null; } @Override public int getQueryTimeout() throws OBDAException { try { return sqlstatement.getQueryTimeout(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } @Override public boolean isClosed() throws OBDAException { try { return sqlstatement.isClosed(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } /*** * Inserts a stream of ABox assertions into the repository. * * @param data * @param recreateIndexes * Indicates if indexes (if any) should be droped before * inserting the tuples and recreated afterwards. Note, if no * index existed before the insert no drop will be done and no * new index will be created. * @throws SQLException */ public int insertData(Iterator<Assertion> data, boolean useFile, int commit, int batch) throws SQLException { int result = -1; EquivalentTriplePredicateIterator newData = new EquivalentTriplePredicateIterator( data, questInstance.getEquivalenceMap()); if (!useFile) { result = repository.insertData(conn.conn, newData, commit, batch); } else { try { // File temporalFile = new File("quest-copy.tmp"); // FileOutputStream os = new FileOutputStream(temporalFile); result = (int) repository.loadWithFile(conn.conn, newData); // os.close(); } catch (IOException e) { log.error(e.getMessage()); } } return result; } /*** * As before, but using recreateIndexes = false. * * @param data * @throws SQLException */ public int insertData(Iterator<Assertion> data, int commit, int batch) throws SQLException { return insertData(data, false, commit, batch); } public void createIndexes() throws Exception { repository.createIndexes(conn.conn); } public void dropIndexes() throws Exception { repository.dropIndexes(conn.conn); } public boolean isIndexed() { if (repository == null) return false; return repository.isIndexed(conn.conn); } public void dropRepository() throws SQLException { if (repository == null) return; repository.dropDBSchema(conn.conn); } /*** * In an ABox store (classic) this methods triggers the generation of the * schema and the insertion of the metadata. * * @throws SQLException */ public void createDB() throws SQLException { repository.createDBSchema(conn.conn, false); repository.insertMetadata(conn.conn); } public void analyze() throws Exception { repository.collectStatistics(conn.conn); } /* * Methods for getting the benchmark parameters */ public long getQueryProcessingTime() { return queryProcessingTime; } public long getRewritingTime() { return rewritingTime; } public long getUnfoldingTime() { return unfoldingTime; } public int getUCQSizeAfterRewriting() { return programAfterRewriting.getRules().size(); } public int getMinQuerySizeAfterRewriting() { int toReturn = Integer.MAX_VALUE; List<CQIE> rules = programAfterRewriting.getRules(); for (CQIE rule : rules) { int querySize = getBodySize(rule.getBody()); if (querySize < toReturn) { toReturn = querySize; } } return toReturn; } public int getMaxQuerySizeAfterRewriting() { int toReturn = Integer.MIN_VALUE; List<CQIE> rules = programAfterRewriting.getRules(); for (CQIE rule : rules) { int querySize = getBodySize(rule.getBody()); if (querySize > toReturn) { toReturn = querySize; } } return toReturn; } public int getUCQSizeAfterUnfolding() { return programAfterUnfolding.getRules().size(); } public int getMinQuerySizeAfterUnfolding() { int toReturn = Integer.MAX_VALUE; List<CQIE> rules = programAfterUnfolding.getRules(); for (CQIE rule : rules) { int querySize = getBodySize(rule.getBody()); if (querySize < toReturn) { toReturn = querySize; } } return (toReturn == Integer.MAX_VALUE) ? 0 : toReturn; } public int getMaxQuerySizeAfterUnfolding() { int toReturn = Integer.MIN_VALUE; List<CQIE> rules = programAfterUnfolding.getRules(); for (CQIE rule : rules) { int querySize = getBodySize(rule.getBody()); if (querySize > toReturn) { toReturn = querySize; } } return (toReturn == Integer.MIN_VALUE) ? 0 : toReturn; } private int getBodySize(List<? extends Function> atoms) { int counter = 0; for (Function atom : atoms) { Predicate predicate = atom.getPredicate(); if (!(predicate instanceof BuiltinPredicate)) { counter++; } } return counter; } }
true
true
public String getUnfolding(String strquery) throws Exception { String sql = ""; List<String> signature; Map<Predicate, List<CQIE>> rulesIndex = questInstance.sigmaRulesIndex; // Check the cache first if the system has processed the query string before if (querycache.containsKey(strquery)) { // Obtain immediately the SQL string from cache sql = querycache.get(strquery); } else { Query query = QueryFactory.create(strquery); DatalogProgram program = translateAndPreProcess(query); try { log.debug("Input user query:\n" + strquery); for (CQIE q : program.getRules()) { DatalogNormalizer.unfoldJoinTrees(q, false); } log.debug("Normalized program: \n{}", program); /* * Empty unfolding, constructing an empty result set */ if (program.getRules().size() < 1) { throw new OBDAException("Error, invalid query"); } /* * Query optimization w.r.t Sigma rules */ optimizeQueryWithSigmaRules(program, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException(e1); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } log.debug("Start the rewriting process..."); try { final long startTime = System.currentTimeMillis(); programAfterRewriting = getRewriting(program); final long endTime = System.currentTimeMillis(); rewritingTime = endTime - startTime; optimizeQueryWithSigmaRules(program, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error rewriting query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { final long startTime = System.currentTimeMillis(); programAfterUnfolding = getUnfolding(programAfterRewriting); final long endTime = System.currentTimeMillis(); unfoldingTime = endTime - startTime; } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error unfolding query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { signature = getSignature(query); sql = getSQL(programAfterUnfolding, signature); cacheQueryAndProperties(strquery, sql); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error generating SQL. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } } return sql; }
public String getUnfolding(String strquery) throws Exception { String sql = ""; List<String> signature; Map<Predicate, List<CQIE>> rulesIndex = questInstance.sigmaRulesIndex; // Check the cache first if the system has processed the query string before if (querycache.containsKey(strquery)) { // Obtain immediately the SQL string from cache sql = querycache.get(strquery); } else { Query query = QueryFactory.create(strquery); DatalogProgram program = translateAndPreProcess(query); try { log.debug("Input user query:\n" + strquery); for (CQIE q : program.getRules()) { DatalogNormalizer.unfoldJoinTrees(q, false); } log.debug("Normalized program: \n{}", program); /* * Empty unfolding, constructing an empty result set */ if (program.getRules().size() < 1) { throw new OBDAException("Error, invalid query"); } /* * Query optimization w.r.t Sigma rules */ optimizeQueryWithSigmaRules(program, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException(e1); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } log.debug("Start the rewriting process..."); try { final long startTime = System.currentTimeMillis(); programAfterRewriting = getRewriting(program); final long endTime = System.currentTimeMillis(); rewritingTime = endTime - startTime; optimizeQueryWithSigmaRules(programAfterRewriting, rulesIndex); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error rewriting query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { final long startTime = System.currentTimeMillis(); programAfterUnfolding = getUnfolding(programAfterRewriting); final long endTime = System.currentTimeMillis(); unfoldingTime = endTime - startTime; } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error unfolding query. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } try { signature = getSignature(query); sql = getSQL(programAfterUnfolding, signature); cacheQueryAndProperties(strquery, sql); } catch (Exception e1) { log.debug(e1.getMessage(), e1); OBDAException obdaException = new OBDAException( "Error generating SQL. \n" + e1.getMessage()); obdaException.setStackTrace(e1.getStackTrace()); throw obdaException; } } return sql; }
diff --git a/src/org/liberty/android/fantastischmemo/cardscreen/MemoScreen.java b/src/org/liberty/android/fantastischmemo/cardscreen/MemoScreen.java index 042afe1b..d91c49fe 100644 --- a/src/org/liberty/android/fantastischmemo/cardscreen/MemoScreen.java +++ b/src/org/liberty/android/fantastischmemo/cardscreen/MemoScreen.java @@ -1,630 +1,630 @@ /* 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.cardscreen; import org.liberty.android.fantastischmemo.*; import org.liberty.android.fantastischmemo.tts.*; import org.amr.arabic.ArabicUtilities; import org.xml.sax.XMLReader; import java.io.InputStream; import java.io.FileInputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Date; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.Editable; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import android.content.Context; import android.preference.PreferenceManager; import android.text.Html; import android.text.ClipboardManager; import android.view.Gravity; import android.view.Menu; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Display; import android.view.LayoutInflater; import android.view.Window; import android.view.WindowManager; import android.view.ViewGroup; import android.view.KeyEvent; import android.gesture.GestureOverlayView; import android.widget.Button; import android.os.Handler; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.EditText; import android.widget.ListView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.Toast; import android.util.Log; import android.os.SystemClock; import android.os.Environment; import android.graphics.Typeface; import android.text.Html.TagHandler; import android.text.Html.ImageGetter; import android.content.res.Configuration; import android.view.inputmethod.InputMethodManager; import android.net.Uri; public class MemoScreen extends AMActivity{ private final static String TAG = "org.liberty.android.fantastischmemo.cardscreen.MemoScreen"; private AnyMemoTTS questionTTS = null; private AnyMemoTTS answerTTS = null; private final int DIALOG_LOADING_PROGRESS = 100; private final int ACTIVITY_FILTER = 10; private final int ACTIVITY_EDIT = 11; private final int ACTIVITY_CARD_TOOLBOX = 12; private final int ACTIVITY_DB_TOOLBOX = 13; private final int ACTIVITY_GOTO_PREV = 14; private final int ACTIVITY_SETTINGS = 15; Handler mHandler; Item currentItem = null; Item prevItem = null; String dbPath = ""; String dbName = ""; String activeFilter = ""; FlashcardDisplay flashcardDisplay; SettingManager settingManager; ControlButtons controlButtons; QueueManager queueManager; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.memo_screen_layout); Bundle extras = getIntent().getExtras(); mHandler = new Handler(); if (extras != null) { dbPath = extras.getString("dbpath"); dbName = extras.getString("dbname"); activeFilter = extras.getString("filter"); } try{ settingManager = new SettingManager(this, dbPath, dbName); flashcardDisplay = new FlashcardDisplay(this, settingManager); if(settingManager.getButtonStyle() == SettingManager.ButtonStyle.ANKI){ controlButtons = new AnkiGradeButtons(this); } else if(settingManager.getButtonStyle() == SettingManager.ButtonStyle.MNEMOSYNE){ controlButtons = new MnemosyneGradeButtons(this); } else{ controlButtons = new AnyMemoGradeButtons(this); } initTTS(); composeViews(); hideButtons(); registerForContextMenu(flashcardDisplay.getView()); /* Run the learnQueue init in a separate thread */ createQueue(); initQueue(); } catch(Exception e){ AMGUIUtility.displayError(this, getString(R.string.open_database_error_title), getString(R.string.open_database_error_message), e); } } void createQueue(){ queueManager =new LearnQueueManager.Builder(this, dbPath, dbName) .setFilter(activeFilter) .setQueueSize(settingManager.getLearningQueueSize()) .setShuffle(settingManager.getShufflingCards()) .build(); } void initQueue(){ showDialog(DIALOG_LOADING_PROGRESS); new Thread(){ public void run(){ queueManager.initQueue(); currentItem = queueManager.updateAndNext(null); mHandler.post(new Runnable(){ public void run(){ if(currentItem == null){ showNoItemDialog(); } else{ setViewListeners(); updateFlashcardView(false); } removeDialog(DIALOG_LOADING_PROGRESS); } }); } }.start(); } @Override public void onDestroy(){ if(settingManager != null){ settingManager.close(); settingManager = null; } if(questionTTS != null){ questionTTS.shutdown(); } if(answerTTS != null){ answerTTS.shutdown(); } if(queueManager != null){ queueManager.close(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.memo_screen_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_memo_help: { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.addCategory(Intent.CATEGORY_BROWSABLE); myIntent.setData(Uri.parse(getString(R.string.website_help_memo))); startActivity(myIntent); return true; } case R.id.menuspeakquestion: { if(questionTTS != null && currentItem != null){ questionTTS.sayText(currentItem.getQuestion()); } return true; } case R.id.menuspeakanswer: { if(answerTTS != null && currentItem != null){ - answerTTS.sayText(currentItem.getQuestion()); + answerTTS.sayText(currentItem.getAnswer()); } return true; } case R.id.menusettings: { Intent myIntent = new Intent(this, SettingsScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_SETTINGS); return true; } case R.id.menudetail: { Intent myIntent = new Intent(this, DetailScreen.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("itemid", currentItem.getId()); startActivityForResult(myIntent, 2); return true; } case R.id.menuundo: { undoItem(); return true; } case R.id.menu_memo_filter: { Intent myIntent = new Intent(this, Filter.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_FILTER); return true; } } return false; } /* * When the user select the undo from the menu * this is what to do */ protected void undoItem(){ if(prevItem != null){ currentItem = prevItem.clone(); queueManager.insertIntoQueue(currentItem, 0); prevItem = null; updateFlashcardView(false); hideButtons(); } else{ new AlertDialog.Builder(this) .setTitle(getString(R.string.undo_fail_text)) .setMessage(getString(R.string.undo_fail_message)) .setNeutralButton(R.string.ok_text, null) .create() .show(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){ super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.memoscreen_context_menu, menu); menu.setHeaderTitle(R.string.menu_text); } @Override public boolean onContextItemSelected(MenuItem menuitem) { switch(menuitem.getItemId()) { case R.id.menu_context_edit: { Intent myIntent = new Intent(this, CardEditor.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("item", currentItem); startActivityForResult(myIntent, ACTIVITY_EDIT); return true; } case R.id.menu_context_gotoprev: { Intent myIntent = new Intent(this, EditScreen.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("id", currentItem.getId()); startActivityForResult(myIntent, ACTIVITY_GOTO_PREV); return true; } default: { return super.onContextItemSelected(menuitem); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(resultCode ==Activity.RESULT_CANCELED){ return; } switch(requestCode){ case ACTIVITY_FILTER: { Bundle extras = data.getExtras(); activeFilter = extras.getString("filter"); restartActivity(); break; } case ACTIVITY_EDIT: { Bundle extras = data.getExtras(); Item item = (Item)extras.getSerializable("item"); if(item != null){ currentItem = item; updateFlashcardView(false); queueManager.updateQueueItem(currentItem); } break; } case ACTIVITY_GOTO_PREV: { restartActivity(); break; } case ACTIVITY_SETTINGS: { restartActivity(); break; } } } @Override public Dialog onCreateDialog(int id){ switch(id){ case DIALOG_LOADING_PROGRESS:{ ProgressDialog progressDialog = new ProgressDialog(MemoScreen.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setTitle(getString(R.string.loading_please_wait)); progressDialog.setMessage(getString(R.string.loading_database)); progressDialog.setCancelable(false); return progressDialog; } default: return super.onCreateDialog(id); } } void updateFlashcardView(boolean showAnswer){ flashcardDisplay.updateView(currentItem, showAnswer); setActivityTitle(); setGradeButtonTitle(); setGradeButtonListeners(); } void setViewListeners(){ View.OnClickListener showAnswerListener = new View.OnClickListener(){ public void onClick(View v){ if(currentItem != null){ showButtons(); updateFlashcardView(true); controlButtons.getView().setVisibility(View.VISIBLE); } } }; View.OnClickListener speakQuestionListener = new View.OnClickListener(){ public void onClick(View v){ if(currentItem != null){ questionTTS.sayText(currentItem.getQuestion()); } } }; View.OnClickListener speakAnswerListener = new View.OnClickListener(){ public void onClick(View v){ if(currentItem != null){ updateFlashcardView(true); showButtons(); answerTTS.sayText(currentItem.getAnswer()); } } }; View.OnLongClickListener openContextMenuListener = new View.OnLongClickListener(){ public boolean onLongClick(View v){ MemoScreen.this.openContextMenu(flashcardDisplay.getView()); Log.v(TAG, "Open Menu!"); return true; } }; flashcardDisplay.setQuestionLayoutLongClickListener(openContextMenuListener); flashcardDisplay.setAnswerLayoutLongClickListener(openContextMenuListener); flashcardDisplay.setQuestionLayoutClickListener(showAnswerListener); flashcardDisplay.setAnswerLayoutClickListener(showAnswerListener); if(settingManager.getSpeechControlMethod() == SettingManager.SpeechControlMethod.TAP || settingManager.getSpeechControlMethod() == SettingManager.SpeechControlMethod.AUTOTAP){ flashcardDisplay.setQuestionTextClickListener(speakQuestionListener); flashcardDisplay.setAnswerTextClickListener(speakAnswerListener); } else{ flashcardDisplay.setQuestionTextClickListener(showAnswerListener); flashcardDisplay.setAnswerTextClickListener(showAnswerListener); } } void setGradeButtonTitle(){ Map<String, Button> hm = controlButtons.getButtons(); if(settingManager.getButtonStyle() == SettingManager.ButtonStyle.MNEMOSYNE){ hm.get("0").setText(getString(R.string.memo_btn0_brief_text)); hm.get("1").setText(getString(R.string.memo_btn1_brief_text)); hm.get("2").setText(getString(R.string.memo_btn2_brief_text)); hm.get("3").setText(getString(R.string.memo_btn3_brief_text)); hm.get("4").setText(getString(R.string.memo_btn4_brief_text)); hm.get("5").setText(getString(R.string.memo_btn5_brief_text)); } else if(settingManager.getButtonStyle() == SettingManager.ButtonStyle.ANKI){ hm.get("0").setText(getString(R.string.memo_btn0_anki_text) + "\n+" + currentItem.processAnswer(0, true)); hm.get("1").setText(getString(R.string.memo_btn1_anki_text) + "\n+" + currentItem.processAnswer(1, true)); hm.get("2").setText(getString(R.string.memo_btn2_anki_text) + "\n+" + currentItem.processAnswer(2, true)); hm.get("3").setText(getString(R.string.memo_btn3_anki_text) + "\n+" + currentItem.processAnswer(3, true)); hm.get("4").setText(getString(R.string.memo_btn4_anki_text) + "\n+" + currentItem.processAnswer(4, true)); hm.get("5").setText(getString(R.string.memo_btn5_anki_text) + "\n+" + currentItem.processAnswer(5, true)); } else{ hm.get("0").setText(getString(R.string.memo_btn0_text) + "\n+" + currentItem.processAnswer(0, true)); hm.get("1").setText(getString(R.string.memo_btn1_text) + "\n+" + currentItem.processAnswer(1, true)); hm.get("2").setText(getString(R.string.memo_btn2_text) + "\n+" + currentItem.processAnswer(2, true)); hm.get("3").setText(getString(R.string.memo_btn3_text) + "\n+" + currentItem.processAnswer(3, true)); hm.get("4").setText(getString(R.string.memo_btn4_text) + "\n+" + currentItem.processAnswer(4, true)); hm.get("5").setText(getString(R.string.memo_btn5_text) + "\n+" + currentItem.processAnswer(5, true)); } } void setGradeButtonListeners(){ Map<String, Button> hm = controlButtons.getButtons(); for(int i = 0; i < 6; i++){ Button b = hm.get(Integer.valueOf(i).toString()); b.setOnClickListener(getGradeButtonListener(i)); b.setOnLongClickListener(getGradeButtonLongClickListener(i)); } } void setActivityTitle(){ int[] stat = queueManager.getStatInfo(); setTitle(getString(R.string.stat_new) + stat[0] + " " + getString(R.string.stat_scheduled) + stat[1] + " " + getString(R.string.memo_current_id) + currentItem.getId()); } private View.OnClickListener getGradeButtonListener(final int grade){ return new View.OnClickListener(){ public void onClick(View v){ prevItem = currentItem.clone(); currentItem.processAnswer(grade, false); currentItem = queueManager.updateAndNext(currentItem); if(currentItem == null){ showNoItemDialog(); } else{ updateFlashcardView(false); hideButtons(); } } }; } private View.OnLongClickListener getGradeButtonLongClickListener(final int grade){ return new View.OnLongClickListener(){ public boolean onLongClick(View v){ String[] helpText = {getString(R.string.memo_btn0_help_text),getString(R.string.memo_btn1_help_text),getString(R.string.memo_btn2_help_text),getString(R.string.memo_btn3_help_text),getString(R.string.memo_btn4_help_text),getString(R.string.memo_btn5_help_text)}; Toast.makeText(MemoScreen.this, helpText[grade], Toast.LENGTH_SHORT).show(); return true; } }; } private void hideButtons(){ controlButtons.getView().setVisibility(View.INVISIBLE); } private void showButtons(){ controlButtons.getView().setVisibility(View.VISIBLE); } private void composeViews(){ LinearLayout memoRoot = (LinearLayout)findViewById(R.id.memo_screen_root); LinearLayout flashcardDisplayView = (LinearLayout)flashcardDisplay.getView(); LinearLayout controlButtonsView = (LinearLayout)controlButtons.getView(); /* * -1: Match parent -2: Wrap content * This is necessary or the view will not be * stetched */ memoRoot.addView(flashcardDisplayView, -1, -1); memoRoot.addView(controlButtonsView, -1, -2); flashcardDisplayView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f)); } @Override public void restartActivity(){ Intent myIntent = new Intent(this, MemoScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("filter", activeFilter); finish(); startActivity(myIntent); } void showNoItemDialog(){ new AlertDialog.Builder(this) .setTitle(this.getString(R.string.memo_no_item_title)) .setMessage(this.getString(R.string.memo_no_item_message)) .setNeutralButton(getString(R.string.back_menu_text), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { /* Finish the current activity and go back to the last activity. * It should be the open screen. */ finish(); } }) .setNegativeButton(getString(R.string.learn_ahead), new OnClickListener(){ public void onClick(DialogInterface arg0, int arg1) { finish(); Intent myIntent = new Intent(); myIntent.setClass(MemoScreen.this, CramMemoScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivity(myIntent); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog){ finish(); } }) .create() .show(); } private void initTTS(){ String audioDir = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_audio_dir); Locale ql = settingManager.getQuestionAudioLocale(); Locale al = settingManager.getAnswerAudioLocale(); if(settingManager.getQuestionUserAudio()){ questionTTS = new AudioFileTTS(audioDir, dbName); } else if(ql != null){ if(settingManager.getEnableTTSExtended()){ questionTTS = new AnyMemoTTSExtended(this, ql); } else{ questionTTS = new AnyMemoTTSPlatform(this, ql); } } else{ questionTTS = null; } if(settingManager.getAnswerUserAudio()){ answerTTS = new AudioFileTTS(audioDir, dbName); } else if(al != null){ if(settingManager.getEnableTTSExtended()){ answerTTS = new AnyMemoTTSExtended(this, al); } else{ answerTTS = new AnyMemoTTSPlatform(this, al); } } else{ answerTTS = null; } } }
true
true
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_memo_help: { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.addCategory(Intent.CATEGORY_BROWSABLE); myIntent.setData(Uri.parse(getString(R.string.website_help_memo))); startActivity(myIntent); return true; } case R.id.menuspeakquestion: { if(questionTTS != null && currentItem != null){ questionTTS.sayText(currentItem.getQuestion()); } return true; } case R.id.menuspeakanswer: { if(answerTTS != null && currentItem != null){ answerTTS.sayText(currentItem.getQuestion()); } return true; } case R.id.menusettings: { Intent myIntent = new Intent(this, SettingsScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_SETTINGS); return true; } case R.id.menudetail: { Intent myIntent = new Intent(this, DetailScreen.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("itemid", currentItem.getId()); startActivityForResult(myIntent, 2); return true; } case R.id.menuundo: { undoItem(); return true; } case R.id.menu_memo_filter: { Intent myIntent = new Intent(this, Filter.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_FILTER); return true; } } return false; }
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_memo_help: { Intent myIntent = new Intent(); myIntent.setAction(Intent.ACTION_VIEW); myIntent.addCategory(Intent.CATEGORY_BROWSABLE); myIntent.setData(Uri.parse(getString(R.string.website_help_memo))); startActivity(myIntent); return true; } case R.id.menuspeakquestion: { if(questionTTS != null && currentItem != null){ questionTTS.sayText(currentItem.getQuestion()); } return true; } case R.id.menuspeakanswer: { if(answerTTS != null && currentItem != null){ answerTTS.sayText(currentItem.getAnswer()); } return true; } case R.id.menusettings: { Intent myIntent = new Intent(this, SettingsScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_SETTINGS); return true; } case R.id.menudetail: { Intent myIntent = new Intent(this, DetailScreen.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("itemid", currentItem.getId()); startActivityForResult(myIntent, 2); return true; } case R.id.menuundo: { undoItem(); return true; } case R.id.menu_memo_filter: { Intent myIntent = new Intent(this, Filter.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_FILTER); return true; } } return false; }
diff --git a/src/main/java/org/mvel/compiler/AbstractParser.java b/src/main/java/org/mvel/compiler/AbstractParser.java index 6389a5dd..1a749c67 100644 --- a/src/main/java/org/mvel/compiler/AbstractParser.java +++ b/src/main/java/org/mvel/compiler/AbstractParser.java @@ -1,2285 +1,2285 @@ /** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * 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.mvel.compiler; import org.mvel.*; import static org.mvel.Operator.*; import org.mvel.ast.*; import static org.mvel.ast.TypeDescriptor.getClassReference; import org.mvel.integration.VariableResolverFactory; import static org.mvel.util.ArrayTools.findFirst; import org.mvel.util.ExecutionStack; import static org.mvel.util.ParseTools.*; import org.mvel.util.PropertyTools; import static org.mvel.util.PropertyTools.*; import org.mvel.util.Stack; import org.mvel.util.StringAppender; import java.io.Serializable; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Float.parseFloat; import static java.lang.Runtime.getRuntime; import static java.lang.System.getProperty; import static java.lang.Thread.currentThread; import static java.util.Collections.synchronizedMap; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * @author Christopher Brock */ public class AbstractParser implements Serializable { protected char[] expr; protected int cursor; protected int start; protected int length; protected int fields; protected static final int OP_TERMINATE = -1; protected static final int OP_RESET_FRAME = 0; protected static final int OP_CONTINUE = 1; protected boolean greedy = true; protected boolean lastWasIdentifier = false; protected boolean lastWasLineLabel = false; protected boolean lastWasComment = false; protected boolean literalOnly = true; protected boolean debugSymbols = false; protected int lastLineStart = -1; protected int line = 1; protected ASTNode lastNode; private static Map<String, char[]> EX_PRECACHE; public static final Map<String, Object> LITERALS = new HashMap<String, Object>(35 * 2, 0.4f); public static final Map<String, Integer> OPERATORS = new HashMap<String, Integer>(25 * 2, 0.4f); protected Stack stk; protected ExecutionStack splitAccumulator = new ExecutionStack(); protected static ThreadLocal<ParserContext> parserContext; protected ParserContext pCtx; protected ExecutionStack dStack; protected Object ctx; protected VariableResolverFactory variableFactory; static { configureFactory(); /** * Setup the basic literals */ LITERALS.put("true", TRUE); LITERALS.put("false", FALSE); LITERALS.put("null", null); LITERALS.put("nil", null); LITERALS.put("empty", BlankLiteral.INSTANCE); /** * Add System and all the class wrappers from the JCL. */ LITERALS.put("System", System.class); LITERALS.put("String", String.class); LITERALS.put("Integer", Integer.class); LITERALS.put("int", Integer.class); LITERALS.put("Long", Long.class); LITERALS.put("long", Long.class); LITERALS.put("Boolean", Boolean.class); LITERALS.put("boolean", Boolean.class); LITERALS.put("Short", Short.class); LITERALS.put("short", Short.class); LITERALS.put("Character", Character.class); LITERALS.put("char", Character.class); LITERALS.put("Double", Double.class); LITERALS.put("double", double.class); LITERALS.put("Float", Float.class); LITERALS.put("float", float.class); LITERALS.put("Math", Math.class); LITERALS.put("Void", Void.class); LITERALS.put("Object", Object.class); LITERALS.put("Class", Class.class); LITERALS.put("ClassLoader", ClassLoader.class); LITERALS.put("Runtime", Runtime.class); LITERALS.put("Thread", Thread.class); LITERALS.put("Compiler", Compiler.class); LITERALS.put("StringBuffer", StringBuffer.class); LITERALS.put("ThreadLocal", ThreadLocal.class); LITERALS.put("SecurityManager", SecurityManager.class); LITERALS.put("StrictMath", StrictMath.class); LITERALS.put("Array", java.lang.reflect.Array.class); if (parseFloat(getProperty("java.version").substring(0, 2)) >= 1.5) { try { LITERALS.put("StringBuilder", currentThread().getContextClassLoader().loadClass("java.lang.StringBuilder")); } catch (Exception e) { throw new RuntimeException("cannot resolve a built-in literal", e); } } setLanguageLevel(5); } public static void configureFactory() { if (MVEL.THREAD_SAFE) { EX_PRECACHE = synchronizedMap(new WeakHashMap<String, char[]>(10)); } else { EX_PRECACHE = new WeakHashMap<String, char[]>(10); } } protected ASTNode nextTokenSkipSymbols() { ASTNode n = nextToken(); if (n != null && n.getFields() == -1) n = nextToken(); return n; } /** * Retrieve the next token in the expression. * * @return - */ protected ASTNode nextToken() { try { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, idx; start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ boolean capture = false, union = false; pCtx = getParserContext(); if (debugSymbols) { if (!lastWasLineLabel) { if (pCtx.getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } line = pCtx.getLineCount(); skipWhitespaceWithLineAccounting(); if (!pCtx.isKnownLine(pCtx.getSourceFile(), pCtx.setLineCount(line)) && !pCtx.isBlockSymbols()) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); return lastNode = pCtx.setLastLineLabel(new LineLabel(pCtx.getSourceFile(), line)); } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start != length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor != length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor = trimRight(cursor); captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: return captureCodeBlock(ASTNode.BLOCK_IF); case ELSE: throw new CompileException("else without if", cursor); case FOREACH: return captureCodeBlock(ASTNode.BLOCK_FOREACH); case WHILE: return captureCodeBlock(ASTNode.BLOCK_WHILE); case UNTIL: return captureCodeBlock(ASTNode.BLOCK_UNTIL); case FOR: return captureCodeBlock(ASTNode.BLOCK_FOR); case WITH: return captureCodeBlock(ASTNode.BLOCK_WITH); case DO: return captureCodeBlock(ASTNode.BLOCK_DO); case ISDEF: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new IsDef(subArray(start, cursor)); case IMPORT: start = cursor = trimRight(cursor); captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--)); if (importNode.isPackageImport()) { pCtx.addPackageImport(importNode.getPackageImport()); cursor++; } else { pCtx.addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); } return importNode; case IMPORT_STATIC: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--)); case FUNCTION: Function function = (Function) captureCodeBlock(FUNCTION); capture = false; start = cursor + 1; return function; case UNTYPED_VAR: start = cursor + 1; captureToEOT(); int end = cursor; skipWhitespace(); if (expr[cursor] == '=') { if (end == start) throw new CompileException("illegal use of reserved word: var"); cursor = start; continue; } else { String name = new String(subArray(start, end)); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedDeclTypedVarNode(idx, Object.class); } else { return lastNode = new DeclTypedVarNode(name, Object.class, fields); } } } } skipWhitespace(); /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ if (cursor != length && expr[cursor] == '(') { cursor = balancedCapture(expr, cursor, '(') + 1; } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor != length) { switch (expr[cursor]) { case '?': if (lookToLast() == '.') { capture = true; cursor++; continue; } case '+': switch (lookAhead()) { case '+': - if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { + if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, trimLeft(cursor))))) != -1) { lastNode = new IndexedPostFixIncNode(idx); } else { lastNode = new PostFixIncNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = createStringTrimmed(expr, start, cursor - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, ADD, t); } else if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedAssignmentNode(subArray(start, cursor), fields, ADD, name, idx); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, ADD, name); } } break; case '-': switch (lookAhead()) { case '-': - if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { + if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, trimLeft(cursor))))) != -1) { lastNode = new IndexedPostFixDecNode(idx); } else { lastNode = new PostFixDecNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.SUB, fields); } } break; case '*': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.MULT, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.MULT, fields); } } break; case '/': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.DIV, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.DIV, fields); } } break; case ']': case '[': cursor = balancedCapture(expr, cursor, '[') + 1; continue; case '.': union = true; cursor++; skipWhitespaceWithLineAccounting(); continue; case '{': if (union) { char[] prop = subArray(start, cursor - 1); start = cursor; cursor = balancedCapture(expr, cursor, '{') + 1; return lastNode = new WithNode(prop, subArray(start + 1, cursor - 1), fields); } break; case '~': if (lookAhead() == '=') { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case '=': if (lookAhead() == '+') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), ADD, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), ADD, fields); } } else if (lookAhead() == '-') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), SUB, fields); } } if (greedy && lookAhead() != '=') { cursor++; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { TypeDescriptor tDescr = new TypeDescriptor(((String) lastNode.getLiteralValue()).toCharArray(), 0); try { lastNode.setLiteralValue(TypeDescriptor.getClassReference(pCtx, tDescr)); lastNode.discard(); } catch (Exception e) { // fall through; } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Class) lastNode.getLiteralValue()); } throw new CompileException("unknown class or illegal statement: " + lastNode.getLiteralValue(), expr, cursor); } else if (pCtx != null && ((idx = pCtx.variableIndexOf(t)) != -1 || (pCtx.isIndexAllocation()))) { IndexedAssignmentNode ian = new IndexedAssignmentNode(subArray(start, cursor), ASTNode.ASSIGN, idx); if (idx == -1) { pCtx.addIndexedVariable(t = ian.getAssignmentVar()); ian.setRegister(idx = pCtx.variableIndexOf(t)); } return lastNode = ian; } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else { String name; switch (expr[cursor]) { case '@': { start++; captureToEOT(); if (pCtx.getInterceptors() == null || !pCtx.getInterceptors(). containsKey(name = new String(expr, start, cursor - start))) { throw new CompileException("reference to undefined interceptor: " + new String(expr, start, cursor - start), expr, cursor); } return lastNode = new InterceptorWrapper(pCtx.getInterceptors().get(name), nextToken()); } case '=': return createOperator(expr, start, (cursor += 2)); case '-': if (lookAhead() == '-') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixDecNode(idx); } else { return lastNode = new PreFixDecNode(name); } } else if ((cursor != 0 && !isWhitespace(lookBehind())) || !PropertyTools.isDigit(lookAhead())) { return createOperator(expr, start, cursor++ + 1); } else if ((cursor - 1) != 0 || (!PropertyTools.isDigit(lookBehind())) && PropertyTools.isDigit(lookAhead())) { cursor++; break; } case '+': if (lookAhead() == '+') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixIncNode(idx); } else { return lastNode = new PreFixIncNode(name); } } return createOperator(expr, start, cursor++ + 1); case '*': if (lookAhead() == '*') { cursor++; } return createOperator(expr, start, cursor++ + 1); case ';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case '#': case '/': switch (skipCommentBlock()) { case OP_TERMINATE: return null; case OP_RESET_FRAME: continue; } case '?': case ':': case '^': case '%': { return createOperator(expr, start, cursor++ + 1); } case '(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor != length && brace != 0; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': brace--; break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; case 'i': if (lookAhead() == 'n' && isWhitespace(lookAhead(2)) && !isIdentifierPart(lookBehind())) { fields |= ASTNode.FOLD; for (int level = brace; cursor != length; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': if (--brace != level) { if (lookAhead() == '.') { lastNode = createToken(expr, trimRight(start + 1), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, lastNode); } else { return createToken(expr, trimRight(start + 1), cursor++, ASTNode.FOLD); } } break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS && expr[cursor] != '.') { switch (expr[cursor]) { case '[': case ']': break; default: if (!(isIdentifierPart(expr[cursor]) || expr[cursor] == '.')) { singleToken = false; } } } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace != 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } //todo: support typecast to array types char[] _subset = null; if (singleToken) { int st; TypeDescriptor tDescr = new TypeDescriptor(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st), fields); Class cls; if (tDescr.getClassName() != null) { try { cls = getClassReference(pCtx, tDescr); start = cursor; captureToEOS(); return lastNode = new TypeCast(subset(expr, start, cursor - start), cls, fields); } catch (Exception e) { // fallthrough } } } if (_subset != null) { return handleUnion(handleSubstatement(new Substatement(_subset, fields))); } else { return handleUnion(handleSubstatement(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields))); } } case '}': case ']': case ')': { throw new ParseException("unbalanced braces", expr, cursor); } case '>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor + 1] == '=') { return createOperator(expr, start, cursor += 2); } else { return createOperator(expr, start, ++cursor); } } case '<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor] == '=') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '\'': case '"': lastNode = new LiteralNode( handleStringEscapes( subset(expr, start + 1, (cursor = captureStringLiteral(expr[cursor], expr, cursor, length)) - start - 1)) , String.class); cursor++; if (tokenContinues()) { return lastNode = handleUnion(lastNode); } return lastNode; case '&': { if (expr[cursor++ + 1] == '&') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '|': { if (expr[cursor++ + 1] == '|') { return new OperatorNode(OPERATORS.get(new String(expr, start, ++cursor - start))); } else { return createOperator(expr, start, cursor); } } case '~': if ((cursor++ - 1 != 0 || !isIdentifierPart(lookBehind())) && PropertyTools.isDigit(expr[cursor])) { start = cursor; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else { if (expr[cursor] == '=') cursor++; return createOperator(expr, start, cursor); } case '!': { ++cursor; if (isNextIdentifier()) { start = cursor; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createOperator(expr, start, ++cursor); } } case '[': case '{': cursor = balancedCapture(expr, cursor, expr[cursor]) + 1; if (tokenContinues()) { lastNode = new InlineCollectionNode(expr, start, start = cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, lastNode); } else { return lastNode = new InlineCollectionNode(expr, start, cursor, fields); } default: cursor++; } } } if (start == cursor) return null; return createPropertyToken(start, cursor); } catch (ArrayIndexOutOfBoundsException e) { CompileException c = new CompileException("unexpected end of statement", expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (CompileException e) { CompileException c = new CompileException(e.getMessage(), expr, cursor, e.getCursor() == 0, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } } public ASTNode handleSubstatement(Substatement stmt) { if (stmt.getStatement() != null && stmt.getStatement().isLiteralOnly()) { return new LiteralNode(stmt.getStatement().getValue(null, null, null)); } else { return stmt; } } protected ASTNode handleUnion(ASTNode node) { if (cursor != length) { skipWhitespace(); if (expr[cursor] == '.') { int union = cursor + 1; captureToEOT(); return lastNode = new Union(expr, union, cursor, fields, node); } else if (expr[cursor] == '[') { captureToEOT(); return lastNode = new Union(expr, cursor, cursor, fields, node); } } return lastNode = node; } /** * Most of this method should be self-explanatory. * * @param expr - * @param start - * @param end - * @param fields - * @return - */ private ASTNode createToken(final char[] expr, final int start, final int end, int fields) { lastWasIdentifier = (lastNode = new ASTNode(expr, start, end, fields)).isIdentifier(); return lastNode; } private ASTNode createOperator(final char[] expr, final int start, final int end) { lastWasIdentifier = false; return lastNode = new OperatorNode(OPERATORS.get(new String(expr, start, end - start))); } private char[] subArray(final int start, final int end) { if (start >= end) return new char[0]; char[] newA = new char[end - start]; for (int i = 0; i != newA.length; i++) { newA[i] = expr[i + start]; } return newA; } //todo: improve performance of this method private ASTNode createPropertyToken(int start, int end) { lastWasIdentifier = true; String tmp; if (parserContext != null && parserContext.get() != null && parserContext.get().hasImports()) { char[] _subset = subset(expr, start, cursor - start); int offset; if ((offset = findFirst('.', _subset)) != -1) { String iStr = new String(_subset, 0, offset); if (pCtx.hasImport(iStr)) { return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, pCtx.getImport(iStr)); } } else { if (pCtx.hasImport(tmp = new String(_subset))) { Object i = pCtx.getStaticOrClassImport(tmp); if (i instanceof Class) { return lastNode = new LiteralNode(i, Class.class); } } lastWasIdentifier = true; } } if ((fields & ASTNode.METHOD) != 0) { return lastNode = new ASTNode(expr, start, end, fields); } else if (LITERALS.containsKey(tmp = new String(expr, start, end - start))) { return lastNode = new LiteralNode(LITERALS.get(tmp)); } else if (OPERATORS.containsKey(tmp)) { return lastNode = new OperatorNode(OPERATORS.get(tmp)); } return lastNode = new ASTNode(expr, start, end, fields); } private ASTNode createBlockToken(final int condStart, final int condEnd, final int blockStart, final int blockEnd, int type) { lastWasIdentifier = false; cursor++; if (isStatementNotManuallyTerminated()) { splitAccumulator.add(new EndOfStatement()); } switch (type) { case ASTNode.BLOCK_IF: return new IfNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); case ASTNode.BLOCK_FOREACH: return new ForEachNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); case ASTNode.BLOCK_FOR: return new ForNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd)); case ASTNode.BLOCK_WHILE: return new WhileNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd)); case ASTNode.BLOCK_UNTIL: return new UntilNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd)); case ASTNode.BLOCK_DO: return new DoNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd)); case ASTNode.BLOCK_DO_UNTIL: return new DoUntilNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd)); default: return new WithNode(subArray(condStart, condEnd), subArray(blockStart, blockEnd), fields); } } private ASTNode captureCodeBlock(int type) { boolean cond = true; ASTNode first = null; ASTNode tk = null; switch (type) { case ASTNode.BLOCK_IF: { do { if (tk != null) { captureToNextTokenJunction(); skipWhitespace(); cond = expr[cursor] != '{' && expr[cursor] == 'i' && expr[++cursor] == 'f' && (isWhitespace(expr[++cursor]) || expr[cursor] == '('); } if (((IfNode) (tk = _captureBlock(tk, expr, cond, type))).getElseBlock() != null) { cursor++; return first; } if (first == null) first = tk; if (cursor != length && expr[cursor] != ';') { cursor++; } } while (ifThenElseBlockContinues()); return first; } case ASTNode.BLOCK_DO: skipWhitespaceWithLineAccounting(); return _captureBlock(null, expr, false, type); default: // either BLOCK_WITH or BLOCK_FOREACH captureToNextTokenJunction(); skipWhitespaceWithLineAccounting(); return _captureBlock(null, expr, true, type); } } private ASTNode _captureBlock(ASTNode node, final char[] expr, boolean cond, int type) { skipWhitespace(); int startCond = 0; int endCond = 0; int blockStart; int blockEnd; String name; /** * Functions are a special case we handle differently from the rest of block parsing */ if (type == FUNCTION) { int start = cursor; captureToNextTokenJunction(); if (cursor == length) { throw new CompileException("unexpected end of statement", expr, start); } /** * Grabe the function name. */ name = createStringTrimmed(expr, start, (startCond = cursor) - start); /** * Check to see if the name is legal. */ if (isReservedWord(name) || isNotValidNameorLabel(name)) throw new CompileException("illegal function name or use of reserved word", expr, cursor); if (expr[cursor] == '(') { /** * If we discover an opening bracket after the function name, we check to see * if this function accepts parameters. */ endCond = cursor = balancedCapture(expr, startCond = cursor, '('); startCond++; cursor++; skipWhitespace(); if (cursor >= length) { throw new CompileException("incomplete statement", expr, cursor); } else if (expr[cursor] == '{') { // blockStart = cursor; blockEnd = cursor = balancedCapture(expr, blockStart = cursor, '{'); } else { blockStart = cursor - 1; captureToEOS(); blockEnd = cursor; } } else { /** * This function has not parameters. */ if (expr[cursor] == '{') { /** * This function is bracketed. We capture the entire range in the brackets. */ blockStart = cursor; blockEnd = cursor = balancedCapture(expr, cursor, '{'); } else { /** * This is a single statement function declaration. We only capture the statement. */ blockStart = cursor - 1; captureToEOS(); blockEnd = cursor; } } /** * Trim any whitespace from the captured block range. */ blockStart = trimRight(blockStart + 1); blockEnd = trimLeft(blockEnd); cursor++; /** * Check if the function is manually terminated. */ if (isStatementNotManuallyTerminated()) { /** * Add an EndOfStatement to the split accumulator in the parser. */ splitAccumulator.add(new EndOfStatement()); } /** * Produce the funciton node. */ return new Function(name, subArray(startCond, endCond), subArray(blockStart, blockEnd)); } else if (cond) { if (expr[cursor] != '(') { throw new CompileException("expected '(' but encountered: " + expr[cursor]); } /** * This block is an: IF, FOREACH or WHILE node. */ int[] cap = balancedCaptureWithLineAccounting(expr, startCond = cursor, '('); endCond = cursor = cap[0]; startCond++; cursor++; pCtx.incrementLineCount(cap[1]); } skipWhitespace(); if (cursor >= length) { throw new CompileException("unbalanced braces", expr, cursor); } else if (expr[cursor] == '{') { blockStart = cursor; int[] cap = balancedCaptureWithLineAccounting(expr, cursor, '{'); blockEnd = cursor = cap[0]; pCtx.incrementLineCount(cap[1]); } else { blockStart = cursor - 1; captureToEOSorEOL(); blockEnd = cursor + 1; } if (type == ASTNode.BLOCK_IF) { IfNode ifNode = (IfNode) node; if (node != null) { if (!cond) { return ifNode.setElseBlock(subArray(trimRight(blockStart + 1), trimLeft(blockEnd - 1))); } else { return ifNode.setElseIf((IfNode) createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type)); } } else { return createBlockToken(startCond, endCond, blockStart + 1, blockEnd, type); } } else if (type == ASTNode.BLOCK_DO) { cursor++; skipWhitespaceWithLineAccounting(); start = cursor; captureToNextTokenJunction(); if ("while".equals(name = new String(expr, start, cursor - start))) { skipWhitespaceWithLineAccounting(); startCond = cursor + 1; int[] cap = balancedCaptureWithLineAccounting(expr, cursor, '('); endCond = cursor = cap[0]; pCtx.incrementLineCount(cap[1]); return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type); } else if ("until".equals(name)) { skipWhitespaceWithLineAccounting(); startCond = cursor + 1; int[] cap = balancedCaptureWithLineAccounting(expr, cursor, '('); endCond = cursor = cap[0]; pCtx.incrementLineCount(cap[1]); return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), ASTNode.BLOCK_DO_UNTIL); } else { throw new CompileException("expected 'while' or 'until' but encountered: " + name, expr, cursor); } } // DON"T REMOVE THIS COMMENT! // else if (isFlag(ASTNode.BLOCK_FOREACH) || isFlag(ASTNode.BLOCK_WITH)) { else { return createBlockToken(startCond, endCond, trimRight(blockStart + 1), trimLeft(blockEnd), type); } } /** * Checking from the current cursor position, check to see if the if-then-else block continues. * * @return boolean value */ protected boolean ifThenElseBlockContinues() { if ((cursor + 4) < length) { if (expr[cursor] != ';') cursor--; skipWhitespaceWithLineAccounting(); skipCommentBlock(); return expr[cursor] == 'e' && expr[cursor + 1] == 'l' && expr[cursor + 2] == 's' && expr[cursor + 3] == 'e' && (isWhitespace(expr[cursor + 4]) || expr[cursor + 4] == '{'); } return false; } protected int skipCommentBlock() { if (lookAhead() == expr[cursor]) { /** * Handle single line comments. */ captureToEOL(); line = pCtx.getLineCount(); skipWhitespaceWithLineAccounting(); if (lastNode instanceof LineLabel) { pCtx.getLastLineLabel().setLineNumber(line); pCtx.addKnownLine(line); } lastWasComment = true; pCtx.setLineCount(line); if ((start = cursor) >= length) return OP_TERMINATE; return OP_RESET_FRAME; } else if (expr[cursor] == '/' && lookAhead() == '*') { /** * Handle multi-line comments. */ int len = length - 1; /** * This probably seems highly redundant, but sub-compilations within the same * source will spawn a new compiler, and we need to sync this with the * parser context; */ line = pCtx.getLineCount(); while (true) { cursor++; /** * Since multi-line comments may cross lines, we must keep track of any line-break * we encounter. */ skipWhitespaceWithLineAccounting(); if (cursor == len) { throw new CompileException("unterminated block comment", expr, cursor); } if (expr[cursor] == '*' && lookAhead() == '/') { if ((cursor += 2) >= length) return OP_RESET_FRAME; skipWhitespaceWithLineAccounting(); start = cursor; break; } } pCtx.setLineCount(line); if (lastNode instanceof LineLabel) { pCtx.getLastLineLabel().setLineNumber(line); pCtx.addKnownLine(line); } lastWasComment = true; return OP_RESET_FRAME; } return OP_CONTINUE; } /** * Checking from the current cursor position, check to see if we're inside a contiguous identifier. * * @return */ protected boolean tokenContinues() { if (cursor >= length) return false; else if (expr[cursor] == '.' || expr[cursor] == '[') return true; else if (isWhitespace(expr[cursor])) { int markCurrent = cursor; skipWhitespace(); if (cursor != length && (expr[cursor] == '.' || expr[cursor] == '[')) return true; cursor = markCurrent; } return false; } protected void expectEOS() { skipWhitespace(); if (cursor != length && expr[cursor] != ';') { switch (expr[cursor]) { case '&': if (lookAhead() == '&') return; else break; case '|': if (lookAhead() == '|') return; else break; case '!': if (lookAhead() == '=') return; else break; case '<': case '>': return; case '=': { switch (lookAhead()) { case '=': case '+': case '-': case '*': return; } break; } case '+': case '-': case '/': case '*': if (lookAhead() == '=') return; else break; } throw new CompileException("expected end of statement but encountered: " + (cursor == length ? "<end of stream>" : expr[cursor]), expr, cursor); } } protected boolean isNextIdentifier() { while (cursor != length && isWhitespace(expr[cursor])) cursor++; return cursor != length && isIdentifierPart(expr[cursor]); } /** * Capture from the current cursor position, to the end of the statement. */ protected void captureToEOS() { while (cursor != length) { switch (expr[cursor]) { case '(': case '[': case '{': cursor = balancedCapture(expr, cursor, expr[cursor]); break; case ';': case '}': return; } cursor++; } } /** * From the current cursor position, capture to the end of statement, or the end of line, whichever comes first. */ protected void captureToEOSorEOL() { while (cursor != length && (expr[cursor] != '\n' && expr[cursor] != '\r' && expr[cursor] != ';')) { cursor++; } } /** * From the current cursor position, capture to the end of the line. */ protected void captureToEOL() { while (cursor != length && (expr[cursor] != '\n')) cursor++; } protected void captureIdentifier() { if (cursor == length) throw new CompileException("unexpected end of statement: EOF", expr, cursor); while (cursor != length) { switch (expr[cursor]) { case ';': return; default: { if (!isIdentifierPart(expr[cursor])) { throw new CompileException("unexpected symbol (was expecting an identifier): " + expr[cursor], expr, cursor); } } } cursor++; } } /** * From the current cursor position, capture to the end of the current token. */ protected void captureToEOT() { skipWhitespace(); do { switch (expr[cursor]) { case '(': case '[': case '{': if ((cursor = balancedCapture(expr, cursor, expr[cursor])) == -1) { throw new CompileException("unbalanced braces", expr, cursor); } break; case '=': case '&': case '|': case ';': return; case '.': skipWhitespace(); break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; default: if (isWhitespace(expr[cursor])) { skipWhitespace(); if (expr[cursor] == '.') { if (cursor != length) cursor++; skipWhitespace(); break; } else { trimWhitespace(); return; } } } } while (++cursor != length); } /** * From the specified cursor position, trim out any whitespace between the current position and the end of the * last non-whitespace character. * * @param pos - current position * @return new position. */ protected int trimLeft(int pos) { while (pos != 0 && isWhitespace(expr[pos - 1])) pos--; return pos; } /** * From the specified cursor position, trim out any whitespace between the current position and beginning of the * first non-whitespace character. * * @param pos * @return */ protected int trimRight(int pos) { while (pos != length && isWhitespace(expr[pos])) pos++; return pos; } /** * If the cursor is currently pointing to whitespace, move the cursor forward to the first non-whitespace * character. */ protected void skipWhitespace() { while (cursor != length && isWhitespace(expr[cursor])) cursor++; } /** * If the cursor is currently pointing to whitespace, move the cursor forward to the first non-whitespace * character, but account for carraige returns in the script (updates parser field: line). */ protected void skipWhitespaceWithLineAccounting() { while (cursor != length && isWhitespace(expr[cursor])) { switch (expr[cursor]) { case '\n': line++; lastLineStart = cursor; case '\r': cursor++; continue; } cursor++; } } /** * From the current cursor position, capture to the end of the next token junction. */ protected void captureToNextTokenJunction() { while (cursor != length) { switch (expr[cursor]) { case '{': case '(': return; default: if (isWhitespace(expr[cursor])) return; cursor++; } } } /** * From the current cursor position, trim backward over any whitespace to the first non-whitespace character. */ protected void trimWhitespace() { while (cursor != 0 && isWhitespace(expr[cursor - 1])) cursor--; } /** * Check if the specified string is a reserved word in the parser. * * @param name * @return */ public static boolean isReservedWord(String name) { return LITERALS.containsKey(name) || OPERATORS.containsKey(name); } /** * Check if the specfied string represents a valid name of label. * * @param name * @return */ public static boolean isNotValidNameorLabel(String name) { for (char c : name.toCharArray()) { if (c == '.') return true; else if (!isIdentifierPart(c)) return true; } return false; } protected void setExpression(String expression) { if (expression != null && !"".equals(expression)) { if ((this.expr = EX_PRECACHE.get(expression)) == null) { length = (this.expr = expression.toCharArray()).length; // trim any whitespace. while (length != 0 && isWhitespace(this.expr[length - 1])) length--; char[] e = new char[length]; //arraycopy(this.expr, 0, e, 0, length); for (int i = 0; i != e.length; i++) e[i] = expr[i]; EX_PRECACHE.put(expression, e); } else { length = this.expr.length; } } } protected void setExpression(char[] expression) { length = (this.expr = expression).length; while (length != 0 && isWhitespace(this.expr[length - 1])) length--; } /** * Return the previous non-whitespace character. * * @return */ protected char lookToLast() { if (cursor == 0) return 0; int temp = cursor; while (temp != 0 && isWhitespace(expr[--temp])) ; return expr[temp]; } /** * Return the last character (delta -1 of cursor position). * * @return */ protected char lookBehind() { if (cursor == 0) return 0; return expr[cursor - 1]; } /** * Return the next character (delta 1 of cursor position). * * @return */ protected char lookAhead() { int tmp = cursor + 1; if (tmp != length) return expr[tmp]; return 0; } /** * Return the character, forward of the currrent cursor position based on the specified range delta. * * @param range * @return */ protected char lookAhead(int range) { if ((cursor + range) >= length) return 0; else { return expr[cursor + range]; } } protected boolean isNextIdentifierOrLiteral() { int tmp = cursor; if (tmp == length) return false; else { while (tmp != length && isWhitespace(expr[tmp])) tmp++; if (tmp == length) return false; char n = expr[tmp]; return isIdentifierPart(n) || isDigit(n) || n == '\'' || n == '"'; } } public int nextNonBlank() { if ((cursor + 1) >= length) { return -1; } int i = cursor; while (i != length && isWhitespace(expr[i])) i++; return i; } /** * NOTE: This method assumes that the current position of the cursor is at the end of a logical statement, to * begin with. * <p/> * Determines whether or not the logical statement is manually terminated with a statement separator (';'). * * @return */ protected boolean isStatementNotManuallyTerminated() { if (cursor >= length) return false; int c = cursor; while (c != length && isWhitespace(expr[c])) c++; return !(c != length && expr[c] == ';'); } protected ParserContext getParserContext() { if (parserContext == null || parserContext.get() == null) { newContext(); } return parserContext.get(); } public static ParserContext getCurrentThreadParserContext() { return contextControl(GET_OR_CREATE, null, null); } public static void setCurrentThreadParserContext(ParserContext pCtx) { contextControl(SET, pCtx, null); } /** * Create a new ParserContext in the current thread. */ protected void newContext() { contextControl(SET, new ParserContext(), this); } /** * Create a new ParserContext in the current thread, using the one specified. * * @param pCtx */ protected void newContext(ParserContext pCtx) { contextControl(SET, pCtx, this); } /** * Remove the current ParserContext from the thread. */ protected void removeContext() { contextControl(REMOVE, null, this); } protected static ParserContext contextControl(int operation, ParserContext pCtx, AbstractParser parser) { synchronized (getRuntime()) { if (parserContext == null) parserContext = new ThreadLocal<ParserContext>(); switch (operation) { case SET: pCtx.setRootParser(parser); parserContext.set(pCtx); return pCtx; case REMOVE: parserContext.set(null); return null; case GET_OR_CREATE: if (parserContext.get() == null) { parserContext.set(new ParserContext(parser)); } case GET: return parserContext.get(); } } return null; } protected static final int SET = 0; protected static final int REMOVE = 1; protected static final int GET = 2; protected static final int GET_OR_CREATE = 3; public boolean isDebugSymbols() { return debugSymbols; } public void setDebugSymbols(boolean debugSymbols) { this.debugSymbols = debugSymbols; } protected static String getCurrentSourceFileName() { if (parserContext != null && parserContext.get() != null) { return parserContext.get().getSourceFile(); } return null; } protected void addFatalError(String message) { getParserContext().addError(new ErrorDetail(getParserContext().getLineCount(), cursor - getParserContext().getLineOffset(), true, message)); } protected void addFatalError(String message, int row, int cols) { getParserContext().addError(new ErrorDetail(row, cols, true, message)); } protected void addWarning(String message) { getParserContext().addError(new ErrorDetail(message, false)); } public static final int LEVEL_5_CONTROL_FLOW = 5; public static final int LEVEL_4_ASSIGNMENT = 4; public static final int LEVEL_3_ITERATION = 3; public static final int LEVEL_2_MULTI_STATEMENT = 2; public static final int LEVEL_1_BASIC_LANG = 1; public static final int LEVEL_0_PROPERTY_ONLY = 0; public static void setLanguageLevel(int level) { OPERATORS.clear(); OPERATORS.putAll(loadLanguageFeaturesByLevel(level)); } public static Map<String, Integer> loadLanguageFeaturesByLevel(int languageLevel) { Map<String, Integer> operatorsTable = new HashMap<String, Integer>(); switch (languageLevel) { case 5: // control flow operations operatorsTable.put("if", IF); operatorsTable.put("else", ELSE); operatorsTable.put("?", TERNARY); operatorsTable.put("switch", SWITCH); operatorsTable.put("function", FUNCTION); operatorsTable.put("def", FUNCTION); operatorsTable.put("isdef", ISDEF); case 4: // assignment operatorsTable.put("=", ASSIGN); operatorsTable.put("var", UNTYPED_VAR); operatorsTable.put("+=", ASSIGN_ADD); operatorsTable.put("-=", ASSIGN_SUB); case 3: // iteration operatorsTable.put("foreach", FOREACH); operatorsTable.put("while", WHILE); operatorsTable.put("until", UNTIL); operatorsTable.put("for", FOR); operatorsTable.put("do", DO); case 2: // multi-statement operatorsTable.put("return", RETURN); operatorsTable.put(";", END_OF_STMT); case 1: // boolean, math ops, projection, assertion, objection creation, block setters, imports operatorsTable.put("+", ADD); operatorsTable.put("-", SUB); operatorsTable.put("*", MULT); operatorsTable.put("**", POWER); operatorsTable.put("/", DIV); operatorsTable.put("%", MOD); operatorsTable.put("==", EQUAL); operatorsTable.put("!=", NEQUAL); operatorsTable.put(">", GTHAN); operatorsTable.put(">=", GETHAN); operatorsTable.put("<", LTHAN); operatorsTable.put("<=", LETHAN); operatorsTable.put("&&", AND); operatorsTable.put("and", AND); operatorsTable.put("||", OR); operatorsTable.put("or", CHOR); operatorsTable.put("~=", REGEX); operatorsTable.put("instanceof", INSTANCEOF); operatorsTable.put("is", INSTANCEOF); operatorsTable.put("contains", CONTAINS); operatorsTable.put("soundslike", SOUNDEX); operatorsTable.put("strsim", SIMILARITY); operatorsTable.put("convertable_to", CONVERTABLE_TO); operatorsTable.put("#", STR_APPEND); operatorsTable.put("&", BW_AND); operatorsTable.put("|", BW_OR); operatorsTable.put("^", BW_XOR); operatorsTable.put("<<", BW_SHIFT_LEFT); operatorsTable.put("<<<", BW_USHIFT_LEFT); operatorsTable.put(">>", BW_SHIFT_RIGHT); operatorsTable.put(">>>", BW_USHIFT_RIGHT); operatorsTable.put("new", Operator.NEW); operatorsTable.put("in", PROJECTION); operatorsTable.put("with", WITH); operatorsTable.put("assert", ASSERT); operatorsTable.put("import", IMPORT); operatorsTable.put("import_static", IMPORT_STATIC); operatorsTable.put("++", INC); operatorsTable.put("--", DEC); case 0: // Property access and inline collections operatorsTable.put(":", TERNARY_ELSE); } return operatorsTable; } /** * Remove the current parser context from the thread. */ public static void resetParserContext() { contextControl(REMOVE, null, null); } protected static boolean isArithmeticOperator(int operator) { return operator < 6; } protected int arithmeticFunctionReduction(int operator) { ASTNode tk; int operator2; boolean x = false; int y = 0; /** * If the next token is an operator, we check to see if it has a higher * precdence. */ if ((tk = nextToken()) != null && tk.isOperator()) { if (isArithmeticOperator(operator2 = tk.getOperator()) && PTABLE[operator2] > PTABLE[operator]) { xswap(); /** * The current arith. operator is of higher precedence the last. */ dStack.push(operator = operator2, nextToken().getReducedValue(ctx, ctx, variableFactory)); while (true) { // look ahead again if ((tk = nextToken()) != null && PTABLE[operator2 = tk.getOperator()] > PTABLE[operator]) { // if we have back to back operations on the stack, we don't xswap if (x) { xswap(); } /** * This operator is of higher precedence, or the same level precedence. push to the RHS. */ dStack.push(operator = operator2, nextToken().getReducedValue(ctx, ctx, variableFactory)); y = 1; continue; } else if (tk != null) { if (PTABLE[operator2] == PTABLE[operator]) { // if we have back to back operations on the stack, we don't xswap if (x) { xswap(); } /** * Reduce any operations waiting now. */ while (!dStack.isEmpty()) { dreduce(); } /** * This operator is of the same level precedence. push to the RHS. */ dStack.push(operator = operator2, nextToken().getReducedValue(ctx, ctx, variableFactory)); y++; continue; } else { /** * The operator doesn't have higher precedence. Therfore reduce the LHS. */ if (!dStack.isEmpty()) { do { if (y == 1) { dreduce2(); y = 0; } else { dreduce(); } } while (dStack.size() > 1); } if (!dStack.isEmpty()) { stk.push(dStack.pop()); xswap(); } operator = tk.getOperator(); // Reduce the lesser or equal precedence operations. while (stk.size() != 1 && PTABLE[((Integer) stk.peek2())] >= PTABLE[operator]) { xswap(); reduce(); } y = 0; } } else { /** * There are no more tokens. */ x = false; if (dStack.size() > 1) { do { if (y == 1) { dreduce2(); y = 0; } else { dreduce(); } } while (dStack.size() > 1); x = true; } if (!dStack.isEmpty()) { stk.push(dStack.pop()); } else if (x) { xswap(); } y = 0; break; } if (tk != null && (tk = nextToken()) != null) { switch (operator) { case AND: { if (!((Boolean) stk.peek())) return OP_TERMINATE; else { splitAccumulator.add(tk); return AND; } } case OR: { if (((Boolean) stk.peek())) return OP_TERMINATE; else { splitAccumulator.add(tk); return OR; } } default: stk.push(tk.getReducedValue(ctx, ctx, variableFactory), operator); } } x = true; y = 0; } } else { reduce(); splitAccumulator.push(tk); } } // while any values remain on the stack // keep XSWAPing and reducing, until there is nothing left. while (stk.size() > 1) { reduce(); if (stk.size() > 1) xswap(); } return OP_RESET_FRAME; } private void dreduce() { stk.push(dStack.pop(), dStack.pop()); // reduce the top of the stack reduce(); } private void dreduce2() { Object o1, o2; o1 = dStack.pop(); o2 = dStack.pop(); if (!dStack.isEmpty()) stk.push(dStack.pop()); stk.push(o1); stk.push(o2); reduce(); } /** * XSWAP. */ private void xswap() { stk.push(stk.pop(), stk.pop()); } /** * This method is called when we reach the point where we must subEval a trinary operation in the expression. * (ie. val1 op val2). This is not the same as a binary operation, although binary operations would appear * to have 3 structures as well. A binary structure (or also a junction in the expression) compares the * current state against 2 downrange structures (usually an op and a val). */ protected void reduce() { Object v1, v2; int operator; try { switch (operator = (Integer) stk.pop()) { case ADD: case SUB: case DIV: case MULT: case MOD: case EQUAL: case NEQUAL: case GTHAN: case LTHAN: case GETHAN: case LETHAN: case POWER: v1 = stk.pop(); stk.push(doOperations(stk.pop(), operator, v1)); break; case AND: v1 = stk.pop(); stk.push(((Boolean) stk.pop()) && ((Boolean) v1)); break; case OR: v1 = stk.pop(); stk.push(((Boolean) stk.pop()) || ((Boolean) v1)); break; case CHOR: v1 = stk.pop(); if (!isEmpty(v2 = stk.pop()) || !isEmpty(v1)) { stk.clear(); stk.push(!isEmpty(v2) ? v2 : v1); return; } else stk.push(null); break; case REGEX: stk.push(java.util.regex.Pattern.compile(java.lang.String.valueOf(stk.pop())).matcher(java.lang.String.valueOf(stk.pop())).matches()); break; case INSTANCEOF: if ((v1 = stk.pop()) instanceof Class) stk.push(((Class) v1).isInstance(stk.pop())); else stk.push(currentThread().getContextClassLoader().loadClass(java.lang.String.valueOf(v1)).isInstance(stk.pop())); break; case CONVERTABLE_TO: if ((v1 = stk.pop()) instanceof Class) stk.push(org.mvel.DataConversion.canConvert(stk.pop().getClass(), (Class) v1)); else stk.push(org.mvel.DataConversion.canConvert(stk.pop().getClass(), currentThread().getContextClassLoader().loadClass(java.lang.String.valueOf(v1)))); break; case CONTAINS: v1 = stk.pop(); stk.push(containsCheck(stk.pop(), v1)); break; case BW_AND: v1 = stk.pop(); stk.push(asInt(stk.pop()) & asInt(v1)); break; case BW_OR: v1 = stk.pop(); stk.push(asInt(stk.pop()) | asInt(v1)); break; case BW_XOR: v1 = stk.pop(); stk.push(asInt(stk.pop()) ^ asInt(v1)); break; case BW_SHIFT_LEFT: v1 = stk.pop(); stk.push(asInt(stk.pop()) << asInt(v1)); break; case BW_USHIFT_LEFT: v1 = stk.pop(); int iv2 = asInt(stk.pop()); if (iv2 < 0) iv2 *= -1; stk.push(iv2 << asInt(v1)); break; case BW_SHIFT_RIGHT: v1 = stk.pop(); stk.push(asInt(stk.pop()) >> asInt(v1)); break; case BW_USHIFT_RIGHT: v1 = stk.pop(); stk.push(asInt(stk.pop()) >>> asInt(v1)); break; case STR_APPEND: v1 = stk.pop(); stk.push(new StringAppender(java.lang.String.valueOf(stk.pop())).append(java.lang.String.valueOf(v1)).toString()); break; case SOUNDEX: stk.push(Soundex.soundex(java.lang.String.valueOf(stk.pop())).equals(Soundex.soundex(java.lang.String.valueOf(stk.pop())))); break; case SIMILARITY: stk.push(similarity(java.lang.String.valueOf(stk.pop()), java.lang.String.valueOf(stk.pop()))); break; } } catch (ClassCastException e) { throw new CompileException("syntax error or incompatable types", expr, cursor, e); } catch (Exception e) { throw new CompileException("failed to subEval expression", e); } } private static int asInt(final Object o) { return (Integer) o; } }
false
true
protected ASTNode nextToken() { try { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, idx; start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ boolean capture = false, union = false; pCtx = getParserContext(); if (debugSymbols) { if (!lastWasLineLabel) { if (pCtx.getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } line = pCtx.getLineCount(); skipWhitespaceWithLineAccounting(); if (!pCtx.isKnownLine(pCtx.getSourceFile(), pCtx.setLineCount(line)) && !pCtx.isBlockSymbols()) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); return lastNode = pCtx.setLastLineLabel(new LineLabel(pCtx.getSourceFile(), line)); } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start != length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor != length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor = trimRight(cursor); captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: return captureCodeBlock(ASTNode.BLOCK_IF); case ELSE: throw new CompileException("else without if", cursor); case FOREACH: return captureCodeBlock(ASTNode.BLOCK_FOREACH); case WHILE: return captureCodeBlock(ASTNode.BLOCK_WHILE); case UNTIL: return captureCodeBlock(ASTNode.BLOCK_UNTIL); case FOR: return captureCodeBlock(ASTNode.BLOCK_FOR); case WITH: return captureCodeBlock(ASTNode.BLOCK_WITH); case DO: return captureCodeBlock(ASTNode.BLOCK_DO); case ISDEF: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new IsDef(subArray(start, cursor)); case IMPORT: start = cursor = trimRight(cursor); captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--)); if (importNode.isPackageImport()) { pCtx.addPackageImport(importNode.getPackageImport()); cursor++; } else { pCtx.addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); } return importNode; case IMPORT_STATIC: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--)); case FUNCTION: Function function = (Function) captureCodeBlock(FUNCTION); capture = false; start = cursor + 1; return function; case UNTYPED_VAR: start = cursor + 1; captureToEOT(); int end = cursor; skipWhitespace(); if (expr[cursor] == '=') { if (end == start) throw new CompileException("illegal use of reserved word: var"); cursor = start; continue; } else { String name = new String(subArray(start, end)); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedDeclTypedVarNode(idx, Object.class); } else { return lastNode = new DeclTypedVarNode(name, Object.class, fields); } } } } skipWhitespace(); /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ if (cursor != length && expr[cursor] == '(') { cursor = balancedCapture(expr, cursor, '(') + 1; } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor != length) { switch (expr[cursor]) { case '?': if (lookToLast() == '.') { capture = true; cursor++; continue; } case '+': switch (lookAhead()) { case '+': if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { lastNode = new IndexedPostFixIncNode(idx); } else { lastNode = new PostFixIncNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = createStringTrimmed(expr, start, cursor - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, ADD, t); } else if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedAssignmentNode(subArray(start, cursor), fields, ADD, name, idx); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, ADD, name); } } break; case '-': switch (lookAhead()) { case '-': if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { lastNode = new IndexedPostFixDecNode(idx); } else { lastNode = new PostFixDecNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.SUB, fields); } } break; case '*': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.MULT, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.MULT, fields); } } break; case '/': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.DIV, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.DIV, fields); } } break; case ']': case '[': cursor = balancedCapture(expr, cursor, '[') + 1; continue; case '.': union = true; cursor++; skipWhitespaceWithLineAccounting(); continue; case '{': if (union) { char[] prop = subArray(start, cursor - 1); start = cursor; cursor = balancedCapture(expr, cursor, '{') + 1; return lastNode = new WithNode(prop, subArray(start + 1, cursor - 1), fields); } break; case '~': if (lookAhead() == '=') { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case '=': if (lookAhead() == '+') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), ADD, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), ADD, fields); } } else if (lookAhead() == '-') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), SUB, fields); } } if (greedy && lookAhead() != '=') { cursor++; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { TypeDescriptor tDescr = new TypeDescriptor(((String) lastNode.getLiteralValue()).toCharArray(), 0); try { lastNode.setLiteralValue(TypeDescriptor.getClassReference(pCtx, tDescr)); lastNode.discard(); } catch (Exception e) { // fall through; } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Class) lastNode.getLiteralValue()); } throw new CompileException("unknown class or illegal statement: " + lastNode.getLiteralValue(), expr, cursor); } else if (pCtx != null && ((idx = pCtx.variableIndexOf(t)) != -1 || (pCtx.isIndexAllocation()))) { IndexedAssignmentNode ian = new IndexedAssignmentNode(subArray(start, cursor), ASTNode.ASSIGN, idx); if (idx == -1) { pCtx.addIndexedVariable(t = ian.getAssignmentVar()); ian.setRegister(idx = pCtx.variableIndexOf(t)); } return lastNode = ian; } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else { String name; switch (expr[cursor]) { case '@': { start++; captureToEOT(); if (pCtx.getInterceptors() == null || !pCtx.getInterceptors(). containsKey(name = new String(expr, start, cursor - start))) { throw new CompileException("reference to undefined interceptor: " + new String(expr, start, cursor - start), expr, cursor); } return lastNode = new InterceptorWrapper(pCtx.getInterceptors().get(name), nextToken()); } case '=': return createOperator(expr, start, (cursor += 2)); case '-': if (lookAhead() == '-') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixDecNode(idx); } else { return lastNode = new PreFixDecNode(name); } } else if ((cursor != 0 && !isWhitespace(lookBehind())) || !PropertyTools.isDigit(lookAhead())) { return createOperator(expr, start, cursor++ + 1); } else if ((cursor - 1) != 0 || (!PropertyTools.isDigit(lookBehind())) && PropertyTools.isDigit(lookAhead())) { cursor++; break; } case '+': if (lookAhead() == '+') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixIncNode(idx); } else { return lastNode = new PreFixIncNode(name); } } return createOperator(expr, start, cursor++ + 1); case '*': if (lookAhead() == '*') { cursor++; } return createOperator(expr, start, cursor++ + 1); case ';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case '#': case '/': switch (skipCommentBlock()) { case OP_TERMINATE: return null; case OP_RESET_FRAME: continue; } case '?': case ':': case '^': case '%': { return createOperator(expr, start, cursor++ + 1); } case '(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor != length && brace != 0; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': brace--; break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; case 'i': if (lookAhead() == 'n' && isWhitespace(lookAhead(2)) && !isIdentifierPart(lookBehind())) { fields |= ASTNode.FOLD; for (int level = brace; cursor != length; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': if (--brace != level) { if (lookAhead() == '.') { lastNode = createToken(expr, trimRight(start + 1), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, lastNode); } else { return createToken(expr, trimRight(start + 1), cursor++, ASTNode.FOLD); } } break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS && expr[cursor] != '.') { switch (expr[cursor]) { case '[': case ']': break; default: if (!(isIdentifierPart(expr[cursor]) || expr[cursor] == '.')) { singleToken = false; } } } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace != 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } //todo: support typecast to array types char[] _subset = null; if (singleToken) { int st; TypeDescriptor tDescr = new TypeDescriptor(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st), fields); Class cls; if (tDescr.getClassName() != null) { try { cls = getClassReference(pCtx, tDescr); start = cursor; captureToEOS(); return lastNode = new TypeCast(subset(expr, start, cursor - start), cls, fields); } catch (Exception e) { // fallthrough } } } if (_subset != null) { return handleUnion(handleSubstatement(new Substatement(_subset, fields))); } else { return handleUnion(handleSubstatement(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields))); } } case '}': case ']': case ')': { throw new ParseException("unbalanced braces", expr, cursor); } case '>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor + 1] == '=') { return createOperator(expr, start, cursor += 2); } else { return createOperator(expr, start, ++cursor); } } case '<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor] == '=') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '\'': case '"': lastNode = new LiteralNode( handleStringEscapes( subset(expr, start + 1, (cursor = captureStringLiteral(expr[cursor], expr, cursor, length)) - start - 1)) , String.class); cursor++; if (tokenContinues()) { return lastNode = handleUnion(lastNode); } return lastNode; case '&': { if (expr[cursor++ + 1] == '&') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '|': { if (expr[cursor++ + 1] == '|') { return new OperatorNode(OPERATORS.get(new String(expr, start, ++cursor - start))); } else { return createOperator(expr, start, cursor); } } case '~': if ((cursor++ - 1 != 0 || !isIdentifierPart(lookBehind())) && PropertyTools.isDigit(expr[cursor])) { start = cursor; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else { if (expr[cursor] == '=') cursor++; return createOperator(expr, start, cursor); } case '!': { ++cursor; if (isNextIdentifier()) { start = cursor; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createOperator(expr, start, ++cursor); } } case '[': case '{': cursor = balancedCapture(expr, cursor, expr[cursor]) + 1; if (tokenContinues()) { lastNode = new InlineCollectionNode(expr, start, start = cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, lastNode); } else { return lastNode = new InlineCollectionNode(expr, start, cursor, fields); } default: cursor++; } } } if (start == cursor) return null; return createPropertyToken(start, cursor); } catch (ArrayIndexOutOfBoundsException e) { CompileException c = new CompileException("unexpected end of statement", expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (CompileException e) { CompileException c = new CompileException(e.getMessage(), expr, cursor, e.getCursor() == 0, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } }
protected ASTNode nextToken() { try { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { return null; } else if (!splitAccumulator.isEmpty()) { return lastNode = (ASTNode) splitAccumulator.pop(); } int brace, idx; start = cursor; /** * Because of parser recursion for sub-expression parsing, we sometimes need to remain * certain field states. We do not reset for assignments, boolean mode, list creation or * a capture only mode. */ boolean capture = false, union = false; pCtx = getParserContext(); if (debugSymbols) { if (!lastWasLineLabel) { if (pCtx.getSourceFile() == null) { throw new CompileException("unable to produce debugging symbols: source name must be provided."); } line = pCtx.getLineCount(); skipWhitespaceWithLineAccounting(); if (!pCtx.isKnownLine(pCtx.getSourceFile(), pCtx.setLineCount(line)) && !pCtx.isBlockSymbols()) { lastWasLineLabel = true; pCtx.setLineAndOffset(line, cursor); return lastNode = pCtx.setLastLineLabel(new LineLabel(pCtx.getSourceFile(), line)); } } else { lastWasComment = lastWasLineLabel = false; } } /** * Skip any whitespace currently under the starting point. */ while (start != length && isWhitespace(expr[start])) start++; /** * From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for * trouble unless you really know what you're doing. */ for (cursor = start; cursor != length;) { if (isIdentifierPart(expr[cursor])) { /** * If the current character under the cursor is a valid * part of an identifier, we keep capturing. */ capture = true; cursor++; } else if (capture) { String t; if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) { switch (OPERATORS.get(t)) { case NEW: start = cursor = trimRight(cursor); captureToEOT(); return lastNode = new NewObjectNode(subArray(start, cursor), fields); case ASSERT: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new AssertNode(subArray(start, cursor--), fields); case RETURN: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new ReturnNode(subArray(start, cursor), fields); case IF: return captureCodeBlock(ASTNode.BLOCK_IF); case ELSE: throw new CompileException("else without if", cursor); case FOREACH: return captureCodeBlock(ASTNode.BLOCK_FOREACH); case WHILE: return captureCodeBlock(ASTNode.BLOCK_WHILE); case UNTIL: return captureCodeBlock(ASTNode.BLOCK_UNTIL); case FOR: return captureCodeBlock(ASTNode.BLOCK_FOR); case WITH: return captureCodeBlock(ASTNode.BLOCK_WITH); case DO: return captureCodeBlock(ASTNode.BLOCK_DO); case ISDEF: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new IsDef(subArray(start, cursor)); case IMPORT: start = cursor = trimRight(cursor); captureToEOS(); ImportNode importNode = new ImportNode(subArray(start, cursor--)); if (importNode.isPackageImport()) { pCtx.addPackageImport(importNode.getPackageImport()); cursor++; } else { pCtx.addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass()); } return importNode; case IMPORT_STATIC: start = cursor = trimRight(cursor); captureToEOS(); return lastNode = new StaticImportNode(subArray(start, cursor--)); case FUNCTION: Function function = (Function) captureCodeBlock(FUNCTION); capture = false; start = cursor + 1; return function; case UNTYPED_VAR: start = cursor + 1; captureToEOT(); int end = cursor; skipWhitespace(); if (expr[cursor] == '=') { if (end == start) throw new CompileException("illegal use of reserved word: var"); cursor = start; continue; } else { String name = new String(subArray(start, end)); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedDeclTypedVarNode(idx, Object.class); } else { return lastNode = new DeclTypedVarNode(name, Object.class, fields); } } } } skipWhitespace(); /** * If we *were* capturing a token, and we just hit a non-identifier * character, we stop and figure out what to do. */ if (cursor != length && expr[cursor] == '(') { cursor = balancedCapture(expr, cursor, '(') + 1; } /** * If we encounter any of the following cases, we are still dealing with * a contiguous token. */ String name; if (cursor != length) { switch (expr[cursor]) { case '?': if (lookToLast() == '.') { capture = true; cursor++; continue; } case '+': switch (lookAhead()) { case '+': if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, trimLeft(cursor))))) != -1) { lastNode = new IndexedPostFixIncNode(idx); } else { lastNode = new PostFixIncNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = createStringTrimmed(expr, start, cursor - start); start = cursor += 2; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields, ADD, t); } else if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedAssignmentNode(subArray(start, cursor), fields, ADD, name, idx); } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields, ADD, name); } } break; case '-': switch (lookAhead()) { case '-': if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, trimLeft(cursor))))) != -1) { lastNode = new IndexedPostFixDecNode(idx); } else { lastNode = new PostFixDecNode(name); } cursor += 2; expectEOS(); return lastNode; case '=': name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.SUB, fields); } } break; case '*': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.MULT, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.MULT, fields); } } break; case '/': if (lookAhead() == '=') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), Operator.DIV, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), Operator.DIV, fields); } } break; case ']': case '[': cursor = balancedCapture(expr, cursor, '[') + 1; continue; case '.': union = true; cursor++; skipWhitespaceWithLineAccounting(); continue; case '{': if (union) { char[] prop = subArray(start, cursor - 1); start = cursor; cursor = balancedCapture(expr, cursor, '{') + 1; return lastNode = new WithNode(prop, subArray(start + 1, cursor - 1), fields); } break; case '~': if (lookAhead() == '=') { char[] stmt = subArray(start, trimLeft(cursor)); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOT(); return lastNode = new RegExMatch(stmt, fields, subArray(start, cursor)); } break; case '=': if (lookAhead() == '+') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), ADD, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), ADD, fields); } } else if (lookAhead() == '-') { name = new String(expr, start, trimLeft(cursor) - start); start = cursor += 2; if (!isNextIdentifierOrLiteral()) { throw new CompileException("unexpected symbol '" + expr[cursor] + "'", expr, cursor); } captureToEOS(); if ((idx = pCtx.variableIndexOf(name)) != -1) { return lastNode = new IndexedOperativeAssign(subArray(start, cursor), SUB, idx, fields); } else { return lastNode = new OperativeAssign(name, subArray(start, cursor), SUB, fields); } } if (greedy && lookAhead() != '=') { cursor++; captureToEOS(); if (union) { return lastNode = new DeepAssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } else if (lastWasIdentifier) { /** * Check for typing information. */ if (lastNode.getLiteralValue() instanceof String) { TypeDescriptor tDescr = new TypeDescriptor(((String) lastNode.getLiteralValue()).toCharArray(), 0); try { lastNode.setLiteralValue(TypeDescriptor.getClassReference(pCtx, tDescr)); lastNode.discard(); } catch (Exception e) { // fall through; } } if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) { lastNode.discard(); captureToEOS(); return new TypedVarNode(subArray(start, cursor), fields | ASTNode.ASSIGN, (Class) lastNode.getLiteralValue()); } throw new CompileException("unknown class or illegal statement: " + lastNode.getLiteralValue(), expr, cursor); } else if (pCtx != null && ((idx = pCtx.variableIndexOf(t)) != -1 || (pCtx.isIndexAllocation()))) { IndexedAssignmentNode ian = new IndexedAssignmentNode(subArray(start, cursor), ASTNode.ASSIGN, idx); if (idx == -1) { pCtx.addIndexedVariable(t = ian.getAssignmentVar()); ian.setRegister(idx = pCtx.variableIndexOf(t)); } return lastNode = ian; } else { return lastNode = new AssignmentNode(subArray(start, cursor), fields | ASTNode.ASSIGN); } } } } /** * Produce the token. */ trimWhitespace(); return createPropertyToken(start, cursor); } else { String name; switch (expr[cursor]) { case '@': { start++; captureToEOT(); if (pCtx.getInterceptors() == null || !pCtx.getInterceptors(). containsKey(name = new String(expr, start, cursor - start))) { throw new CompileException("reference to undefined interceptor: " + new String(expr, start, cursor - start), expr, cursor); } return lastNode = new InterceptorWrapper(pCtx.getInterceptors().get(name), nextToken()); } case '=': return createOperator(expr, start, (cursor += 2)); case '-': if (lookAhead() == '-') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixDecNode(idx); } else { return lastNode = new PreFixDecNode(name); } } else if ((cursor != 0 && !isWhitespace(lookBehind())) || !PropertyTools.isDigit(lookAhead())) { return createOperator(expr, start, cursor++ + 1); } else if ((cursor - 1) != 0 || (!PropertyTools.isDigit(lookBehind())) && PropertyTools.isDigit(lookAhead())) { cursor++; break; } case '+': if (lookAhead() == '+') { cursor += 2; skipWhitespace(); start = cursor; captureIdentifier(); if ((idx = pCtx.variableIndexOf(name = new String(subArray(start, cursor)))) != -1) { return lastNode = new IndexedPreFixIncNode(idx); } else { return lastNode = new PreFixIncNode(name); } } return createOperator(expr, start, cursor++ + 1); case '*': if (lookAhead() == '*') { cursor++; } return createOperator(expr, start, cursor++ + 1); case ';': cursor++; lastWasIdentifier = false; return lastNode = new EndOfStatement(); case '#': case '/': switch (skipCommentBlock()) { case OP_TERMINATE: return null; case OP_RESET_FRAME: continue; } case '?': case ':': case '^': case '%': { return createOperator(expr, start, cursor++ + 1); } case '(': { cursor++; boolean singleToken = true; boolean lastWS = false; skipWhitespace(); for (brace = 1; cursor != length && brace != 0; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': brace--; break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('"', expr, cursor, length); break; case 'i': if (lookAhead() == 'n' && isWhitespace(lookAhead(2)) && !isIdentifierPart(lookBehind())) { fields |= ASTNode.FOLD; for (int level = brace; cursor != length; cursor++) { switch (expr[cursor]) { case '(': brace++; break; case ')': if (--brace != level) { if (lookAhead() == '.') { lastNode = createToken(expr, trimRight(start + 1), (start = cursor++), ASTNode.FOLD); captureToEOT(); return lastNode = new Union(expr, trimRight(start + 2), cursor, fields, lastNode); } else { return createToken(expr, trimRight(start + 1), cursor++, ASTNode.FOLD); } } break; case '\'': cursor = captureStringLiteral('\'', expr, cursor, length); break; case '"': cursor = captureStringLiteral('\'', expr, cursor, length); break; } } } break; default: /** * Check to see if we should disqualify this current token as a potential * type-cast candidate. */ if (lastWS && expr[cursor] != '.') { switch (expr[cursor]) { case '[': case ']': break; default: if (!(isIdentifierPart(expr[cursor]) || expr[cursor] == '.')) { singleToken = false; } } } else if (isWhitespace(expr[cursor])) { lastWS = true; skipWhitespace(); cursor--; } } } if (brace != 0) { throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor); } //todo: support typecast to array types char[] _subset = null; if (singleToken) { int st; TypeDescriptor tDescr = new TypeDescriptor(_subset = subset(expr, st = trimRight(start + 1), trimLeft(cursor - 1) - st), fields); Class cls; if (tDescr.getClassName() != null) { try { cls = getClassReference(pCtx, tDescr); start = cursor; captureToEOS(); return lastNode = new TypeCast(subset(expr, start, cursor - start), cls, fields); } catch (Exception e) { // fallthrough } } } if (_subset != null) { return handleUnion(handleSubstatement(new Substatement(_subset, fields))); } else { return handleUnion(handleSubstatement(new Substatement(subset(expr, start = trimRight(start + 1), trimLeft(cursor - 1) - start), fields))); } } case '}': case ']': case ')': { throw new ParseException("unbalanced braces", expr, cursor); } case '>': { if (expr[cursor + 1] == '>') { if (expr[cursor += 2] == '>') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor + 1] == '=') { return createOperator(expr, start, cursor += 2); } else { return createOperator(expr, start, ++cursor); } } case '<': { if (expr[++cursor] == '<') { if (expr[++cursor] == '<') cursor++; return createOperator(expr, start, cursor); } else if (expr[cursor] == '=') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '\'': case '"': lastNode = new LiteralNode( handleStringEscapes( subset(expr, start + 1, (cursor = captureStringLiteral(expr[cursor], expr, cursor, length)) - start - 1)) , String.class); cursor++; if (tokenContinues()) { return lastNode = handleUnion(lastNode); } return lastNode; case '&': { if (expr[cursor++ + 1] == '&') { return createOperator(expr, start, ++cursor); } else { return createOperator(expr, start, cursor); } } case '|': { if (expr[cursor++ + 1] == '|') { return new OperatorNode(OPERATORS.get(new String(expr, start, ++cursor - start))); } else { return createOperator(expr, start, cursor); } } case '~': if ((cursor++ - 1 != 0 || !isIdentifierPart(lookBehind())) && PropertyTools.isDigit(expr[cursor])) { start = cursor; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Invert(subset(expr, start, cursor - start), fields); } else { if (expr[cursor] == '=') cursor++; return createOperator(expr, start, cursor); } case '!': { ++cursor; if (isNextIdentifier()) { start = cursor; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] == '(') { start = cursor--; captureToEOT(); return lastNode = new Negation(subset(expr, start, cursor - start), fields); } else if (expr[cursor] != '=') throw new CompileException("unexpected operator '!'", expr, cursor, null); else { return createOperator(expr, start, ++cursor); } } case '[': case '{': cursor = balancedCapture(expr, cursor, expr[cursor]) + 1; if (tokenContinues()) { lastNode = new InlineCollectionNode(expr, start, start = cursor, fields); captureToEOT(); return lastNode = new Union(expr, start + 1, cursor, fields, lastNode); } else { return lastNode = new InlineCollectionNode(expr, start, cursor, fields); } default: cursor++; } } } if (start == cursor) return null; return createPropertyToken(start, cursor); } catch (ArrayIndexOutOfBoundsException e) { CompileException c = new CompileException("unexpected end of statement", expr, cursor, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } catch (CompileException e) { CompileException c = new CompileException(e.getMessage(), expr, cursor, e.getCursor() == 0, e); c.setLineNumber(line); c.setColumn(cursor - lastLineStart); throw c; } }
diff --git a/src/main/java/biomesoplenty/common/world/forcedworldgenerators/PondForcedGenerator.java b/src/main/java/biomesoplenty/common/world/forcedworldgenerators/PondForcedGenerator.java index d8ac70975..70d47930b 100644 --- a/src/main/java/biomesoplenty/common/world/forcedworldgenerators/PondForcedGenerator.java +++ b/src/main/java/biomesoplenty/common/world/forcedworldgenerators/PondForcedGenerator.java @@ -1,38 +1,38 @@ package biomesoplenty.common.world.forcedworldgenerators; import java.lang.reflect.Field; import java.util.Random; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.feature.WorldGenerator; import biomesoplenty.common.world.decoration.IBOPDecoration; import biomesoplenty.common.world.generation.ForcedWorldGeneratorBOP; public class PondForcedGenerator extends ForcedWorldGeneratorBOP { @Override public void doGeneration(World world, Random random, Field worldGeneratorField, WorldGenerator worldGenerator, BiomeGenBase biome, IBOPDecoration bopDecoration, int x, int z) throws Exception { if (biome.theBiomeDecorator.generateLakes) { for (int i = 0; i < 50 + bopDecoration.getWorldFeatures().waterPoolsPerChunk; ++i) { - int randX = x + random.nextInt(16); + int randX = x + random.nextInt(16) + 8; int randY = random.nextInt(random.nextInt(248) + 8); - int randZ = z + random.nextInt(16); + int randZ = z + random.nextInt(16) + 8; worldGenerator.generate(world, random, randX, randY, randZ); } for (int i = 0; i < 20 + bopDecoration.getWorldFeatures().lavaPoolsPerChunk; ++i) { - int randX = x + random.nextInt(16); + int randX = x + random.nextInt(16) + 8; int randY = random.nextInt(random.nextInt(random.nextInt(240) + 8) + 8); - int randZ = z + random.nextInt(16); + int randZ = z + random.nextInt(16) + 8; worldGenerator.generate(world, random, randX, randY, randZ); } } } }
false
true
public void doGeneration(World world, Random random, Field worldGeneratorField, WorldGenerator worldGenerator, BiomeGenBase biome, IBOPDecoration bopDecoration, int x, int z) throws Exception { if (biome.theBiomeDecorator.generateLakes) { for (int i = 0; i < 50 + bopDecoration.getWorldFeatures().waterPoolsPerChunk; ++i) { int randX = x + random.nextInt(16); int randY = random.nextInt(random.nextInt(248) + 8); int randZ = z + random.nextInt(16); worldGenerator.generate(world, random, randX, randY, randZ); } for (int i = 0; i < 20 + bopDecoration.getWorldFeatures().lavaPoolsPerChunk; ++i) { int randX = x + random.nextInt(16); int randY = random.nextInt(random.nextInt(random.nextInt(240) + 8) + 8); int randZ = z + random.nextInt(16); worldGenerator.generate(world, random, randX, randY, randZ); } } }
public void doGeneration(World world, Random random, Field worldGeneratorField, WorldGenerator worldGenerator, BiomeGenBase biome, IBOPDecoration bopDecoration, int x, int z) throws Exception { if (biome.theBiomeDecorator.generateLakes) { for (int i = 0; i < 50 + bopDecoration.getWorldFeatures().waterPoolsPerChunk; ++i) { int randX = x + random.nextInt(16) + 8; int randY = random.nextInt(random.nextInt(248) + 8); int randZ = z + random.nextInt(16) + 8; worldGenerator.generate(world, random, randX, randY, randZ); } for (int i = 0; i < 20 + bopDecoration.getWorldFeatures().lavaPoolsPerChunk; ++i) { int randX = x + random.nextInt(16) + 8; int randY = random.nextInt(random.nextInt(random.nextInt(240) + 8) + 8); int randZ = z + random.nextInt(16) + 8; worldGenerator.generate(world, random, randX, randY, randZ); } } }
diff --git a/src/uk/me/parabola/mkgmap/general/MapLine.java b/src/uk/me/parabola/mkgmap/general/MapLine.java index 4d1114d3..1d376bf9 100644 --- a/src/uk/me/parabola/mkgmap/general/MapLine.java +++ b/src/uk/me/parabola/mkgmap/general/MapLine.java @@ -1,138 +1,138 @@ /* * Copyright (C) 2006 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 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. * * * Author: Steve Ratcliffe * Create date: 18-Dec-2006 */ package uk.me.parabola.mkgmap.general; import java.util.List; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.log.Logger; /** * Represent a line on a Garmin map. Lines are a list of points. They have * a type (major highway, stream etc) and a name. And that is just about it. * * @author Steve Ratcliffe */ public class MapLine extends MapElement { private static final Logger log = Logger.getLogger(MapLine.class); private List<Coord> points; private boolean direction; // set if direction is important. private int minLat = Integer.MAX_VALUE; private int minLong = Integer.MAX_VALUE; private int maxLat = Integer.MIN_VALUE; private int maxLong = Integer.MIN_VALUE; private String ref; public MapLine() { } public MapLine(MapLine orig) { super(orig); direction = orig.direction; //roadDef = orig.roadDef; } public MapLine copy() { return new MapLine(this); } public List<Coord> getPoints() { return points; } public void setPoints(List<Coord> points) { if (this.points != null) log.warn("overwriting points"); assert points != null : "trying to set null points"; this.points = points; Coord last = null; for (Coord co : points) { if (last != null && last.equals(co)) - log.warn("Line " + getName() + " has consecutive identical points at ", co.toDegreeString()); + log.info("Line " + getName() + " has consecutive identical points at ", co.toDegreeString()); addToBounds(co); last = co; } } public boolean isDirection() { return direction; } public void setDirection(boolean direction) { this.direction = direction; } public boolean isRoad() { return false; } public boolean isHighway() { return false; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } /** * Get the mid-point of the bounding box for this element. This is as good * an indication of 'where the element is' as any. Previously we just * used the location of the first point which would lead to biases in * allocating elements to subdivisions. * * @return The mid-point of the bounding box. */ public Coord getLocation() { return new Coord((minLat + maxLat) / 2, (minLong + maxLong) / 2); } /** * We build up the bounding box of this element by calling this routine. * * @param co The coordinate to add. */ private void addToBounds(Coord co) { int lat = co.getLatitude(); if (lat < minLat) minLat = lat; if (lat > maxLat) maxLat = lat; int lon = co.getLongitude(); if (lon < minLong) minLong = lon; if (lon > maxLong) maxLong = lon; } /** * Get the region that this element covers. * * @return The area that bounds this element. */ public Area getBounds() { return new Area(minLat, minLong, maxLat, maxLong); } }
true
true
public void setPoints(List<Coord> points) { if (this.points != null) log.warn("overwriting points"); assert points != null : "trying to set null points"; this.points = points; Coord last = null; for (Coord co : points) { if (last != null && last.equals(co)) log.warn("Line " + getName() + " has consecutive identical points at ", co.toDegreeString()); addToBounds(co); last = co; } }
public void setPoints(List<Coord> points) { if (this.points != null) log.warn("overwriting points"); assert points != null : "trying to set null points"; this.points = points; Coord last = null; for (Coord co : points) { if (last != null && last.equals(co)) log.info("Line " + getName() + " has consecutive identical points at ", co.toDegreeString()); addToBounds(co); last = co; } }
diff --git a/tests/src/com/todoroo/andlib/utility/TitleParserTest.java b/tests/src/com/todoroo/andlib/utility/TitleParserTest.java index 76da07724..1088400ec 100644 --- a/tests/src/com/todoroo/andlib/utility/TitleParserTest.java +++ b/tests/src/com/todoroo/andlib/utility/TitleParserTest.java @@ -1,549 +1,549 @@ package com.todoroo.andlib.utility; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import com.google.ical.values.Frequency; import com.google.ical.values.RRule; import com.timsu.astrid.R; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.test.DatabaseTestCase; import com.todoroo.astrid.utility.TitleParser; public class TitleParserTest extends DatabaseTestCase { @Override protected void setUp() throws Exception { super.setUp(); Preferences.setStringFromInteger(R.string.p_default_urgency_key, 0); } /** test that completing a task w/ no regular expressions creates a simple task with no date, no repeat, no lists*/ public void testNoRegexes() throws Exception{ TaskService taskService = new TaskService(); Task task = new Task(); Task nothing = new Task(); task.setValue(Task.TITLE, "Jog"); taskService.quickAdd(task); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); assertEquals(task.getValue(Task.RECURRENCE), nothing.getValue(Task.RECURRENCE)); } /** Tests correct date is parsed **/ public void testMonthDate() { TaskService taskService = new TaskService(); Task task = new Task(); String[] titleMonthStrings = { "Jan.", "January", "Feb.", "February", "Mar.", "March", "Apr.", "April", "May", "May", "Jun.", "June", "Jul.", "July", "Aug.", "August", "Sep.", "September", "Oct.", "October", "Nov.", "November", "Dec.", "December" }; for (int i = 0; i < 23; i++) { String testTitle = "Jog on " + titleMonthStrings[i] + " 12."; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMonth(), i/2); assertEquals(date.getDate(), 12); } } public void testMonthSlashDay() { TaskService taskService = new TaskService(); Task task = new Task(); for (int i = 1; i < 13; i++) { String testTitle = "Jog on " + i + "/12/13"; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMonth(), i-1); assertEquals(date.getDate(), 12); assertEquals(date.getYear(), 113); } } public void testArmyTime() { TaskService taskService = new TaskService(); Task task = new Task(); String testTitle = "Jog on 23:21."; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 21); assertEquals(date.getHours(), 23); } public void test_AM_PM() { TaskService taskService = new TaskService(); Task task = new Task(); String testTitle = "Jog at 8:33 PM."; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 33); assertEquals(date.getHours(), 20); } public void test_at_hour() { TaskService taskService = new TaskService(); Task task = new Task(); String testTitle = "Jog at 8 PM."; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 0); assertEquals(date.getHours(), 20); } public void test_oclock_AM() { TaskService taskService = new TaskService(); Task task = new Task(); String testTitle = "Jog at 8 o'clock AM."; insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 0); assertEquals(date.getHours(), 8); } public void test_several_forms_of_eight() { TaskService taskService = new TaskService(); Task task = new Task(); String[] testTitles = { "Jog 8 AM", "Jog 8 o'clock AM", "at 8:00 AM" }; for (String testTitle: testTitles) { insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 0); assertEquals(date.getHours(), 8); } } public void test_several_forms_of_1230PM() { TaskService taskService = new TaskService(); Task task = new Task(); String[] testTitles = { "Jog 12:30 PM", "at 12:30 PM", "Do something on 12:30 PM", "Jog at 12:30 PM Friday" }; for (String testTitle: testTitles) { insertTitleAddTask(testTitle, task, taskService); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getMinutes(), 30); assertEquals(date.getHours(), 12); } } private void insertTitleAddTask(String title, Task task, TaskService taskService) { task.setValue(Task.TITLE, title); taskService.quickAdd(task); } // ----------------Days begin----------------// public void testDays() throws Exception{ Calendar today = Calendar.getInstance(); TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog today"); taskService.quickAdd(task); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay()+1, today.get(Calendar.DAY_OF_WEEK)); //Calendar starts 1-6, date.getDay() starts at 0 task = new Task(); task.setValue(Task.TITLE, "Jog tomorrow"); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); - assertEquals(date.getDay()+1 % 7, today.get(Calendar.DAY_OF_WEEK)+1 % 7); + assertEquals((date.getDay()+1) % 7, (today.get(Calendar.DAY_OF_WEEK)+1) % 7); String[] days = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", }; String[] abrevDays = { "sun.", "mon.", "tue.", "wed.", "thu.", "fri.", "sat." }; for (int i = 1; i <= 6; i++){ task = new Task(); task.setValue(Task.TITLE, "Jog "+ days[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); task = new Task(); task.setValue(Task.TITLE, "Jog "+ abrevDays[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); } } //----------------Days end----------------// //----------------Priority begin----------------// /** tests all words using priority 0 */ public void testPriority0() throws Exception { String[] acceptedStrings = { "priority 0", "least priority", "lowest priority", "bang 0" }; TaskService taskService = new TaskService(); Task task = new Task(); for (String acceptedString:acceptedStrings){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedString); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_LEAST); } for (String acceptedString:acceptedStrings){ task = new Task(); task.setValue(Task.TITLE, acceptedString + " jog"); //test at beginning of task. should not set importance. taskService.quickAdd(task); assertNotSame((int)task.getValue(Task.IMPORTANCE),(int)Task.IMPORTANCE_LEAST); } } public void testPriority1() throws Exception { String[] acceptedStringsAtEnd = { "priority 1", "low priority", "bang", "bang 1" }; String[] acceptedStringsAnywhere = { "!1", "!" }; TaskService taskService = new TaskService(); Task task = new Task(); for (String acceptedStringAtEnd:acceptedStringsAtEnd){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAtEnd); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_SHOULD_DO); } for (String acceptedStringAtEnd:acceptedStringsAtEnd){ task = new Task(); task.setValue(Task.TITLE, acceptedStringAtEnd + " jog"); //test at beginning of task. should not set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_SHOULD_DO); } for (String acceptedStringAnywhere:acceptedStringsAnywhere){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAnywhere); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_SHOULD_DO); task.setValue(Task.TITLE, acceptedStringAnywhere + " jog"); //test at beginning of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_SHOULD_DO); } } public void testPriority2() throws Exception { String[] acceptedStringsAtEnd = { "priority 2", "high priority", "bang bang", "bang 2" }; String[] acceptedStringsAnywhere = { "!2", "!!" }; TaskService taskService = new TaskService(); Task task = new Task(); for (String acceptedStringAtEnd:acceptedStringsAtEnd){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAtEnd); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_MUST_DO); task = new Task(); task.setValue(Task.TITLE, acceptedStringAtEnd + " jog"); //test at beginning of task. should not set importance. taskService.quickAdd(task); assertNotSame((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_MUST_DO); } for (String acceptedStringAnywhere:acceptedStringsAnywhere){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAnywhere); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_MUST_DO); task.setValue(Task.TITLE, acceptedStringAnywhere + " jog"); //test at beginning of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_MUST_DO); } } public void testPriority3() throws Exception { String[] acceptedStringsAtEnd = { "priority 3", "highest priority", "bang bang bang", "bang 3", "bang bang bang bang bang bang bang" }; String[] acceptedStringsAnywhere = { "!3", "!!!", "!6", "!!!!!!!!!!!!!" }; TaskService taskService = new TaskService(); Task task = new Task(); for (String acceptedStringAtEnd:acceptedStringsAtEnd){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAtEnd); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_DO_OR_DIE); task = new Task(); task.setValue(Task.TITLE, acceptedStringAtEnd + " jog"); //test at beginning of task. should not set importance. taskService.quickAdd(task); assertNotSame((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_DO_OR_DIE); } for (String acceptedStringAnywhere:acceptedStringsAnywhere){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedStringAnywhere); //test at end of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_DO_OR_DIE); task.setValue(Task.TITLE, acceptedStringAnywhere + " jog"); //test at beginning of task. should set importance. taskService.quickAdd(task); assertEquals((int)task.getValue(Task.IMPORTANCE), (int)Task.IMPORTANCE_DO_OR_DIE); } } //----------------Priority end----------------// //----------------Repeats begin----------------// /** test daily repeat from due date, but with no due date set */ public void testDailyWithNoDueDate() throws Exception { TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog daily"); taskService.quickAdd(task); RRule rrule = new RRule(); rrule.setFreq(Frequency.DAILY); rrule.setInterval(1); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task.setValue(Task.TITLE, "Jog every day"); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); for (int i = 1; i <= 12; i++){ task.setValue(Task.TITLE, "Jog every " + i + " days."); rrule.setInterval(i); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task = new Task(); } } /** test weekly repeat from due date, with no due date & time set */ public void testWeeklyWithNoDueDate() throws Exception { TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog weekly"); taskService.quickAdd(task); RRule rrule = new RRule(); rrule.setFreq(Frequency.WEEKLY); rrule.setInterval(1); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task.setValue(Task.TITLE, "Jog every week"); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); for (int i = 1; i <= 12; i++){ task.setValue(Task.TITLE, "Jog every " + i + " weeks"); rrule.setInterval(i); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task = new Task(); } } /** test hourly repeat from due date, with no due date but no time */ public void testMonthlyFromNoDueDate() throws Exception { TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog monthly"); taskService.quickAdd(task); RRule rrule = new RRule(); rrule.setFreq(Frequency.MONTHLY); rrule.setInterval(1); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task.setValue(Task.TITLE, "Jog every month"); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); for (int i = 1; i <= 12; i++){ task.setValue(Task.TITLE, "Jog every " + i + " months"); rrule.setInterval(i); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertFalse(task.hasDueTime()); assertFalse(task.hasDueDate()); task = new Task(); } } public void testDailyFromDueDate() throws Exception { TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog daily starting from today"); taskService.quickAdd(task); RRule rrule = new RRule(); rrule.setFreq(Frequency.DAILY); rrule.setInterval(1); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); task.setValue(Task.TITLE, "Jog every day starting from today"); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); for (int i = 1; i <= 12; i++){ task.setValue(Task.TITLE, "Jog every " + i + " days starting from today"); rrule.setInterval(i); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); task = new Task(); } } public void testWeeklyFromDueDate() throws Exception { TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog weekly starting from today"); taskService.quickAdd(task); RRule rrule = new RRule(); rrule.setFreq(Frequency.WEEKLY); rrule.setInterval(1); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); task.setValue(Task.TITLE, "Jog every week starting from today"); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); for (int i = 1; i <= 12; i++){ task.setValue(Task.TITLE, "Jog every " + i + " weeks starting from today"); rrule.setInterval(i); taskService.quickAdd(task); assertEquals(task.getValue(Task.RECURRENCE), rrule.toIcal()); assertTrue(task.hasDueDate()); task = new Task(); } } //----------------Repeats end----------------// //----------------Tags begin----------------// /** tests all words using priority 0 */ public void testTagsPound() throws Exception { String[] acceptedStrings = { "#tag", "#a", "#(a cool tag)", "#(cool)" }; Task task = new Task(); for (String acceptedString:acceptedStrings){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedString); //test at end of task. should set importance. ArrayList<String> tags = new ArrayList<String>(); TitleParser.listHelper(task, tags); String[] splitTags = TitleParser.trimParenthesisAndSplit(acceptedString); for (String tag : splitTags) { assertTrue("test pound at failed for string: " + acceptedString + " for tags: " + tags.toString(),tags.contains(tag)); } } } /** tests all words using priority 0 */ public void testTagsAt() throws Exception { String[] acceptedStrings = { "@tag", "@a", "@(a cool tag)", "@(cool)" }; Task task = new Task(); for (String acceptedString:acceptedStrings){ task = new Task(); task.setValue(Task.TITLE, "Jog " + acceptedString); //test at end of task. should set importance. ArrayList<String> tags = new ArrayList<String>(); TitleParser.listHelper(task, tags); String[] splitTags = TitleParser.trimParenthesisAndSplit(acceptedString); for (String tag : splitTags) { assertTrue("testTagsAt failed for string: " + acceptedString+ " for tags: " + tags.toString(), tags.contains(tag)); } } } //----------------Priority end----------------// }
true
true
public void testDays() throws Exception{ Calendar today = Calendar.getInstance(); TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog today"); taskService.quickAdd(task); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay()+1, today.get(Calendar.DAY_OF_WEEK)); //Calendar starts 1-6, date.getDay() starts at 0 task = new Task(); task.setValue(Task.TITLE, "Jog tomorrow"); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay()+1 % 7, today.get(Calendar.DAY_OF_WEEK)+1 % 7); String[] days = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", }; String[] abrevDays = { "sun.", "mon.", "tue.", "wed.", "thu.", "fri.", "sat." }; for (int i = 1; i <= 6; i++){ task = new Task(); task.setValue(Task.TITLE, "Jog "+ days[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); task = new Task(); task.setValue(Task.TITLE, "Jog "+ abrevDays[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); } }
public void testDays() throws Exception{ Calendar today = Calendar.getInstance(); TaskService taskService = new TaskService(); Task task = new Task(); task.setValue(Task.TITLE, "Jog today"); taskService.quickAdd(task); Date date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay()+1, today.get(Calendar.DAY_OF_WEEK)); //Calendar starts 1-6, date.getDay() starts at 0 task = new Task(); task.setValue(Task.TITLE, "Jog tomorrow"); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals((date.getDay()+1) % 7, (today.get(Calendar.DAY_OF_WEEK)+1) % 7); String[] days = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", }; String[] abrevDays = { "sun.", "mon.", "tue.", "wed.", "thu.", "fri.", "sat." }; for (int i = 1; i <= 6; i++){ task = new Task(); task.setValue(Task.TITLE, "Jog "+ days[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); task = new Task(); task.setValue(Task.TITLE, "Jog "+ abrevDays[i]); taskService.quickAdd(task); date = new Date(task.getValue(Task.DUE_DATE)); assertEquals(date.getDay(), i); } }
diff --git a/PhotoWebApp/WEB-INF/classes/main/web/Search.java b/PhotoWebApp/WEB-INF/classes/main/web/Search.java index a4df1b9..ce5b68e 100644 --- a/PhotoWebApp/WEB-INF/classes/main/web/Search.java +++ b/PhotoWebApp/WEB-INF/classes/main/web/Search.java @@ -1,99 +1,99 @@ package main.web; import java.io.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.servlet.*; import javax.servlet.http.*; import main.util.DBConnection; import main.util.Filter; public class Search extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/Search.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keywords = request.getParameter("keywords"); String fromDate = request.getParameter("fromDate"); String toDate = request.getParameter("toDate"); String sort = request.getParameter("SortBy"); String query = "SELECT * FROM images"; if(!keywords.isEmpty()){ - query += " WHERE CONTAINS(subject, ?, 1) > 0 OR CONTAINS(place, ?, 2) > 0 OR CONTAINS(description, ?, 3) > 0 "; + query += " WHERE (CONTAINS(subject, ?, 1) > 0 OR CONTAINS(place, ?, 2) > 0 OR CONTAINS(description, ?, 3) > 0 )"; } if(!fromDate.isEmpty() && keywords.isEmpty()){ query += " WHERE timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!fromDate.isEmpty() && !keywords.isEmpty()){ query += " AND timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(!toDate.isEmpty() && keywords.isEmpty() && fromDate.isEmpty()){ query += " WHERE timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!toDate.isEmpty()){ query += " AND timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(sort.equals("Rank")){ query += " ORDER BY ((6*SCORE(1))+(3*SCORE(2))+SCORE(3)) DESC"; }else if(sort.equals("New")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing DESC"; }else if(sort.equals("Old")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing ASC"; } Connection myConn = null; try{ myConn = DBConnection.createConnection(); ArrayList<String> matchingIds = new ArrayList<String>(); PreparedStatement myQuery = myConn.prepareStatement(query); int n = 1; if(!keywords.isEmpty()){ myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; } if(!fromDate.isEmpty()){ myQuery.setString(n, fromDate); n++; } if(!toDate.isEmpty()){ myQuery.setString(n, toDate); n++; } ResultSet results = myQuery.executeQuery(); HttpSession session = request.getSession(); String currentUser = (String) session.getAttribute("username"); while (results.next()) { String foundId = Integer.toString(results.getInt("photo_id")); if(Filter.isViewable(currentUser, foundId)){ matchingIds.add(foundId); } } request.setAttribute("matchingIds", matchingIds); myQuery.close(); } catch(Exception ex) { System.err.println("Exception: " + ex.getMessage()); } finally { try { myConn.close(); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } } request.getRequestDispatcher("/SearchResults.jsp").forward(request, response); } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keywords = request.getParameter("keywords"); String fromDate = request.getParameter("fromDate"); String toDate = request.getParameter("toDate"); String sort = request.getParameter("SortBy"); String query = "SELECT * FROM images"; if(!keywords.isEmpty()){ query += " WHERE CONTAINS(subject, ?, 1) > 0 OR CONTAINS(place, ?, 2) > 0 OR CONTAINS(description, ?, 3) > 0 "; } if(!fromDate.isEmpty() && keywords.isEmpty()){ query += " WHERE timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!fromDate.isEmpty() && !keywords.isEmpty()){ query += " AND timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(!toDate.isEmpty() && keywords.isEmpty() && fromDate.isEmpty()){ query += " WHERE timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!toDate.isEmpty()){ query += " AND timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(sort.equals("Rank")){ query += " ORDER BY ((6*SCORE(1))+(3*SCORE(2))+SCORE(3)) DESC"; }else if(sort.equals("New")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing DESC"; }else if(sort.equals("Old")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing ASC"; } Connection myConn = null; try{ myConn = DBConnection.createConnection(); ArrayList<String> matchingIds = new ArrayList<String>(); PreparedStatement myQuery = myConn.prepareStatement(query); int n = 1; if(!keywords.isEmpty()){ myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; } if(!fromDate.isEmpty()){ myQuery.setString(n, fromDate); n++; } if(!toDate.isEmpty()){ myQuery.setString(n, toDate); n++; } ResultSet results = myQuery.executeQuery(); HttpSession session = request.getSession(); String currentUser = (String) session.getAttribute("username"); while (results.next()) { String foundId = Integer.toString(results.getInt("photo_id")); if(Filter.isViewable(currentUser, foundId)){ matchingIds.add(foundId); } } request.setAttribute("matchingIds", matchingIds); myQuery.close(); } catch(Exception ex) { System.err.println("Exception: " + ex.getMessage()); } finally { try { myConn.close(); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } } request.getRequestDispatcher("/SearchResults.jsp").forward(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keywords = request.getParameter("keywords"); String fromDate = request.getParameter("fromDate"); String toDate = request.getParameter("toDate"); String sort = request.getParameter("SortBy"); String query = "SELECT * FROM images"; if(!keywords.isEmpty()){ query += " WHERE (CONTAINS(subject, ?, 1) > 0 OR CONTAINS(place, ?, 2) > 0 OR CONTAINS(description, ?, 3) > 0 )"; } if(!fromDate.isEmpty() && keywords.isEmpty()){ query += " WHERE timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!fromDate.isEmpty() && !keywords.isEmpty()){ query += " AND timing >= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(!toDate.isEmpty() && keywords.isEmpty() && fromDate.isEmpty()){ query += " WHERE timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; }else if(!toDate.isEmpty()){ query += " AND timing <= TO_DATE( ? , 'DD/MM/YYYY HH24:MI:SS')"; } if(sort.equals("Rank")){ query += " ORDER BY ((6*SCORE(1))+(3*SCORE(2))+SCORE(3)) DESC"; }else if(sort.equals("New")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing DESC"; }else if(sort.equals("Old")){ query += " ORDER BY CASE WHEN timing IS NULL THEN 1 ELSE 0 END, timing ASC"; } Connection myConn = null; try{ myConn = DBConnection.createConnection(); ArrayList<String> matchingIds = new ArrayList<String>(); PreparedStatement myQuery = myConn.prepareStatement(query); int n = 1; if(!keywords.isEmpty()){ myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; myQuery.setString(n, keywords); n++; } if(!fromDate.isEmpty()){ myQuery.setString(n, fromDate); n++; } if(!toDate.isEmpty()){ myQuery.setString(n, toDate); n++; } ResultSet results = myQuery.executeQuery(); HttpSession session = request.getSession(); String currentUser = (String) session.getAttribute("username"); while (results.next()) { String foundId = Integer.toString(results.getInt("photo_id")); if(Filter.isViewable(currentUser, foundId)){ matchingIds.add(foundId); } } request.setAttribute("matchingIds", matchingIds); myQuery.close(); } catch(Exception ex) { System.err.println("Exception: " + ex.getMessage()); } finally { try { myConn.close(); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } } request.getRequestDispatcher("/SearchResults.jsp").forward(request, response); }
diff --git a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java b/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java index 8c15d389e..b58992258 100755 --- a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java +++ b/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java @@ -1,47 +1,47 @@ /* ==================================================================== 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.poi.poifs.storage; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for org.apache.poi.poifs.storage<br/> * * @author Josh Micich */ public final class AllPOIFSStorageTests { - public static Test suite() { - TestSuite result = new TestSuite("Tests for org.apache.poi.poifs.storage"); - result.addTestSuite(TestBATBlock.class); - result.addTestSuite(TestBlockAllocationTableReader.class); - result.addTestSuite(TestBlockAllocationTableWriter.class); - result.addTestSuite(TestBlockListImpl.class); - result.addTestSuite(TestDocumentBlock.class); - result.addTestSuite(TestHeaderBlockReader.class); - result.addTestSuite(TestHeaderBlockWriter.class); - result.addTestSuite(TestPropertyBlock.class); - result.addTestSuite(TestRawDataBlock.class); - result.addTestSuite(TestRawDataBlockList.class); - result.addTestSuite(TestSmallBlockTableReader.class); - result.addTestSuite(TestSmallBlockTableWriter.class); - result.addTestSuite(TestSmallDocumentBlock.class); - result.addTestSuite(TestSmallDocumentBlockList.class); - return result; - } + public static Test suite() { + TestSuite result = new TestSuite(AllPOIFSStorageTests.class.getName()); + result.addTestSuite(TestBATBlock.class); + result.addTestSuite(TestBlockAllocationTableReader.class); + result.addTestSuite(TestBlockAllocationTableWriter.class); + result.addTestSuite(TestBlockListImpl.class); + result.addTestSuite(TestDocumentBlock.class); + result.addTestSuite(TestHeaderBlockReader.class); + result.addTestSuite(TestHeaderBlockWriter.class); + result.addTestSuite(TestPropertyBlock.class); + result.addTestSuite(TestRawDataBlock.class); + result.addTestSuite(TestRawDataBlockList.class); + result.addTestSuite(TestSmallBlockTableReader.class); + result.addTestSuite(TestSmallBlockTableWriter.class); + result.addTestSuite(TestSmallDocumentBlock.class); + result.addTestSuite(TestSmallDocumentBlockList.class); + return result; + } }
true
true
public static Test suite() { TestSuite result = new TestSuite("Tests for org.apache.poi.poifs.storage"); result.addTestSuite(TestBATBlock.class); result.addTestSuite(TestBlockAllocationTableReader.class); result.addTestSuite(TestBlockAllocationTableWriter.class); result.addTestSuite(TestBlockListImpl.class); result.addTestSuite(TestDocumentBlock.class); result.addTestSuite(TestHeaderBlockReader.class); result.addTestSuite(TestHeaderBlockWriter.class); result.addTestSuite(TestPropertyBlock.class); result.addTestSuite(TestRawDataBlock.class); result.addTestSuite(TestRawDataBlockList.class); result.addTestSuite(TestSmallBlockTableReader.class); result.addTestSuite(TestSmallBlockTableWriter.class); result.addTestSuite(TestSmallDocumentBlock.class); result.addTestSuite(TestSmallDocumentBlockList.class); return result; }
public static Test suite() { TestSuite result = new TestSuite(AllPOIFSStorageTests.class.getName()); result.addTestSuite(TestBATBlock.class); result.addTestSuite(TestBlockAllocationTableReader.class); result.addTestSuite(TestBlockAllocationTableWriter.class); result.addTestSuite(TestBlockListImpl.class); result.addTestSuite(TestDocumentBlock.class); result.addTestSuite(TestHeaderBlockReader.class); result.addTestSuite(TestHeaderBlockWriter.class); result.addTestSuite(TestPropertyBlock.class); result.addTestSuite(TestRawDataBlock.class); result.addTestSuite(TestRawDataBlockList.class); result.addTestSuite(TestSmallBlockTableReader.class); result.addTestSuite(TestSmallBlockTableWriter.class); result.addTestSuite(TestSmallDocumentBlock.class); result.addTestSuite(TestSmallDocumentBlockList.class); return result; }
diff --git a/core/src/org/icepdf/core/pobjects/ImageStream.java b/core/src/org/icepdf/core/pobjects/ImageStream.java index 0c8e7a96..e48762b6 100644 --- a/core/src/org/icepdf/core/pobjects/ImageStream.java +++ b/core/src/org/icepdf/core/pobjects/ImageStream.java @@ -1,1140 +1,1140 @@ /* * Copyright 2006-2013 ICEsoft Technologies 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 org.icepdf.core.pobjects; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageDecoder; import org.icepdf.core.io.BitStream; import org.icepdf.core.io.SeekableInputConstrainedWrapper; import org.icepdf.core.pobjects.filters.CCITTFax; import org.icepdf.core.pobjects.filters.CCITTFaxDecoder; import org.icepdf.core.pobjects.graphics.*; import org.icepdf.core.tag.Tagger; import org.icepdf.core.util.Defs; import org.icepdf.core.util.Library; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.image.renderable.ParameterBlock; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * ImageStream contains image data that is contains in an XObject of subtype * Image. * * @since 5.0 */ public class ImageStream extends Stream { private static final Logger logger = Logger.getLogger(ImageStream.class.toString()); public static final Name TYPE_VALUE = new Name("Image"); public static final Name BITSPERCOMPONENT_KEY = new Name("BitsPerComponent"); public static final Name BPC_KEY = new Name("BPC"); public static final Name DECODE_KEY = new Name("Decode"); public static final Name D_KEY = new Name("D"); public static final Name SMASK_KEY = new Name("SMask"); public static final Name MASK_KEY = new Name("Mask"); public static final Name JBIG2GLOBALS_KEY = new Name("JBIG2Globals"); public static final Name DECODEPARMS_KEY = new Name("DecodeParms"); public static final Name DP_KEY = new Name("DP"); public static final Name K_KEY = new Name("K"); public static final Name ENCODEDBYTEALIGN_KEY = new Name("EncodedByteAlign"); public static final Name COLUMNS_KEY = new Name("Columns"); public static final Name ROWS_KEY = new Name("Rows"); public static final Name BLACKIS1_KEY = new Name("BlackIs1"); // filter names protected static final String[] CCITTFAX_DECODE_FILTERS = new String[]{"CCITTFaxDecode", "/CCF", "CCF"}; protected static final String[] DCT_DECODE_FILTERS = new String[]{"DCTDecode", "/DCT", "DCT"}; protected static final String[] JBIG2_DECODE_FILTERS = new String[]{"JBIG2Decode"}; protected static final String[] JPX_DECODE_FILTERS = new String[]{"JPXDecode"}; // paper size for rare corner case when ccittfax is missing a dimension. private static double pageRatio; // flag the forces jai to be use over our fax decode class. private static boolean forceJaiccittfax; static { // define alternate page size ration w/h, default Legal. pageRatio = Defs.sysPropertyDouble("org.icepdf.core.pageRatio", 8.26 / 11.68); // force jai as the default ccittfax decode. forceJaiccittfax = Defs.sysPropertyBoolean("org.icepdf.core.ccittfax.jai", false); } private int width; private int height; /** * Create a new instance of a Stream. * * @param l library containing a hash of all document objects * @param h HashMap of parameters specific to the Stream object. * @param streamInputWrapper Accessor to stream byte data */ public ImageStream(Library l, HashMap h, SeekableInputConstrainedWrapper streamInputWrapper) { super(l, h, streamInputWrapper); init(); } public ImageStream(Library l, HashMap h, byte[] rawBytes) { super(l, h, rawBytes); init(); } public void init() { // get dimension of image stream width = library.getInt(entries, WIDTH_KEY); height = library.getInt(entries, HEIGHT_KEY); // PDF-458 corner case/one off for trying to guess the width or height // of an CCITTfax image that is basically the same use as the page, we // use the page dimensions to try and determine the page size. // This will fail miserably if the image isn't full page. if (height == 0) { height = (int) ((1 / pageRatio) * width); } else if (width == 0) { width = (int) (pageRatio * height); } } public int getWidth() { return width; } public int getHeight() { return height; } /** * Gets the image object for the given resource. This method can optionally * scale an image to reduce the total memory foot print or to increase the * perceived render quality on screen at low zoom levels. * * @param fill color value of image * @param resources resouces containing image reference * @return new image object */ // was synchronized, not think it is needed? public BufferedImage getImage(Color fill, Resources resources) { if (Tagger.tagging) Tagger.tagImage("Filter=" + getNormalisedFilterNames()); // parse colour space PColorSpace colourSpace = null; Object o = library.getObject(entries, COLORSPACE_KEY); if (resources != null) { colourSpace = resources.getColorSpace(o); } // assume b&w image is no colour space if (colourSpace == null) { colourSpace = new DeviceGray(library, null); if (Tagger.tagging) Tagger.tagImage("ColorSpace_Implicit_DeviceGray"); } if (Tagger.tagging) Tagger.tagImage("ColorSpace=" + colourSpace.getDescription()); boolean imageMask = isImageMask(); if (Tagger.tagging) Tagger.tagImage("ImageMask=" + imageMask); // find out the number of bits in the image int bitsPerComponent = library.getInt(entries, BITSPERCOMPONENT_KEY); if (imageMask && bitsPerComponent == 0) { bitsPerComponent = 1; if (Tagger.tagging) Tagger.tagImage("BitsPerComponent_Implicit_1"); } if (Tagger.tagging) Tagger.tagImage("BitsPerComponent=" + bitsPerComponent); // check for available memory, get colour space and bit count // to better estimate size of image in memory int colorSpaceCompCount = colourSpace.getNumComponents(); // parse decode information int maxValue = ((int) Math.pow(2, bitsPerComponent)) - 1; float[] decode = new float[2 * colorSpaceCompCount]; List<Number> decodeVec = (List<Number>) library.getObject(entries, DECODE_KEY); if (decodeVec == null) { // add a decode param for each colour channel. for (int i = 0, j = 0; i < colorSpaceCompCount; i++) { decode[j++] = 0.0f; decode[j++] = 1.0f / maxValue; } if (Tagger.tagging) Tagger.tagImage("Decode_Implicit_01"); } else { for (int i = 0, j = 0; i < colorSpaceCompCount; i++) { float Dmin = decodeVec.get(j).floatValue(); float Dmax = decodeVec.get(j + 1).floatValue(); decode[j++] = Dmin; decode[j++] = (Dmax - Dmin) / maxValue; } } if (Tagger.tagging) Tagger.tagImage("Decode=" + Arrays.toString(decode)); BufferedImage smaskImage = null; BufferedImage maskImage = null; int[] maskMinRGB = null; int[] maskMaxRGB = null; int maskMinIndex = -1; int maskMaxIndex = -1; Object smaskObj = library.getObject(entries, SMASK_KEY); Object maskObj = library.getObject(entries, MASK_KEY); if (smaskObj instanceof Stream) { if (Tagger.tagging) Tagger.tagImage("SMaskStream"); ImageStream smaskStream = (ImageStream) smaskObj; if (smaskStream.isImageSubtype()) { smaskImage = smaskStream.getImage(fill, resources); } } if (smaskImage != null) { if (Tagger.tagging) Tagger.tagImage("SMaskImage"); } if (maskObj != null && smaskImage == null) { if (maskObj instanceof Stream) { if (Tagger.tagging) Tagger.tagImage("MaskStream"); ImageStream maskStream = (ImageStream) maskObj; if (maskStream.isImageSubtype()) { maskImage = maskStream.getImage(fill, resources); if (maskImage != null) { if (Tagger.tagging) Tagger.tagImage("MaskImage"); } } } else if (maskObj instanceof List) { if (Tagger.tagging) Tagger.tagImage("MaskVector"); List maskVector = (List) maskObj; int[] maskMinOrigCompsInt = new int[colorSpaceCompCount]; int[] maskMaxOrigCompsInt = new int[colorSpaceCompCount]; for (int i = 0; i < colorSpaceCompCount; i++) { if ((i * 2) < maskVector.size()) maskMinOrigCompsInt[i] = ((Number) maskVector.get(i * 2)).intValue(); if ((i * 2 + 1) < maskVector.size()) maskMaxOrigCompsInt[i] = ((Number) maskVector.get(i * 2 + 1)).intValue(); } if (colourSpace instanceof Indexed) { Indexed icolourSpace = (Indexed) colourSpace; Color[] colors = icolourSpace.accessColorTable(); if (colors != null && maskMinOrigCompsInt.length >= 1 && maskMaxOrigCompsInt.length >= 1) { maskMinIndex = maskMinOrigCompsInt[0]; maskMaxIndex = maskMaxOrigCompsInt[0]; if (maskMinIndex >= 0 && maskMinIndex < colors.length && maskMaxIndex >= 0 && maskMaxIndex < colors.length) { Color minColor = colors[maskMinOrigCompsInt[0]]; Color maxColor = colors[maskMaxOrigCompsInt[0]]; maskMinRGB = new int[]{minColor.getRed(), minColor.getGreen(), minColor.getBlue()}; maskMaxRGB = new int[]{maxColor.getRed(), maxColor.getGreen(), maxColor.getBlue()}; } } } else { PColorSpace.reverseInPlace(maskMinOrigCompsInt); PColorSpace.reverseInPlace(maskMaxOrigCompsInt); float[] maskMinOrigComps = new float[colorSpaceCompCount]; float[] maskMaxOrigComps = new float[colorSpaceCompCount]; colourSpace.normaliseComponentsToFloats(maskMinOrigCompsInt, maskMinOrigComps, (1 << bitsPerComponent) - 1); colourSpace.normaliseComponentsToFloats(maskMaxOrigCompsInt, maskMaxOrigComps, (1 << bitsPerComponent) - 1); Color minColor = colourSpace.getColor(maskMinOrigComps); Color maxColor = colourSpace.getColor(maskMaxOrigComps); PColorSpace.reverseInPlace(maskMinOrigComps); PColorSpace.reverseInPlace(maskMaxOrigComps); maskMinRGB = new int[]{minColor.getRed(), minColor.getGreen(), minColor.getBlue()}; maskMaxRGB = new int[]{maxColor.getRed(), maxColor.getGreen(), maxColor.getBlue()}; } } } BufferedImage img = getImage( colourSpace, fill, width, height, colorSpaceCompCount, bitsPerComponent, imageMask, decode, smaskImage, maskImage, maskMinRGB, maskMaxRGB, maskMinIndex, maskMaxIndex); if (Tagger.tagging) Tagger.endImage(pObjectReference); return img; } /** * Utility to to the image work, the public version pretty much just * parses out image dictionary parameters. This method start the actual * image decoding. * * @param colourSpace colour space of image. * @param fill fill color to aply to image from current graphics context. * @param width width of image. * @param height heigth of image * @param colorSpaceCompCount colour space component count, 1, 3, 4 etc. * @param bitsPerComponent number of bits that represent one component. * @param imageMask boolean flag to use image mask or not. * @param decode decode array, 1,0 or 0,1 can effect colour interpretation. * @param sMaskImage smaask image value, optional. * @param maskImage buffered image image mask to apply to decoded image, optional. * @param maskMinRGB max rgb values for the mask * @param maskMaxRGB min rgb values for the mask. * @param maskMinIndex max indexed colour values for the mask. * @param maskMaxIndex min indexed colour values for the mask. * @return buffered image of decoded image stream, null if an error occured. */ private BufferedImage getImage( PColorSpace colourSpace, Color fill, int width, int height, int colorSpaceCompCount, int bitsPerComponent, boolean imageMask, float[] decode, BufferedImage sMaskImage, BufferedImage maskImage, int[] maskMinRGB, int[] maskMaxRGB, int maskMinIndex, int maskMaxIndex) { // check to see if we need to create an imge with alpha, a mask // will have imageMask=true and in this case we don't need alpha // boolean alphaImage = !imageMask && (sMaskImage != null || maskImage != null); BufferedImage decodedImage = null; // JPEG writes out image if successful if (shouldUseDCTDecode()) { if (Tagger.tagging) Tagger.tagImage("DCTDecode"); decodedImage = dctDecode(width, height, colourSpace, bitsPerComponent, decode); } // JBIG2 writes out image if successful else if (shouldUseJBIG2Decode()) { if (Tagger.tagging) Tagger.tagImage("JBIG2Decode"); decodedImage = jbig2Decode(width, height, colourSpace, bitsPerComponent); } // JPEG2000 writes out image if successful else if (shouldUseJPXDecode()) { if (Tagger.tagging) Tagger.tagImage("JPXDecode"); decodedImage = jpxDecode(width, height, colourSpace, bitsPerComponent, decode); } else { byte[] data = getDecodedStreamBytes( width * height * colourSpace.getNumComponents() * bitsPerComponent / 8); int dataLength = data.length; // CCITTfax data is raw byte decode. if (shouldUseCCITTFaxDecode()) { // try default ccittfax decode. if (Tagger.tagging) Tagger.tagImage("CCITTFaxDecode"); try { // corner case where a user may want to use JAI because of // speed or compatibility requirements. if (forceJaiccittfax) { throw new Throwable("Forcing CCITTFAX decode via JAI"); } data = ccittFaxDecode(data, width, height); dataLength = data.length; } catch (Throwable e) { // on a failure then fall back to JAI for a try. likely // will not happen. if (Tagger.tagging) { Tagger.tagImage("CCITTFaxDecode JAI"); } decodedImage = CCITTFax.attemptDeriveBufferedImageFromBytes( this, library, entries, fill); return decodedImage; } } // finally push the bytes though the common image processor to try // and build a a Buffered image. try { decodedImage = ImageUtility.makeImageWithRasterFromBytes( colourSpace, fill, width, height, colorSpaceCompCount, bitsPerComponent, imageMask, decode, sMaskImage, maskImage, maskMinRGB, maskMaxRGB, maskMinIndex, maskMaxIndex, data, dataLength); // ImageUtility.displayImage(decodedImage, pObjectReference.toString()); if (decodedImage != null) { return decodedImage; } } catch (Exception e) { logger.log(Level.FINE, "Error building image raster.", e); } } // Fallback image cod the will use pixel primitives to build out the image. if (decodedImage == null) { byte[] data = getDecodedStreamBytes( width * height * colourSpace.getNumComponents() * bitsPerComponent / 8); // decodes the image stream and returns an image object. Legacy fallback // code, should never get here, but there are always corner cases. . decodedImage = parseImage( width, height, colourSpace, imageMask, fill, bitsPerComponent, decode, data); } // ImageUtility.displayImage(decodedImage, pObjectReference.toString()); if (imageMask) { decodedImage = ImageUtility.applyExplicitMask(decodedImage, fill); } // apply common mask and sMask processing if (sMaskImage != null) { decodedImage = ImageUtility.applyExplicitSMask(decodedImage, sMaskImage); } if (maskImage != null) { decodedImage = ImageUtility.applyExplicitMask(decodedImage, maskImage); } // ImageUtility.displayImage(decodedImage, pObjectReference.toString()); // with little luck the image is ready for viewing. return decodedImage; } /** * The DCTDecode filter decodes grayscale or color image data that has been * encoded in the JPEG baseline format. Because DCTDecode only deals * with images, the instance of image is update instead of decoded * stream. * * @return buffered images representation of the decoded JPEG data. Null * if the image could not be properly decoded. */ private BufferedImage dctDecode( int width, int height, PColorSpace colourSpace, int bitspercomponent, float[] decode) { // BIS's buffer size should be equal to mark() size, and greater than data size (below) InputStream input = getDecodedByteArrayInputStream(); // Used to just read 1000, but found a PDF that included thumbnails first final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048; BufferedInputStream bufferedInput = new BufferedInputStream( input, MAX_BYTES_TO_READ_FOR_ENCODING); bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING); // We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong // Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA // What does work though, is to look into the JPEG headers themself, via getJPEGEncoding() int jpegEncoding = ImageUtility.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr; try { byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING]; int dataRead = bufferedInput.read(data); bufferedInput.reset(); if (dataRead > 0) jpegEncoding = ImageUtility.getJPEGEncoding(data, dataRead); } catch (IOException ioe) { logger.log(Level.FINE, "Problem determining JPEG type: ", ioe); } if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegEncoding=" + ImageUtility.JPEG_ENC_NAMES[jpegEncoding]); BufferedImage tmpImage = null; if (tmpImage == null) { try { JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput); //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); Raster r = imageDecoder.decodeAsRaster(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); if (jpegEncoding == ImageUtility.JPEG_ENC_RGB && bitspercomponent == 8) { ImageUtility.alterRasterRGB2PColorSpace(wr, colourSpace); tmpImage = ImageUtility.makeRGBtoRGBABuffer(wr, width, height); } else if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCbCr && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterYCbCr2RGBA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { // YCCK to RGB works better if an CMYK intermediate is used, but slower. ImageUtility.alterRasterYCCK2CMYK(wr, decode); - tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); + tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr); } else if (jpegEncoding == ImageUtility.JPEG_ENC_GRAY && bitspercomponent == 8) { // In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core) // In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core) // Avoid converting images that are already likely gray. if (colourSpace != null && !(colourSpace instanceof DeviceGray) && !(colourSpace instanceof ICCBased) && !(colourSpace instanceof Indexed)) { - tmpImage = ImageUtility.makeRGBBufferedImage(wr, colourSpace); + tmpImage = ImageUtility.makeRGBBufferedImage(wr, decode, colourSpace); } else { tmpImage = ImageUtility.makeGrayBufferedImage(wr); } } else { //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() == com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA"); // YCbCrA, which is slightly different than YCCK ImageUtility.alterRasterYCbCrA2RGBA(wr); tmpImage = ImageUtility.makeRGBABufferedImage(wr); } else { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr"); ImageUtility.alterRasterYCbCr2RGBA(wr, decode); tmpImage = ImageUtility.makeRGBBufferedImage(wr); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e); } if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder"); } } try { bufferedInput.close(); } catch (IOException e) { logger.log(Level.FINE, "Error closing image stream.", e); } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() JAI"); Object javax_media_jai_RenderedOp_op = null; try { // Have to reget the data input = getDecodedByteArrayInputStream(); /* com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true ); ParameterBlock pb = new ParameterBlock(); pb.add( s ); javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb ); */ Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream"); Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE); Object com_sun_media_jai_codec_SeekableStream_s = ssWrapInputStream.invoke(null, input, Boolean.TRUE); ParameterBlock pb = new ParameterBlock(); pb.add(com_sun_media_jai_codec_SeekableStream_s); Class jaiClass = Class.forName("javax.media.jai.JAI"); Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class); javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb); } catch (Exception e) { logger.warning("Could not load JAI"); } if (javax_media_jai_RenderedOp_op != null) { if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { /* * With or without alterRasterCMYK2BGRA(), give blank image Raster r = op.copyData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterCMYK2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = img; */ } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { /* * This way, with or without alterRasterYCbCrA2BGRA(), give blank image Raster r = op.getData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterYCbCrA2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = img; */ } else { //System.out.println("Stream.dctDecode() Other"); /* tmpImage = op.getAsBufferedImage(); */ Class roClass = Class.forName("javax.media.jai.RenderedOp"); Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage"); tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op); if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_JAI"); } } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e); } try { input.close(); } catch (IOException e) { logger.log(Level.FINE, "Problem closing image stream. ", e); } } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() Toolkit"); byte[] data = getDecodedStreamBytes(width * height * colourSpace.getNumComponents() * bitspercomponent / 8); if (data != null) { Image img = Toolkit.getDefaultToolkit().createImage(data); if (img != null) { tmpImage = ImageUtility.makeRGBABufferedImageFromImage(img); if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage"); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e); } } return tmpImage; } /** * Utility method to decode JBig2 images. * * @param width width of image * @param height height of image * @return buffered image of decoded jbig2 image stream. Null if an error * occured during decode. */ private BufferedImage jbig2Decode(int width, int height, PColorSpace colourSpace, int bitspercomponent) { BufferedImage tmpImage = null; try { Class jbig2DecoderClass = Class.forName("org.jpedal.jbig2.JBIG2Decoder"); // create instance of decoder Constructor jbig2DecoderClassConstructor = jbig2DecoderClass.getDeclaredConstructor(); Object jbig2Decoder = jbig2DecoderClassConstructor.newInstance(); // get the decode params form the stream HashMap decodeParms = library.getDictionary(entries, DECODEPARMS_KEY); if (decodeParms != null) { Stream globalsStream = null; Object jbigGlobals = library.getObject(decodeParms, JBIG2GLOBALS_KEY); if (jbigGlobals instanceof Stream) { globalsStream = (Stream) jbigGlobals; } if (globalsStream != null) { byte[] globals = globalsStream.getDecodedStreamBytes(0); if (globals != null && globals.length > 0) { // invoked ecoder.setGlobalData(globals); Class partypes[] = new Class[1]; partypes[0] = byte[].class; Object arglist[] = new Object[1]; arglist[0] = globals; Method setGlobalData = jbig2DecoderClass.getMethod("setGlobalData", partypes); setGlobalData.invoke(jbig2Decoder, arglist); } } } // decode the data stream, decoder.decodeJBIG2(data); byte[] data = getDecodedStreamBytes( width * height * colourSpace.getNumComponents() * bitspercomponent / 8); Class argTypes[] = new Class[]{byte[].class}; Object arglist[] = new Object[]{data}; Method decodeJBIG2 = jbig2DecoderClass.getMethod("decodeJBIG2", argTypes); decodeJBIG2.invoke(jbig2Decoder, arglist); // From decoding, memory usage increases more than (width*height/8), // due to intermediate JBIG2Bitmap objects, used to build the final // one, still hanging around. Cleanup intermediate data-structures. // decoder.cleanupPostDecode(); Method cleanupPostDecode = jbig2DecoderClass.getMethod("cleanupPostDecode"); cleanupPostDecode.invoke(jbig2Decoder); // final try an fetch the image. tmpImage = decoder.getPageAsBufferedImage(0); argTypes = new Class[]{Integer.TYPE}; arglist = new Object[]{0}; Method getPageAsBufferedImage = jbig2DecoderClass.getMethod("getPageAsBufferedImage", argTypes); tmpImage = (BufferedImage) getPageAsBufferedImage.invoke(jbig2Decoder, arglist); } catch (ClassNotFoundException e) { logger.warning("JBIG2 image library could not be found"); } catch (Exception e) { logger.log(Level.WARNING, "Problem loading JBIG2 image: ", e); } // apply the fill colour and alpha if masking is enabled. return tmpImage; } /** * Utility method to decode JPEG2000 images. * * @param width width of image. * @param height height of image. * @param colourSpace colour space to apply to image. * @param bitsPerComponent bits used to represent a colour * @return buffered image of the jpeg2000 image stream. Null if a problem * occurred during the decode. */ private BufferedImage jpxDecode(int width, int height, PColorSpace colourSpace, int bitsPerComponent, float[] decode) { BufferedImage tmpImage = null; try { // Verify that ImageIO can read JPEG2000 Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("JPEG2000"); if (!iterator.hasNext()) { logger.info( "ImageIO missing required plug-in to read JPEG 2000 images. " + "You can download the JAI ImageIO Tools from: " + "https://jai-imageio.dev.java.net/"); return null; } // decode the image. byte[] data = getDecodedStreamBytes( width * height * colourSpace.getNumComponents() * bitsPerComponent / 8); ImageInputStream imageInputStream = ImageIO.createImageInputStream( new ByteArrayInputStream(data)); tmpImage = ImageIO.read(imageInputStream); // check for an instance of ICCBased, we don't currently support // this colour mode well so we'll used the alternative colour if (colourSpace instanceof ICCBased) { ICCBased iccBased = (ICCBased) colourSpace; if (iccBased.getAlternate() != null) { // set the alternate as the current colourSpace = iccBased.getAlternate(); } // try to process the ICC colour space else { ColorSpace cs = iccBased.getColorSpace(); ColorConvertOp cco = new ColorConvertOp(cs, null); tmpImage = cco.filter(tmpImage, null); } } // apply respective colour models to the JPEG2000 image. if (colourSpace instanceof DeviceRGB && bitsPerComponent == 8) { WritableRaster wr = tmpImage.getRaster(); ImageUtility.alterRasterRGB2PColorSpace(wr, colourSpace); tmpImage = ImageUtility.makeRGBBufferedImage(wr); } else if (colourSpace instanceof DeviceCMYK && bitsPerComponent == 8) { WritableRaster wr = tmpImage.getRaster(); tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); return tmpImage; } else if ((colourSpace instanceof DeviceGray) && bitsPerComponent == 8) { WritableRaster wr = tmpImage.getRaster(); tmpImage = ImageUtility.makeGrayBufferedImage(wr); } else if (colourSpace instanceof Separation) { WritableRaster wr = tmpImage.getRaster(); ImageUtility.alterRasterY2Gray(wr, decode); } else if (colourSpace instanceof Indexed) { tmpImage = ImageUtility.applyIndexColourModel(tmpImage, width, height, colourSpace, bitsPerComponent); } } catch (IOException e) { logger.log(Level.FINE, "Problem loading JPEG2000 image: ", e); } return tmpImage; } /** * CCITT fax decode algorithm, decodes the stream into a valid image * stream that can be used to create a BufferedImage. * * @param width of image * @param height height of image. * @return decoded stream bytes. */ private byte[] ccittFaxDecode(byte[] streamData, int width, int height) { HashMap decodeParms = library.getDictionary(entries, DECODEPARMS_KEY); float k = library.getFloat(decodeParms, K_KEY); // default value is always false boolean blackIs1 = getBlackIs1(library, decodeParms); // get value of key if it is available. boolean encodedByteAlign = false; Object encodedByteAlignObject = library.getObject(decodeParms, ENCODEDBYTEALIGN_KEY); if (encodedByteAlignObject instanceof Boolean) { encodedByteAlign = (Boolean) encodedByteAlignObject; } int columns = library.getInt(decodeParms, COLUMNS_KEY); int rows = library.getInt(decodeParms, ROWS_KEY); if (columns == 0) { columns = width; } if (rows == 0) { rows = height; } int size = rows * ((columns + 7) >> 3); byte[] decodedStreamData = new byte[size]; CCITTFaxDecoder decoder = new CCITTFaxDecoder(1, columns, rows); decoder.setAlign(encodedByteAlign); // pick three three possible fax encoding. try { if (k == 0) { decoder.decodeT41D(decodedStreamData, streamData, 0, rows); } else if (k > 0) { decoder.decodeT42D(decodedStreamData, streamData, 0, rows); } else if (k < 0) { decoder.decodeT6(decodedStreamData, streamData, 0, rows); } } catch (Exception e) { logger.warning("Error decoding CCITTFax image k: " + k); // IText 5.03 doesn't correctly assign a k value for the deocde, // as result we can try one more time using the T6. decoder.decodeT6(decodedStreamData, streamData, 0, rows); } // check the black is value flag, no one likes inverted colours. if (!blackIs1) { // toggle the byte data invert colour, not bit operand. for (int i = 0; i < decodedStreamData.length; i++) { decodedStreamData[i] = (byte) ~decodedStreamData[i]; } } return decodedStreamData; } /** * Parses the image stream and creates a Java Images object based on the * the given stream and the supporting paramaters. * * @param width dimension of new image * @param height dimension of new image * @param colorSpace colour space of image * @param imageMask true if the image has a imageMask, false otherwise * @param bitsPerColour number of bits used in a colour * @param decode Decode attribute values from PObject * @return valid java image from the PDF stream */ private BufferedImage parseImage( int width, int height, PColorSpace colorSpace, boolean imageMask, Color fill, int bitsPerColour, float[] decode, byte[] baCCITTFaxData) { if (Tagger.tagging) Tagger.tagImage("HandledBy=ParseImage"); // store for manipulating bits in image int[] imageBits = new int[width]; // RGB value for colour used as fill for image int fillRGB = fill.getRGB(); // Number of colour components in image, should be 3 for RGB or 4 // for ARGB. int colorSpaceCompCount = colorSpace.getNumComponents(); boolean isDeviceRGB = colorSpace instanceof DeviceRGB; boolean isDeviceGray = colorSpace instanceof DeviceGray; // Max value used to represent a colour, usually 255, min is 0 int maxColourValue = ((1 << bitsPerColour) - 1); int f[] = new int[colorSpaceCompCount]; float ff[] = new float[colorSpaceCompCount]; // image mask from float imageMaskValue = decode[0]; // Create the memory hole where where the buffered image will be writen // too, bit by painfull bit. BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // create the buffer and get the first series of bytes from the cached // stream BitStream in; if (baCCITTFaxData != null) { in = new BitStream(new ByteArrayInputStream(baCCITTFaxData)); } else { InputStream dataInput = getDecodedByteArrayInputStream(); if (dataInput == null) return null; in = new BitStream(dataInput); } try { // Start encoding bit stream into an image, we work one pixel at // a time, and grap the need bit information for the images // colour space and bits per colour for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // if image has mask apply it if (imageMask) { int bit = in.getBits(bitsPerColour); bit = (bit == imageMaskValue) ? fillRGB : 0x00000000; imageBits[x] = bit; } // other wise start colour bit parsing else { // set some default values int red = 255; int blue = 255; int green = 255; int alpha = 255; // indexed colour if (colorSpaceCompCount == 1) { // get value used for this bit int bit = in.getBits(bitsPerColour); // check decode array if a colour inversion is needed if (decode != null) { // if index 0 > index 1 then we have a need for ainversion if (decode[0] > decode[1]) { bit = (bit == maxColourValue) ? 0x00000000 : maxColourValue; } } if (isDeviceGray) { if (bitsPerColour == 1) bit = ImageUtility.GRAY_1_BIT_INDEX_TO_RGB[bit]; else if (bitsPerColour == 2) bit = ImageUtility.GRAY_2_BIT_INDEX_TO_RGB[bit]; else if (bitsPerColour == 4) bit = ImageUtility.GRAY_4_BIT_INDEX_TO_RGB[bit]; else if (bitsPerColour == 8) { bit = ((bit << 24) | (bit << 16) | (bit << 8) | bit); } imageBits[x] = bit; } else { f[0] = bit; colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue); Color color = colorSpace.getColor(ff); imageBits[x] = color.getRGB(); } } // normal RGB colour else if (colorSpaceCompCount == 3) { // We can have an ICCBased color space that has 3 components, // but where we can't assume it's RGB. // But, when it is DeviceRGB, we don't want the performance hit // of converting the pixels via the PColorSpace, so we'll // break this into the two cases if (isDeviceRGB) { red = in.getBits(bitsPerColour); green = in.getBits(bitsPerColour); blue = in.getBits(bitsPerColour); // combine the colour together imageBits[x] = (alpha << 24) | (red << 16) | (green << 8) | blue; } else { for (int i = 0; i < colorSpaceCompCount; i++) { f[i] = in.getBits(bitsPerColour); } PColorSpace.reverseInPlace(f); colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue); Color color = colorSpace.getColor(ff); imageBits[x] = color.getRGB(); } } // normal aRGB colour, this could use some more // work for optimizing. else if (colorSpaceCompCount == 4) { for (int i = 0; i < colorSpaceCompCount; i++) { f[i] = in.getBits(bitsPerColour); // apply decode if (decode[0] > decode[1]) { f[i] = maxColourValue - f[i]; } } PColorSpace.reverseInPlace(f); colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue); Color color = colorSpace.getColor(ff); imageBits[x] = color.getRGB(); } // else just set pixel with the default values else { // compine the colour together imageBits[x] = (alpha << 24) | (red << 16) | (green << 8) | blue; } } } // Assign the new bits for this pixel bim.setRGB(0, y, width, 1, imageBits, 0, 1); } // final clean up. in.close(); } catch (IOException e) { logger.log(Level.FINE, "Error parsing image.", e); } return bim; } /** * If BlackIs1 was not specified, then return null, instead of the * default value of false, so we can tell if it was given or not */ public boolean getBlackIs1(Library library, HashMap decodeParmsDictionary) { Object blackIs1Obj = library.getObject(decodeParmsDictionary, BLACKIS1_KEY); if (blackIs1Obj != null) { if (blackIs1Obj instanceof Boolean) { return (Boolean) blackIs1Obj; } else if (blackIs1Obj instanceof String) { String blackIs1String = (String) blackIs1Obj; if (blackIs1String.equalsIgnoreCase("true")) return true; else if (blackIs1String.equalsIgnoreCase("t")) return true; else if (blackIs1String.equals("1")) return true; else if (blackIs1String.equalsIgnoreCase("false")) return false; else if (blackIs1String.equalsIgnoreCase("f")) return false; else if (blackIs1String.equals("0")) return false; } } return false; } private boolean containsFilter(String[] searchFilterNames) { List filterNames = getFilterNames(); if (filterNames == null) return false; for (Object filterName1 : filterNames) { String filterName = filterName1.toString(); for (String search : searchFilterNames) { if (search.equals(filterName)) { return true; } } } return false; } /** * Does the image have an ImageMask. */ public boolean isImageMask() { return library.getBoolean(entries, IMAGEMASK_KEY); } private boolean shouldUseCCITTFaxDecode() { return containsFilter(CCITTFAX_DECODE_FILTERS); } private boolean shouldUseDCTDecode() { return containsFilter(DCT_DECODE_FILTERS); } private boolean shouldUseJBIG2Decode() { return containsFilter(JBIG2_DECODE_FILTERS); } private boolean shouldUseJPXDecode() { return containsFilter(JPX_DECODE_FILTERS); } /** * Used to enable/disable the loading of CCITTFax images using JAI library. * This method can be used in place of the system property * org.icepdf.core.ccittfax.jai . * * @param enable eanb */ public static void forceJaiCcittFax(boolean enable) { forceJaiccittfax = enable; } /** * Return a string description of the object. Primarily used for debugging. */ public String toString() { StringBuilder sb = new StringBuilder(64); sb.append("Image stream= "); sb.append(entries); if (getPObjectReference() != null) { sb.append(" "); sb.append(getPObjectReference()); } return sb.toString(); } }
false
true
private BufferedImage dctDecode( int width, int height, PColorSpace colourSpace, int bitspercomponent, float[] decode) { // BIS's buffer size should be equal to mark() size, and greater than data size (below) InputStream input = getDecodedByteArrayInputStream(); // Used to just read 1000, but found a PDF that included thumbnails first final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048; BufferedInputStream bufferedInput = new BufferedInputStream( input, MAX_BYTES_TO_READ_FOR_ENCODING); bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING); // We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong // Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA // What does work though, is to look into the JPEG headers themself, via getJPEGEncoding() int jpegEncoding = ImageUtility.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr; try { byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING]; int dataRead = bufferedInput.read(data); bufferedInput.reset(); if (dataRead > 0) jpegEncoding = ImageUtility.getJPEGEncoding(data, dataRead); } catch (IOException ioe) { logger.log(Level.FINE, "Problem determining JPEG type: ", ioe); } if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegEncoding=" + ImageUtility.JPEG_ENC_NAMES[jpegEncoding]); BufferedImage tmpImage = null; if (tmpImage == null) { try { JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput); //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); Raster r = imageDecoder.decodeAsRaster(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); if (jpegEncoding == ImageUtility.JPEG_ENC_RGB && bitspercomponent == 8) { ImageUtility.alterRasterRGB2PColorSpace(wr, colourSpace); tmpImage = ImageUtility.makeRGBtoRGBABuffer(wr, width, height); } else if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCbCr && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterYCbCr2RGBA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { // YCCK to RGB works better if an CMYK intermediate is used, but slower. ImageUtility.alterRasterYCCK2CMYK(wr, decode); tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_GRAY && bitspercomponent == 8) { // In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core) // In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core) // Avoid converting images that are already likely gray. if (colourSpace != null && !(colourSpace instanceof DeviceGray) && !(colourSpace instanceof ICCBased) && !(colourSpace instanceof Indexed)) { tmpImage = ImageUtility.makeRGBBufferedImage(wr, colourSpace); } else { tmpImage = ImageUtility.makeGrayBufferedImage(wr); } } else { //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() == com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA"); // YCbCrA, which is slightly different than YCCK ImageUtility.alterRasterYCbCrA2RGBA(wr); tmpImage = ImageUtility.makeRGBABufferedImage(wr); } else { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr"); ImageUtility.alterRasterYCbCr2RGBA(wr, decode); tmpImage = ImageUtility.makeRGBBufferedImage(wr); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e); } if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder"); } } try { bufferedInput.close(); } catch (IOException e) { logger.log(Level.FINE, "Error closing image stream.", e); } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() JAI"); Object javax_media_jai_RenderedOp_op = null; try { // Have to reget the data input = getDecodedByteArrayInputStream(); /* com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true ); ParameterBlock pb = new ParameterBlock(); pb.add( s ); javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb ); */ Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream"); Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE); Object com_sun_media_jai_codec_SeekableStream_s = ssWrapInputStream.invoke(null, input, Boolean.TRUE); ParameterBlock pb = new ParameterBlock(); pb.add(com_sun_media_jai_codec_SeekableStream_s); Class jaiClass = Class.forName("javax.media.jai.JAI"); Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class); javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb); } catch (Exception e) { logger.warning("Could not load JAI"); } if (javax_media_jai_RenderedOp_op != null) { if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { /* * With or without alterRasterCMYK2BGRA(), give blank image Raster r = op.copyData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterCMYK2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = img; */ } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { /* * This way, with or without alterRasterYCbCrA2BGRA(), give blank image Raster r = op.getData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterYCbCrA2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = img; */ } else { //System.out.println("Stream.dctDecode() Other"); /* tmpImage = op.getAsBufferedImage(); */ Class roClass = Class.forName("javax.media.jai.RenderedOp"); Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage"); tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op); if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_JAI"); } } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e); } try { input.close(); } catch (IOException e) { logger.log(Level.FINE, "Problem closing image stream. ", e); } } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() Toolkit"); byte[] data = getDecodedStreamBytes(width * height * colourSpace.getNumComponents() * bitspercomponent / 8); if (data != null) { Image img = Toolkit.getDefaultToolkit().createImage(data); if (img != null) { tmpImage = ImageUtility.makeRGBABufferedImageFromImage(img); if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage"); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e); } } return tmpImage; }
private BufferedImage dctDecode( int width, int height, PColorSpace colourSpace, int bitspercomponent, float[] decode) { // BIS's buffer size should be equal to mark() size, and greater than data size (below) InputStream input = getDecodedByteArrayInputStream(); // Used to just read 1000, but found a PDF that included thumbnails first final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048; BufferedInputStream bufferedInput = new BufferedInputStream( input, MAX_BYTES_TO_READ_FOR_ENCODING); bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING); // We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong // Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA // What does work though, is to look into the JPEG headers themself, via getJPEGEncoding() int jpegEncoding = ImageUtility.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr; try { byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING]; int dataRead = bufferedInput.read(data); bufferedInput.reset(); if (dataRead > 0) jpegEncoding = ImageUtility.getJPEGEncoding(data, dataRead); } catch (IOException ioe) { logger.log(Level.FINE, "Problem determining JPEG type: ", ioe); } if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegEncoding=" + ImageUtility.JPEG_ENC_NAMES[jpegEncoding]); BufferedImage tmpImage = null; if (tmpImage == null) { try { JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput); //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); Raster r = imageDecoder.decodeAsRaster(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); if (jpegEncoding == ImageUtility.JPEG_ENC_RGB && bitspercomponent == 8) { ImageUtility.alterRasterRGB2PColorSpace(wr, colourSpace); tmpImage = ImageUtility.makeRGBtoRGBABuffer(wr, width, height); } else if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCbCr && bitspercomponent == 8) { tmpImage = ImageUtility.alterRasterYCbCr2RGBA(wr, decode); } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { // YCCK to RGB works better if an CMYK intermediate is used, but slower. ImageUtility.alterRasterYCCK2CMYK(wr, decode); tmpImage = ImageUtility.alterRasterCMYK2BGRA(wr); } else if (jpegEncoding == ImageUtility.JPEG_ENC_GRAY && bitspercomponent == 8) { // In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core) // In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core) // Avoid converting images that are already likely gray. if (colourSpace != null && !(colourSpace instanceof DeviceGray) && !(colourSpace instanceof ICCBased) && !(colourSpace instanceof Indexed)) { tmpImage = ImageUtility.makeRGBBufferedImage(wr, decode, colourSpace); } else { tmpImage = ImageUtility.makeGrayBufferedImage(wr); } } else { //System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID()); if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() == com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA"); // YCbCrA, which is slightly different than YCCK ImageUtility.alterRasterYCbCrA2RGBA(wr); tmpImage = ImageUtility.makeRGBABufferedImage(wr); } else { if (Tagger.tagging) Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr"); ImageUtility.alterRasterYCbCr2RGBA(wr, decode); tmpImage = ImageUtility.makeRGBBufferedImage(wr); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e); } if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder"); } } try { bufferedInput.close(); } catch (IOException e) { logger.log(Level.FINE, "Error closing image stream.", e); } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() JAI"); Object javax_media_jai_RenderedOp_op = null; try { // Have to reget the data input = getDecodedByteArrayInputStream(); /* com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true ); ParameterBlock pb = new ParameterBlock(); pb.add( s ); javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb ); */ Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream"); Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE); Object com_sun_media_jai_codec_SeekableStream_s = ssWrapInputStream.invoke(null, input, Boolean.TRUE); ParameterBlock pb = new ParameterBlock(); pb.add(com_sun_media_jai_codec_SeekableStream_s); Class jaiClass = Class.forName("javax.media.jai.JAI"); Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class); javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb); } catch (Exception e) { logger.warning("Could not load JAI"); } if (javax_media_jai_RenderedOp_op != null) { if (jpegEncoding == ImageUtility.JPEG_ENC_CMYK && bitspercomponent == 8) { /* * With or without alterRasterCMYK2BGRA(), give blank image Raster r = op.copyData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterCMYK2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterCMYK2BGRA( wr ); tmpImage = img; */ } else if (jpegEncoding == ImageUtility.JPEG_ENC_YCCK && bitspercomponent == 8) { /* * This way, with or without alterRasterYCbCrA2BGRA(), give blank image Raster r = op.getData(); WritableRaster wr = (r instanceof WritableRaster) ? (WritableRaster) r : r.createCompatibleWritableRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = makeRGBABufferedImage( wr ); */ /* * With alterRasterYCbCrA2BGRA() colors gibbled, without is blank * Slower, uses more memory, than JPEGImageDecoder BufferedImage img = op.getAsBufferedImage(); WritableRaster wr = img.getRaster(); alterRasterYCbCrA2BGRA( wr ); tmpImage = img; */ } else { //System.out.println("Stream.dctDecode() Other"); /* tmpImage = op.getAsBufferedImage(); */ Class roClass = Class.forName("javax.media.jai.RenderedOp"); Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage"); tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op); if (tmpImage != null) { if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_JAI"); } } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e); } try { input.close(); } catch (IOException e) { logger.log(Level.FINE, "Problem closing image stream. ", e); } } if (tmpImage == null) { try { //System.out.println("Stream.dctDecode() Toolkit"); byte[] data = getDecodedStreamBytes(width * height * colourSpace.getNumComponents() * bitspercomponent / 8); if (data != null) { Image img = Toolkit.getDefaultToolkit().createImage(data); if (img != null) { tmpImage = ImageUtility.makeRGBABufferedImageFromImage(img); if (Tagger.tagging) Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage"); } } } catch (Exception e) { logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e); } } return tmpImage; }
diff --git a/plugin/src/objective/Startup.java b/plugin/src/objective/Startup.java index 3b51431..9688213 100644 --- a/plugin/src/objective/Startup.java +++ b/plugin/src/objective/Startup.java @@ -1,43 +1,43 @@ package objective; import objective.ng.GotoMethodServer; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.IStartup; @SuppressWarnings("restriction") public class Startup implements IStartup { @Override public void earlyStartup() { JavaPlugin javaPlugin = JavaPlugin.getDefault(); IPreferenceStore preferences = javaPlugin.getPreferenceStore(); preferences.setValue("escapeStrings", true); configureMapEntryFormatters(); startGotoMethodServer(); } private void configureMapEntryFormatters() { IPreferenceStore debugPrefs = JDIDebugUIPlugin.getDefault().getPreferenceStore(); debugPrefs.setValue("org.eclipse.jdt.debug.ui.show_details","INLINE_FORMATTERS"); String previousPref = debugPrefs.getString("org.eclipse.jdt.debug.ui.detail_formatters"); - String hashmapDetail = "java.util.HashMap$Entry,getKey()+\\\"\\\\=\\\"+getValue(),1"; + String hashmapDetail = "java.util.HashMap$Entry,return getKey()+\\\"\\\\=\\\"+getValue();,1"; previousPref = previousPref.replace(hashmapDetail, ""); debugPrefs.setValue("org.eclipse.jdt.debug.ui.detail_formatters", previousPref+"," + hashmapDetail); } private void startGotoMethodServer() { new GotoMethodServer().start(); } }
true
true
private void configureMapEntryFormatters() { IPreferenceStore debugPrefs = JDIDebugUIPlugin.getDefault().getPreferenceStore(); debugPrefs.setValue("org.eclipse.jdt.debug.ui.show_details","INLINE_FORMATTERS"); String previousPref = debugPrefs.getString("org.eclipse.jdt.debug.ui.detail_formatters"); String hashmapDetail = "java.util.HashMap$Entry,getKey()+\\\"\\\\=\\\"+getValue(),1"; previousPref = previousPref.replace(hashmapDetail, ""); debugPrefs.setValue("org.eclipse.jdt.debug.ui.detail_formatters", previousPref+"," + hashmapDetail); }
private void configureMapEntryFormatters() { IPreferenceStore debugPrefs = JDIDebugUIPlugin.getDefault().getPreferenceStore(); debugPrefs.setValue("org.eclipse.jdt.debug.ui.show_details","INLINE_FORMATTERS"); String previousPref = debugPrefs.getString("org.eclipse.jdt.debug.ui.detail_formatters"); String hashmapDetail = "java.util.HashMap$Entry,return getKey()+\\\"\\\\=\\\"+getValue();,1"; previousPref = previousPref.replace(hashmapDetail, ""); debugPrefs.setValue("org.eclipse.jdt.debug.ui.detail_formatters", previousPref+"," + hashmapDetail); }
diff --git a/src/test/java/pages/GooglePage.java b/src/test/java/pages/GooglePage.java index 62f3c23..13fc249 100644 --- a/src/test/java/pages/GooglePage.java +++ b/src/test/java/pages/GooglePage.java @@ -1,35 +1,35 @@ package pages; import helper.WebDriverHelper; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; public class GooglePage { private WebDriverHelper webDriverHelper = WebDriverHelper.getInstance(); @FindBy(id = "gbqfq") private WebElement searchInputTextBox; @FindBy(id = "gbqfb") private WebElement searchButton; public void openHomepage() { this.webDriverHelper.openUrl("http://www.google.com"); } public void searchFor(String searchItem) { webDriverHelper.enterTextInput(searchInputTextBox, "testing"); searchButton.click(); } public String getResultHeadingByIndex(int index) { WebElement resultsList = webDriverHelper.findElement(By.id("rso")); List<WebElement> individualResults = resultsList.findElements(By.cssSelector("li")); - WebElement firstResult = individualResults.get(index); - WebElement resultHeading = firstResult.findElement(By.cssSelector("h3")); + WebElement result = individualResults.get(index); + WebElement resultHeading = result.findElement(By.cssSelector("h3")); return resultHeading.getText(); } }
true
true
public String getResultHeadingByIndex(int index) { WebElement resultsList = webDriverHelper.findElement(By.id("rso")); List<WebElement> individualResults = resultsList.findElements(By.cssSelector("li")); WebElement firstResult = individualResults.get(index); WebElement resultHeading = firstResult.findElement(By.cssSelector("h3")); return resultHeading.getText(); }
public String getResultHeadingByIndex(int index) { WebElement resultsList = webDriverHelper.findElement(By.id("rso")); List<WebElement> individualResults = resultsList.findElements(By.cssSelector("li")); WebElement result = individualResults.get(index); WebElement resultHeading = result.findElement(By.cssSelector("h3")); return resultHeading.getText(); }
diff --git a/rdt/org.eclipse.ptp.rdt.sync.ui/src/org/eclipse/ptp/rdt/sync/ui/wizards/NewRemoteSyncProjectWizardPage.java b/rdt/org.eclipse.ptp.rdt.sync.ui/src/org/eclipse/ptp/rdt/sync/ui/wizards/NewRemoteSyncProjectWizardPage.java index 68f283972..af4b85081 100644 --- a/rdt/org.eclipse.ptp.rdt.sync.ui/src/org/eclipse/ptp/rdt/sync/ui/wizards/NewRemoteSyncProjectWizardPage.java +++ b/rdt/org.eclipse.ptp.rdt.sync.ui/src/org/eclipse/ptp/rdt/sync/ui/wizards/NewRemoteSyncProjectWizardPage.java @@ -1,345 +1,345 @@ /******************************************************************************* * Copyright (c) 2008, 2010 IBM Corporation 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: * IBM - Initial API and implementation * Roland Schulz, University of Tennessee *******************************************************************************/ package org.eclipse.ptp.rdt.sync.ui.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CProjectNature; import org.eclipse.cdt.managedbuilder.ui.wizards.MBSCustomPage; import org.eclipse.cdt.managedbuilder.ui.wizards.MBSCustomPageManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ptp.rdt.sync.ui.ISynchronizeParticipant; import org.eclipse.ptp.rdt.sync.ui.ISynchronizeParticipantDescriptor; import org.eclipse.ptp.rdt.sync.ui.SynchronizeParticipantRegistry; import org.eclipse.ptp.rdt.sync.ui.messages.Messages; import org.eclipse.ptp.services.core.IService; import org.eclipse.ptp.services.core.ServiceModelManager; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; /** * * <strong>EXPERIMENTAL</strong>. This class or interface has been added as part * of a work in progress. There is no guarantee that this API will work or that * it will remain the same. Please do not use this API without consulting with * the RDT team. * * */ public class NewRemoteSyncProjectWizardPage extends MBSCustomPage { public static final String REMOTE_SYNC_WIZARD_PAGE_ID = "org.eclipse.ptp.rdt.sync.ui.remoteSyncWizardPage"; //$NON-NLS-1$ public static final String SERVICE_PROVIDER_PROPERTY = "org.eclipse.ptp.rdt.sync.ui.remoteSyncWizardPage.serviceProvider"; //$NON-NLS-1$ private boolean fbVisited; private String fTitle; private String fDescription; private ImageDescriptor fImageDescriptor; private Image fImage; private ISynchronizeParticipantDescriptor fSelectedProvider; private Control pageControl; private Combo fProviderCombo; private Composite fProviderArea; private StackLayout fProviderStack; private final List<Composite> fProviderControls = new ArrayList<Composite>(); private final Map<Integer, ISynchronizeParticipantDescriptor> fComboIndexToDescriptorMap = new HashMap<Integer, ISynchronizeParticipantDescriptor>(); public NewRemoteSyncProjectWizardPage(String pageID) { super(pageID); } /** * Find available remote services and service providers for a given project * * If project is null, the C and C++ natures are used to determine which * services are available */ protected Set<IService> getContributedServices() { ServiceModelManager smm = ServiceModelManager.getInstance(); Set<IService> cppServices = smm.getServices(CCProjectNature.CC_NATURE_ID); Set<IService> cServices = smm.getServices(CProjectNature.C_NATURE_ID); Set<IService> allApplicableServices = new LinkedHashSet<IService>(); allApplicableServices.addAll(cppServices); allApplicableServices.addAll(cServices); return allApplicableServices; } /** * */ public NewRemoteSyncProjectWizardPage() { this(REMOTE_SYNC_WIZARD_PAGE_ID); } /* * (non-Javadoc) * * @see * org.eclipse.cdt.managedbuilder.ui.wizards.MBSCustomPage#isCustomPageComplete * () */ @Override protected boolean isCustomPageComplete() { return fbVisited; } /* * (non-Javadoc) * * @see org.eclipse.jface.wizard.IWizardPage#getName() */ public String getName() { return Messages.RemoteSyncWizardPage_0; } /* * (non-Javadoc) * * @see * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets * .Composite) */ public void createControl(final Composite parent) { Composite comp = new Composite(parent, SWT.NONE); pageControl = comp; GridLayout layout = new GridLayout(); layout.numColumns = 3; comp.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); comp.setLayoutData(gd); // Label for "Provider:" Label providerLabel = new Label(comp, SWT.LEFT); providerLabel.setText(Messages.NewRemoteSyncProjectWizardPage_syncProvider); // combo for providers fProviderCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY); // set layout to grab horizontal space fProviderCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); gd = new GridData(); gd.horizontalSpan = 2; fProviderCombo.setLayoutData(gd); fProviderCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleProviderSelected(); } }); fProviderArea = new Group(comp, SWT.SHADOW_ETCHED_IN); fProviderStack = new StackLayout(); fProviderArea.setLayout(fProviderStack); GridData providerAreaData = new GridData(SWT.FILL, SWT.FILL, true, true); providerAreaData.horizontalSpan = 3; fProviderArea.setLayoutData(providerAreaData); // populate the combo with a list of providers ISynchronizeParticipantDescriptor[] providers = SynchronizeParticipantRegistry.getDescriptors(); fProviderCombo.add(Messages.NewRemoteSyncProjectWizardPage_selectSyncProvider, 0); for (int k = 0; k < providers.length; k++) { fProviderCombo.add(providers[k].getName(), k + 1); fComboIndexToDescriptorMap.put(k, providers[k]); addProviderControl(providers[k]); } if (providers.length == 1) { fProviderCombo.select(1); handleProviderSelected(); } else { fProviderCombo.select(0); + fSelectedProvider = null; } - fSelectedProvider = null; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#dispose() */ public void dispose() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getControl() */ public Control getControl() { return pageControl; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getDescription() */ public String getDescription() { if (fDescription == null) { fDescription = Messages.RemoteSyncWizardPage_description; } return fDescription; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getErrorMessage() */ public String getErrorMessage() { return null; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getImage() */ public Image getImage() { if (fImage == null && fImageDescriptor != null) { fImage = fImageDescriptor.createImage(); } if (fImage == null && wizard != null) { fImage = wizard.getDefaultPageImage(); } return fImage; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getMessage() */ public String getMessage() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#getTitle() */ public String getTitle() { if (fTitle == null) { fTitle = Messages.RemoteSyncWizardPage_0; } return fTitle; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#performHelp() */ public void performHelp() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * org.eclipse.jface.dialogs.IDialogPage#setDescription(java.lang.String) */ public void setDescription(String description) { fDescription = description; } /* * (non-Javadoc) * * @see * org.eclipse.jface.dialogs.IDialogPage#setImageDescriptor(org.eclipse. * jface.resource.ImageDescriptor) */ public void setImageDescriptor(ImageDescriptor image) { fImageDescriptor = image; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#setTitle(java.lang.String) */ public void setTitle(String title) { fTitle = title; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { if (visible) { fbVisited = true; } } /** * Handle synchronize provider selected. */ private void handleProviderSelected() { int index = fProviderCombo.getSelectionIndex() - 1; if (index >= 0) { fProviderStack.topControl = fProviderControls.get(index); fSelectedProvider = fComboIndexToDescriptorMap.get(index); } else { fProviderStack.topControl = null; fSelectedProvider = null; } fProviderArea.layout(); if (fSelectedProvider != null) { MBSCustomPageManager.addPageProperty(REMOTE_SYNC_WIZARD_PAGE_ID, SERVICE_PROVIDER_PROPERTY, fSelectedProvider.getParticipant()); } else { MBSCustomPageManager.addPageProperty(REMOTE_SYNC_WIZARD_PAGE_ID, SERVICE_PROVIDER_PROPERTY, null); } } private void addProviderControl(ISynchronizeParticipantDescriptor desc) { Composite comp = null; ISynchronizeParticipant part = desc.getParticipant(); if (part != null) { comp = new Composite(fProviderArea, SWT.NONE); comp.setLayout(new GridLayout(1, false)); comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); part.createConfigurationArea(comp, getWizard().getContainer()); } fProviderControls.add(comp); } }
false
true
public void createControl(final Composite parent) { Composite comp = new Composite(parent, SWT.NONE); pageControl = comp; GridLayout layout = new GridLayout(); layout.numColumns = 3; comp.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); comp.setLayoutData(gd); // Label for "Provider:" Label providerLabel = new Label(comp, SWT.LEFT); providerLabel.setText(Messages.NewRemoteSyncProjectWizardPage_syncProvider); // combo for providers fProviderCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY); // set layout to grab horizontal space fProviderCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); gd = new GridData(); gd.horizontalSpan = 2; fProviderCombo.setLayoutData(gd); fProviderCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleProviderSelected(); } }); fProviderArea = new Group(comp, SWT.SHADOW_ETCHED_IN); fProviderStack = new StackLayout(); fProviderArea.setLayout(fProviderStack); GridData providerAreaData = new GridData(SWT.FILL, SWT.FILL, true, true); providerAreaData.horizontalSpan = 3; fProviderArea.setLayoutData(providerAreaData); // populate the combo with a list of providers ISynchronizeParticipantDescriptor[] providers = SynchronizeParticipantRegistry.getDescriptors(); fProviderCombo.add(Messages.NewRemoteSyncProjectWizardPage_selectSyncProvider, 0); for (int k = 0; k < providers.length; k++) { fProviderCombo.add(providers[k].getName(), k + 1); fComboIndexToDescriptorMap.put(k, providers[k]); addProviderControl(providers[k]); } if (providers.length == 1) { fProviderCombo.select(1); handleProviderSelected(); } else { fProviderCombo.select(0); } fSelectedProvider = null; }
public void createControl(final Composite parent) { Composite comp = new Composite(parent, SWT.NONE); pageControl = comp; GridLayout layout = new GridLayout(); layout.numColumns = 3; comp.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); comp.setLayoutData(gd); // Label for "Provider:" Label providerLabel = new Label(comp, SWT.LEFT); providerLabel.setText(Messages.NewRemoteSyncProjectWizardPage_syncProvider); // combo for providers fProviderCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY); // set layout to grab horizontal space fProviderCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); gd = new GridData(); gd.horizontalSpan = 2; fProviderCombo.setLayoutData(gd); fProviderCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleProviderSelected(); } }); fProviderArea = new Group(comp, SWT.SHADOW_ETCHED_IN); fProviderStack = new StackLayout(); fProviderArea.setLayout(fProviderStack); GridData providerAreaData = new GridData(SWT.FILL, SWT.FILL, true, true); providerAreaData.horizontalSpan = 3; fProviderArea.setLayoutData(providerAreaData); // populate the combo with a list of providers ISynchronizeParticipantDescriptor[] providers = SynchronizeParticipantRegistry.getDescriptors(); fProviderCombo.add(Messages.NewRemoteSyncProjectWizardPage_selectSyncProvider, 0); for (int k = 0; k < providers.length; k++) { fProviderCombo.add(providers[k].getName(), k + 1); fComboIndexToDescriptorMap.put(k, providers[k]); addProviderControl(providers[k]); } if (providers.length == 1) { fProviderCombo.select(1); handleProviderSelected(); } else { fProviderCombo.select(0); fSelectedProvider = null; } }
diff --git a/src/main/java/herbstJennrichLehmannRitter/engine/model/impl/AbstractDefenceBuilding.java b/src/main/java/herbstJennrichLehmannRitter/engine/model/impl/AbstractDefenceBuilding.java index edda7d4..1e2b78f 100644 --- a/src/main/java/herbstJennrichLehmannRitter/engine/model/impl/AbstractDefenceBuilding.java +++ b/src/main/java/herbstJennrichLehmannRitter/engine/model/impl/AbstractDefenceBuilding.java @@ -1,43 +1,44 @@ package herbstJennrichLehmannRitter.engine.model.impl; import herbstJennrichLehmannRitter.engine.model.DefenceBuilding; public abstract class AbstractDefenceBuilding implements DefenceBuilding { private int actualPoints; public AbstractDefenceBuilding(int actualPoints) { this.actualPoints = actualPoints; } @Override public int getActualPoints() { return this.actualPoints; } @Override public void setActualPoints(int points) { if (points < 0) { this.actualPoints = 0; } else { this.actualPoints = points; } } @Override public void addPoints(int points) { setActualPoints(this.actualPoints + points); } @Override public int applyDamage(int damage) { if (this.actualPoints < damage) { + damage -= this.actualPoints; setActualPoints(0); - return damage - this.actualPoints; + return damage; } setActualPoints(this.actualPoints - damage); return 0; } }
false
true
public int applyDamage(int damage) { if (this.actualPoints < damage) { setActualPoints(0); return damage - this.actualPoints; } setActualPoints(this.actualPoints - damage); return 0; }
public int applyDamage(int damage) { if (this.actualPoints < damage) { damage -= this.actualPoints; setActualPoints(0); return damage; } setActualPoints(this.actualPoints - damage); return 0; }
diff --git a/dsr/src/main/java/eu/emi/dsr/infrastructure/ServiceEventReciever.java b/dsr/src/main/java/eu/emi/dsr/infrastructure/ServiceEventReciever.java index 6378c10..a6d7f64 100644 --- a/dsr/src/main/java/eu/emi/dsr/infrastructure/ServiceEventReciever.java +++ b/dsr/src/main/java/eu/emi/dsr/infrastructure/ServiceEventReciever.java @@ -1,180 +1,180 @@ /** * */ package eu.emi.dsr.infrastructure; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.ClientResponse.Status; import eu.emi.client.DSRClient; import eu.emi.client.ServiceBasicAttributeNames; import eu.emi.dsr.core.Configuration; import eu.emi.dsr.event.Event; import eu.emi.dsr.event.EventDispatcher; import eu.emi.dsr.event.EventListener; import eu.emi.dsr.event.EventTypes; import eu.emi.dsr.util.Log; /** * @author a.memon * @author g.szigeti * */ public class ServiceEventReciever implements EventListener, Runnable { private static Logger logger = Log.getLogger(Log.DSR, ServiceEventReciever.class); private static Configuration conf; private final WebResource client; private static InfrastructureManager infrastructure; private static boolean parent_lost; private Filters filter; /** * @param property */ public ServiceEventReciever(String parentUrl, Configuration config) { conf = config; infrastructure = new InfrastructureManager(conf); try { infrastructure.setParent(parentUrl); } catch (EmptyIdentifierFailureException e) { logger.error("Empty parent URL added!"); } catch (NullPointerFailureException e) { logger.error("NULL point error by the parent URL!"); } DSRClient c = new DSRClient(parentUrl + "/serviceadmin"); client = c.getClientResource(); parent_lost = false; filter = new Filters(); } /* * (non-Javadoc) * * @see eu.emi.dsr.event.EventReciever#recieve(eu.emi.dsr.event.Event) */ @Override public void recieve(Event event) { List<String> IDs = new ArrayList<String>(); JSONArray jos = new JSONArray(); try { jos = filter.outputFilter((JSONArray) event.getData()); } catch (ClassCastException e) { if (logger.isDebugEnabled()) { - logger.debug("event.data to JSONObject cast problem. May be delete message."); + logger.debug("event.data to JSONArray cast problem. May be delete message."); } } try { for (int i=0; i<jos.length(); i++){ IDs.add(jos.getJSONObject(i).getString("Service_Endpoint_URL")); } } catch (JSONException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } // here sending messages to the parent DSR's if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_ADD)) { if (logger.isDebugEnabled()) { logger.debug("service added event fired"); } try{ ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ try { IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.REGISTER, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleRegistration(IDs); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_UPDATE)) { if (logger.isDebugEnabled()) { logger.debug("service update event fired"); } try { ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .put(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.UPDATE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleUpdate(IDs); } catch (Exception e) { Log.logException("Error making update on the parent dsr",e); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_DELETE)) { if (logger.isDebugEnabled()) { logger.debug("service added delete event fired"); } try{ ClientResponse res = client.queryParam( ServiceBasicAttributeNames.SERVICE_ENDPOINT_URL .getAttributeName(), event.getData().toString()).delete(ClientResponse.class); if ( res.getStatus() == Status.OK.getStatusCode() ){ if (parent_lost){ // DB sync List<String> ID = new ArrayList<String>(); ID.add(event.getData().toString()); parent_lost = !infrastructure.dbSynchronization(ID, Method.DELETE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleDelete(event.getData().toString()); } } } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { EventDispatcher.add(this); } }
true
true
public void recieve(Event event) { List<String> IDs = new ArrayList<String>(); JSONArray jos = new JSONArray(); try { jos = filter.outputFilter((JSONArray) event.getData()); } catch (ClassCastException e) { if (logger.isDebugEnabled()) { logger.debug("event.data to JSONObject cast problem. May be delete message."); } } try { for (int i=0; i<jos.length(); i++){ IDs.add(jos.getJSONObject(i).getString("Service_Endpoint_URL")); } } catch (JSONException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } // here sending messages to the parent DSR's if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_ADD)) { if (logger.isDebugEnabled()) { logger.debug("service added event fired"); } try{ ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ try { IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.REGISTER, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleRegistration(IDs); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_UPDATE)) { if (logger.isDebugEnabled()) { logger.debug("service update event fired"); } try { ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .put(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.UPDATE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleUpdate(IDs); } catch (Exception e) { Log.logException("Error making update on the parent dsr",e); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_DELETE)) { if (logger.isDebugEnabled()) { logger.debug("service added delete event fired"); } try{ ClientResponse res = client.queryParam( ServiceBasicAttributeNames.SERVICE_ENDPOINT_URL .getAttributeName(), event.getData().toString()).delete(ClientResponse.class); if ( res.getStatus() == Status.OK.getStatusCode() ){ if (parent_lost){ // DB sync List<String> ID = new ArrayList<String>(); ID.add(event.getData().toString()); parent_lost = !infrastructure.dbSynchronization(ID, Method.DELETE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleDelete(event.getData().toString()); } } }
public void recieve(Event event) { List<String> IDs = new ArrayList<String>(); JSONArray jos = new JSONArray(); try { jos = filter.outputFilter((JSONArray) event.getData()); } catch (ClassCastException e) { if (logger.isDebugEnabled()) { logger.debug("event.data to JSONArray cast problem. May be delete message."); } } try { for (int i=0; i<jos.length(); i++){ IDs.add(jos.getJSONObject(i).getString("Service_Endpoint_URL")); } } catch (JSONException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } // here sending messages to the parent DSR's if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_ADD)) { if (logger.isDebugEnabled()) { logger.debug("service added event fired"); } try{ ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ try { IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.REGISTER, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleRegistration(IDs); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_UPDATE)) { if (logger.isDebugEnabled()) { logger.debug("service update event fired"); } try { ClientResponse res = client.accept(MediaType.APPLICATION_JSON_TYPE) .put(ClientResponse.class, jos); if ( res.getStatus() == Status.OK.getStatusCode() || res.getStatus() == Status.CONFLICT.getStatusCode() ){ if (parent_lost){ // remove the wrong IDs from the ID list if ( res.getStatus() == Status.CONFLICT.getStatusCode() ){ JSONArray errors = res.getEntity(JSONArray.class); for (int i=0; i<errors.length(); i++){ IDs.remove(errors.getJSONObject(i).getString("Service_Endpoint_URL")); } } // DB sync parent_lost = !infrastructure.dbSynchronization(IDs, Method.UPDATE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleUpdate(IDs); } catch (Exception e) { Log.logException("Error making update on the parent dsr",e); } } if (event.getType().equalsIgnoreCase(EventTypes.SERVICE_DELETE)) { if (logger.isDebugEnabled()) { logger.debug("service added delete event fired"); } try{ ClientResponse res = client.queryParam( ServiceBasicAttributeNames.SERVICE_ENDPOINT_URL .getAttributeName(), event.getData().toString()).delete(ClientResponse.class); if ( res.getStatus() == Status.OK.getStatusCode() ){ if (parent_lost){ // DB sync List<String> ID = new ArrayList<String>(); ID.add(event.getData().toString()); parent_lost = !infrastructure.dbSynchronization(ID, Method.DELETE, res.getStatus()); } } } catch(ClientHandlerException e){ parent_lost = true; infrastructure.handleDelete(event.getData().toString()); } } }
diff --git a/server/plugin/src/pt/webdetails/cdf/dd/render/layout/SpaceRender.java b/server/plugin/src/pt/webdetails/cdf/dd/render/layout/SpaceRender.java index fb043e2d..a1c7ba43 100644 --- a/server/plugin/src/pt/webdetails/cdf/dd/render/layout/SpaceRender.java +++ b/server/plugin/src/pt/webdetails/cdf/dd/render/layout/SpaceRender.java @@ -1,32 +1,32 @@ package pt.webdetails.cdf.dd.render.layout; import org.apache.commons.jxpath.JXPathContext; public class SpaceRender extends Render { public SpaceRender(JXPathContext context) { super(context); } @Override public void processProperties() { getPropertyBag().addStyle("background-color", getPropertyString("backgroundColor")); getPropertyBag().addClass(getPropertyString("cssClass")); getPropertyBag().addClass("space"); - getPropertyBag().addStyle("height", getPropertyString("height")); + getPropertyBag().addStyle("height", getPropertyString("height")+"px"); } public String renderStart() { String div = "<hr "; div += getPropertyBagString() + ">"; return div; } public String renderClose() { return "</hr>"; } }
true
true
public void processProperties() { getPropertyBag().addStyle("background-color", getPropertyString("backgroundColor")); getPropertyBag().addClass(getPropertyString("cssClass")); getPropertyBag().addClass("space"); getPropertyBag().addStyle("height", getPropertyString("height")); }
public void processProperties() { getPropertyBag().addStyle("background-color", getPropertyString("backgroundColor")); getPropertyBag().addClass(getPropertyString("cssClass")); getPropertyBag().addClass("space"); getPropertyBag().addStyle("height", getPropertyString("height")+"px"); }
diff --git a/illamapedit/src/illarion/mapedit/data/MapWarpPoint.java b/illamapedit/src/illarion/mapedit/data/MapWarpPoint.java index 4f96c105..23325bb5 100644 --- a/illamapedit/src/illarion/mapedit/data/MapWarpPoint.java +++ b/illamapedit/src/illarion/mapedit/data/MapWarpPoint.java @@ -1,117 +1,117 @@ /* * This file is part of the Illarion Mapeditor. * * Copyright © 2012 - Illarion e.V. * * The Illarion Mapeditor 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. * * The Illarion Mapeditor 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 the Illarion Mapeditor. If not, see <http://www.gnu.org/licenses/>. */ package illarion.mapedit.data; import javolution.lang.Immutable; import javolution.text.TextBuilder; /** * Represents a single warp point, with a start point, as map coordinate and a target point as world coordinate. * * @author Tim */ public class MapWarpPoint implements Immutable { /** * The x coordinate of the target point. */ private final int xTarget; /** * The y coordinate of the target point. */ private final int yTarget; /** * The level/z coordinate of the target point. */ private final int zTarget; /** * Creates a new Warp object with all necessary data. * * @param xTarget * @param yTarget * @param zTarget */ public MapWarpPoint(final int xTarget, final int yTarget, final int zTarget) { this.xTarget = xTarget; this.yTarget = yTarget; this.zTarget = zTarget; } /** * Copies the warp object (probably useless) * * @param old */ public MapWarpPoint(final MapWarpPoint old) { xTarget = old.xTarget; yTarget = old.yTarget; zTarget = old.zTarget; } /** * Returns the x coordinate of the target point. * * @return */ public int getXTarget() { return xTarget; } /** * Returns the y coordinate of the target point. * * @return */ public int getYTarget() { return yTarget; } /** * Returns the z coordinate of the target point. * * @return */ public int getZTarget() { return zTarget; } /** * Serializes the current warp point to a string in the following format: <br> * {@code <tx>;<ty>;<tz>} * * @return */ @Override public String toString() { TextBuilder builder = TextBuilder.newInstance(); builder.append(xTarget).append(';'); builder.append(yTarget).append(';'); - builder.append(zTarget).append(';'); + builder.append(zTarget); try { return builder.toString(); } finally { TextBuilder.recycle(builder); } } }
true
true
public String toString() { TextBuilder builder = TextBuilder.newInstance(); builder.append(xTarget).append(';'); builder.append(yTarget).append(';'); builder.append(zTarget).append(';'); try { return builder.toString(); } finally { TextBuilder.recycle(builder); } }
public String toString() { TextBuilder builder = TextBuilder.newInstance(); builder.append(xTarget).append(';'); builder.append(yTarget).append(';'); builder.append(zTarget); try { return builder.toString(); } finally { TextBuilder.recycle(builder); } }
diff --git a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java index d258d0481..bda42e212 100644 --- a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java +++ b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java @@ -1,27 +1,27 @@ package org.broadinstitute.sting.alignment; import org.junit.Test; import org.broadinstitute.sting.WalkerTest; import java.util.Arrays; /** * Integration tests for the aligner. * * @author mhanna * @version 0.1 */ public class AlignerIntegrationTest extends WalkerTest { @Test public void testBasicAlignment() { - String md5 = "c6d95d8ae707e78fefdaa7375f130995"; + String md5 = "34eb4323742999d6d250a0aaa803c6d5"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( - "-R " + b36KGReference + + "-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); } }
false
true
public void testBasicAlignment() { String md5 = "c6d95d8ae707e78fefdaa7375f130995"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); }
public void testBasicAlignment() { String md5 = "34eb4323742999d6d250a0aaa803c6d5"; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" + " -T Align" + " -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" + " -ob %s", 1, // just one output file Arrays.asList(md5)); executeTest("testBasicAlignment", spec); }
diff --git a/src/edu/uwo/csd/dcsim/core/Simulation.java b/src/edu/uwo/csd/dcsim/core/Simulation.java index 0342e689..a386639d 100644 --- a/src/edu/uwo/csd/dcsim/core/Simulation.java +++ b/src/edu/uwo/csd/dcsim/core/Simulation.java @@ -1,393 +1,395 @@ package edu.uwo.csd.dcsim.core; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import edu.uwo.csd.dcsim.core.metrics.Metric; import edu.uwo.csd.dcsim.logging.*; import java.util.*; import java.io.*; public abstract class Simulation implements SimulationEventListener { public static final String DEFAULT_LOGGER_CONVERSION_PATTERN = "%-10s %-5p - %m%n"; public static final String DEFAULT_LOGGER_DATE_FORMAT = "yyyy_MM_dd'-'HH_mm_ss"; public static final String DEFAULT_LOGGER_FILE_NAME = "dcsim-%n-%d"; public static final int SIMULATION_TERMINATE_EVENT = 1; public static final int SIMULATION_RECORD_METRICS_EVENT = 2; public static final int SIMULATION_RUN_MONITORS_EVENT = 3; private static String homeDirectory = null; private static String LOG_DIRECTORY = "/log"; private static String CONFIG_DIRECTORY = "/config"; private static Properties loggerProperties; protected final Logger logger; private static Properties properties; private String name; private PriorityQueue<Event> eventQueue; private long simulationTime; //in milliseconds private long lastUpdate; //in milliseconds private long duration; private long metricRecordStart; private boolean recordingMetrics; private long eventSendCount = 0; private Map<String, Metric> metrics = new HashMap<String, Metric>(); private Map<String, Monitor> monitors = new HashMap<String, Monitor>(); private Random random; private long randomSeed; private Map<String, Integer> nextIdMap = new HashMap<String, Integer>(); private boolean complete = false; public static final void initializeLogging() { Properties properties = new Properties(); try { properties.load(new FileInputStream(Simulation.getConfigDirectory() + "/logger.properties")); } catch (FileNotFoundException e) { throw new RuntimeException("Logging properties file could not be loaded", e); } catch (IOException e) { throw new RuntimeException("Logging properties file could not be loaded", e); } PropertyConfigurator.configure(properties); loggerProperties = properties; } private static final Properties getProperties() { if (properties == null) { /* * Load configuration properties from fileSIMULATION_RUN_MONITORS_EVENT */ properties = new Properties(); try { properties.load(new FileInputStream(Simulation.getConfigDirectory() + "/simulation.properties")); } catch (FileNotFoundException e) { throw new RuntimeException("Properties file could not be loaded", e); } catch (IOException e) { throw new RuntimeException("Properties file could not be loaded", e); } } return properties; } public Simulation(String name, long randomSeed) { this(name); this.setRandomSeed(randomSeed); //override Random seed with specified value } public Simulation(String name) { eventQueue = new PriorityQueue<Event>(1000, new EventComparator()); simulationTime = 0; lastUpdate = 0; this.name = name; //configure simulation logger logger = Logger.getLogger("simLogger." + name); boolean enableFileLogging = true; String conversionPattern = DEFAULT_LOGGER_CONVERSION_PATTERN; String dateFormat = DEFAULT_LOGGER_DATE_FORMAT; String fileName = DEFAULT_LOGGER_FILE_NAME; if (loggerProperties != null) { if (loggerProperties.getProperty("log4j.logger.simLogger.enableFile") != null) { enableFileLogging = Boolean.parseBoolean(loggerProperties.getProperty("log4j.logger.simLogger.enableFile")); } if (loggerProperties.getProperty("log4j.logger.simLogger.ConversionPattern") != null) { conversionPattern = loggerProperties.getProperty("log4j.logger.simLogger.ConversionPattern"); } if (loggerProperties.getProperty("log4j.logger.simLogger.DateFormat") != null) { dateFormat = loggerProperties.getProperty("log4j.logger.simLogger.DateFormat"); } if (loggerProperties.getProperty("log4j.logger.simLogger.File") != null) { fileName = loggerProperties.getProperty("log4j.logger.simLogger.File"); } } if (enableFileLogging) { SimulationFileAppender simAppender = new SimulationFileAppender(); SimulationPatternLayout patternLayout = new SimulationPatternLayout(this); patternLayout.setConversionPattern(conversionPattern); simAppender.setLayout(patternLayout); simAppender.setSimName(name); simAppender.setDateFormat(dateFormat); simAppender.setFile(getLogDirectory() + "/" + fileName); simAppender.activateOptions(); logger.addAppender(simAppender); } //initialize Random setRandomSeed(new Random().nextLong()); } public final Collection<Metric> run(long duration) { return run(duration, 0); } public final Collection<Metric> run(long duration, long metricRecordStart) { if (complete) throw new IllegalStateException("Simulation has already been run"); Event e; //configure simulation duration this.duration = duration; sendEvent(new Event(Simulation.SIMULATION_TERMINATE_EVENT, duration, this, this)); //this event runs at the last possible time in the simulation to ensure simulation updates if (metricRecordStart > 0) { recordingMetrics = false; this.metricRecordStart = metricRecordStart; sendEvent(new Event(Simulation.SIMULATION_RECORD_METRICS_EVENT, metricRecordStart, this, this)); } else { recordingMetrics = true; } logger.info("Starting simulation " + name); beginSimulation(); while (!eventQueue.isEmpty() && simulationTime < duration) { e = eventQueue.poll(); if (e.getTime() >= simulationTime) { //check if simulationTime is advancing if (simulationTime != e.getTime()) { lastUpdate = simulationTime; simulationTime = e.getTime(); //update the simulation updateSimulation(simulationTime); //run monitors - long nextMonitor = Long.MAX_VALUE; - for (Monitor monitor : monitors.values()) { - long nextExec = monitor.run(); - if (nextExec < nextMonitor) - nextMonitor = nextExec; + if (monitors.size() > 0) { + long nextMonitor = duration; + for (Monitor monitor : monitors.values()) { + long nextExec = monitor.run(); + if (nextExec < nextMonitor) + nextMonitor = nextExec; + } + sendEvent(new Event(Simulation.SIMULATION_RUN_MONITORS_EVENT, nextMonitor, this, this)); } - sendEvent(new Event(Simulation.SIMULATION_RUN_MONITORS_EVENT, nextMonitor, this, this)); } e.getTarget().handleEvent(e); } else { throw new RuntimeException("Encountered event (" + e.getType() + ") with time < current simulation time from class " + e.getSource().getClass().toString()); } } completeSimulation(duration); logger.info("Completed simulation " + name); complete = true; //wrap result in new Collection so that Collection is modifyable, as modifying the values() collection of a HashMap directly breaks things. Vector<Metric> result = new Vector<Metric>(metrics.values()); return result; } public abstract void beginSimulation(); public abstract void updateSimulation(long simulationTime); public abstract void completeSimulation(long duration); public final void sendEvent(Event event) { event.setSendOrder(++eventSendCount); eventQueue.add(event); } @Override public final void handleEvent(Event e) { switch (e.getType()) { case Simulation.SIMULATION_TERMINATE_EVENT: //Do nothing. This ensures that the simulation is fully up-to-date upon termination. logger.debug("Terminating Simulation"); break; case Simulation.SIMULATION_RECORD_METRICS_EVENT: logger.debug("Metric recording started"); recordingMetrics = true; break; case Simulation.SIMULATION_RUN_MONITORS_EVENT: //Do nothing. This ensures that monitors are run in the case that no other event is scheduled. break; default: throw new RuntimeException("Simulation received unknown event type"); } } public final Logger getLogger() { return logger; } public final int nextId(String name) { int id = 1; if (nextIdMap.containsKey(name)) id = nextIdMap.get(name); nextIdMap.put(name, id + 1); return id; } public final String getName() { return name; } public final Random getRandom() { if (random == null) { random = new Random(); setRandomSeed(random.nextLong()); } return random; } public final long getRandomSeed() { return randomSeed; } public final void setRandomSeed(long seed) { randomSeed = seed; random = new Random(randomSeed); } public final boolean hasMetric(String name) { return metrics.containsKey(name); } public final Metric getMetric(String name) { return metrics.get(name); } public final void addMetric(Metric metric) { if (!metrics.containsKey(metric)) { metrics.put(metric.getName(), metric); } else { throw new RuntimeException("Metric " + metric.getName() + " already exists in simulation. Cannot add multiple copies of the same metric to the same simulation."); } } public final void addMonitor(String name, Monitor monitor) { monitors.put(name, monitor); } public final Monitor getMonitor(String name) { return monitors.get(name); } public final long getSimulationTime() { return simulationTime; } public final long getDuration() { return duration; } public final long getMetricRecordStart() { return metricRecordStart; } public final long getRecordingDuration() { return duration - metricRecordStart; } public final long getLastUpdate() { return lastUpdate; } public final long getElapsedTime() { return simulationTime - lastUpdate; } public final double getElapsedSeconds() { return getElapsedTime() / 1000d; } public final boolean isRecordingMetrics() { return recordingMetrics; } /** * Helper functions */ /** * Get the directory of the manager application * @return The directory of the manager application */ public static final String getHomeDirectory() { if (homeDirectory == null) { File dir = new File("."); try { homeDirectory = dir.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } return homeDirectory; } /** * Get the directory that contains log files * @return The directory that contains log files. */ public static final String getLogDirectory() { return getHomeDirectory() + LOG_DIRECTORY; } /** * Get the directory that contains configuration files * @return The directory that contains configuration files. */ public static final String getConfigDirectory() { return getHomeDirectory() + CONFIG_DIRECTORY; } public static final boolean hasProperty(String name) { if (System.getProperty(name) != null || getProperties().getProperty(name) != null) return true; return false; } /** * Retrieve an application property from the configuration file or command line options. If a * property is specified in both, then the command line overrides the properties file. * @param name Name of property. * @return The value of the property. */ public static final String getProperty(String name) { String prop = null; if (System.getProperty(name) != null) { prop = System.getProperty(name); } else { prop = getProperties().getProperty(name); } if (prop == null) throw new RuntimeException("Simulation property '" + name + "' not found"); return prop; } }
false
true
public final Collection<Metric> run(long duration, long metricRecordStart) { if (complete) throw new IllegalStateException("Simulation has already been run"); Event e; //configure simulation duration this.duration = duration; sendEvent(new Event(Simulation.SIMULATION_TERMINATE_EVENT, duration, this, this)); //this event runs at the last possible time in the simulation to ensure simulation updates if (metricRecordStart > 0) { recordingMetrics = false; this.metricRecordStart = metricRecordStart; sendEvent(new Event(Simulation.SIMULATION_RECORD_METRICS_EVENT, metricRecordStart, this, this)); } else { recordingMetrics = true; } logger.info("Starting simulation " + name); beginSimulation(); while (!eventQueue.isEmpty() && simulationTime < duration) { e = eventQueue.poll(); if (e.getTime() >= simulationTime) { //check if simulationTime is advancing if (simulationTime != e.getTime()) { lastUpdate = simulationTime; simulationTime = e.getTime(); //update the simulation updateSimulation(simulationTime); //run monitors long nextMonitor = Long.MAX_VALUE; for (Monitor monitor : monitors.values()) { long nextExec = monitor.run(); if (nextExec < nextMonitor) nextMonitor = nextExec; } sendEvent(new Event(Simulation.SIMULATION_RUN_MONITORS_EVENT, nextMonitor, this, this)); } e.getTarget().handleEvent(e); } else { throw new RuntimeException("Encountered event (" + e.getType() + ") with time < current simulation time from class " + e.getSource().getClass().toString()); } } completeSimulation(duration); logger.info("Completed simulation " + name); complete = true; //wrap result in new Collection so that Collection is modifyable, as modifying the values() collection of a HashMap directly breaks things. Vector<Metric> result = new Vector<Metric>(metrics.values()); return result; }
public final Collection<Metric> run(long duration, long metricRecordStart) { if (complete) throw new IllegalStateException("Simulation has already been run"); Event e; //configure simulation duration this.duration = duration; sendEvent(new Event(Simulation.SIMULATION_TERMINATE_EVENT, duration, this, this)); //this event runs at the last possible time in the simulation to ensure simulation updates if (metricRecordStart > 0) { recordingMetrics = false; this.metricRecordStart = metricRecordStart; sendEvent(new Event(Simulation.SIMULATION_RECORD_METRICS_EVENT, metricRecordStart, this, this)); } else { recordingMetrics = true; } logger.info("Starting simulation " + name); beginSimulation(); while (!eventQueue.isEmpty() && simulationTime < duration) { e = eventQueue.poll(); if (e.getTime() >= simulationTime) { //check if simulationTime is advancing if (simulationTime != e.getTime()) { lastUpdate = simulationTime; simulationTime = e.getTime(); //update the simulation updateSimulation(simulationTime); //run monitors if (monitors.size() > 0) { long nextMonitor = duration; for (Monitor monitor : monitors.values()) { long nextExec = monitor.run(); if (nextExec < nextMonitor) nextMonitor = nextExec; } sendEvent(new Event(Simulation.SIMULATION_RUN_MONITORS_EVENT, nextMonitor, this, this)); } } e.getTarget().handleEvent(e); } else { throw new RuntimeException("Encountered event (" + e.getType() + ") with time < current simulation time from class " + e.getSource().getClass().toString()); } } completeSimulation(duration); logger.info("Completed simulation " + name); complete = true; //wrap result in new Collection so that Collection is modifyable, as modifying the values() collection of a HashMap directly breaks things. Vector<Metric> result = new Vector<Metric>(metrics.values()); return result; }
diff --git a/IntermediateCodeGeneration/src/IntermediateCodeGeneration/AST/LiteralNode.java b/IntermediateCodeGeneration/src/IntermediateCodeGeneration/AST/LiteralNode.java index 374bcea..c09a55d 100644 --- a/IntermediateCodeGeneration/src/IntermediateCodeGeneration/AST/LiteralNode.java +++ b/IntermediateCodeGeneration/src/IntermediateCodeGeneration/AST/LiteralNode.java @@ -1,83 +1,86 @@ package IntermediateCodeGeneration.AST; import IntermediateCodeGeneration.SemanticException; import IntermediateCodeGeneration.SymbolTable.Type.Type; import IntermediateCodeGeneration.Token; import IntermediateCodeGeneration.SymbolTable.SymbolTable; /** * Representacion de un nodo literal * * @author Ramiro Agis * @author Victoria Martínez de la Cruz */ public class LiteralNode extends PrimaryNode { protected Token literal; public LiteralNode(SymbolTable symbolTable, Token literal, Type type) { super(symbolTable, literal); this.literal = literal; expressionType = type; } @Override public void checkNode() { } @Override public void generateCode() throws SemanticException { if (expressionType.getTypeName().equals("null")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'null'"); } else if (expressionType.getTypeName().equals("String")) { String label = ICG.generateLabel(); ICG.GEN(".DATA"); ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); ICG.GEN(".CODE"); ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); } else if (expressionType.getTypeName().equals("char")) { if (literal.getLexeme().equals("'\n'")) { ICG.GEN("PUSH 10", "Apilo el caracter nl."); } else if (literal.getLexeme().equals("'\t'")) { ICG.GEN("PUSH 9", "Apilo el caracter tab."); } else { ICG.GEN("PUSH " + (int) literal.getLexeme().charAt(0), "Apilo el caracter " + literal.getLexeme()); } } else if (expressionType.getTypeName().equals("boolean")) { if (literal.getLexeme().equals("true")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 1", "Apilamos 'true'"); } else if (literal.getLexeme().equals("false")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'false'"); } + } else { + ICG.GEN(".CODE"); + ICG.GEN("PUSH " + literal.getLexeme()); } // if (expressionType.getTypeName().equals("String")) { // String label = ICG.generateLabel(); // // ICG.GEN(".DATA"); // ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); // // ICG.GEN(".CODE"); // ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); // } else if (literal.getLexeme().equals("true")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 1", "Apilamos 'true'"); // } else if (literal.getLexeme().equals("false")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'false'"); // } else if (literal.getLexeme().equals("null")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'null'"); // } else { // ICG.GEN(".CODE"); // ICG.GEN("PUSH " + literal.getLexeme()); // } } }
true
true
public void generateCode() throws SemanticException { if (expressionType.getTypeName().equals("null")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'null'"); } else if (expressionType.getTypeName().equals("String")) { String label = ICG.generateLabel(); ICG.GEN(".DATA"); ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); ICG.GEN(".CODE"); ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); } else if (expressionType.getTypeName().equals("char")) { if (literal.getLexeme().equals("'\n'")) { ICG.GEN("PUSH 10", "Apilo el caracter nl."); } else if (literal.getLexeme().equals("'\t'")) { ICG.GEN("PUSH 9", "Apilo el caracter tab."); } else { ICG.GEN("PUSH " + (int) literal.getLexeme().charAt(0), "Apilo el caracter " + literal.getLexeme()); } } else if (expressionType.getTypeName().equals("boolean")) { if (literal.getLexeme().equals("true")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 1", "Apilamos 'true'"); } else if (literal.getLexeme().equals("false")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'false'"); } } // if (expressionType.getTypeName().equals("String")) { // String label = ICG.generateLabel(); // // ICG.GEN(".DATA"); // ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); // // ICG.GEN(".CODE"); // ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); // } else if (literal.getLexeme().equals("true")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 1", "Apilamos 'true'"); // } else if (literal.getLexeme().equals("false")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'false'"); // } else if (literal.getLexeme().equals("null")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'null'"); // } else { // ICG.GEN(".CODE"); // ICG.GEN("PUSH " + literal.getLexeme()); // } }
public void generateCode() throws SemanticException { if (expressionType.getTypeName().equals("null")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'null'"); } else if (expressionType.getTypeName().equals("String")) { String label = ICG.generateLabel(); ICG.GEN(".DATA"); ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); ICG.GEN(".CODE"); ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); } else if (expressionType.getTypeName().equals("char")) { if (literal.getLexeme().equals("'\n'")) { ICG.GEN("PUSH 10", "Apilo el caracter nl."); } else if (literal.getLexeme().equals("'\t'")) { ICG.GEN("PUSH 9", "Apilo el caracter tab."); } else { ICG.GEN("PUSH " + (int) literal.getLexeme().charAt(0), "Apilo el caracter " + literal.getLexeme()); } } else if (expressionType.getTypeName().equals("boolean")) { if (literal.getLexeme().equals("true")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 1", "Apilamos 'true'"); } else if (literal.getLexeme().equals("false")) { ICG.GEN(".CODE"); ICG.GEN("PUSH 0", "Apilamos 'false'"); } } else { ICG.GEN(".CODE"); ICG.GEN("PUSH " + literal.getLexeme()); } // if (expressionType.getTypeName().equals("String")) { // String label = ICG.generateLabel(); // // ICG.GEN(".DATA"); // ICG.GEN("lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass() + ": DW " + literal.getLexeme() + ", 0"); // // ICG.GEN(".CODE"); // ICG.GEN("PUSH lString" + label + "_" + symbolTable.getCurrentService() + "_" + symbolTable.getCurrentClass(), "Apilamos el label del String '" + literal.getLexeme() + "'."); // } else if (literal.getLexeme().equals("true")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 1", "Apilamos 'true'"); // } else if (literal.getLexeme().equals("false")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'false'"); // } else if (literal.getLexeme().equals("null")) { // ICG.GEN(".CODE"); // ICG.GEN("PUSH 0", "Apilamos 'null'"); // } else { // ICG.GEN(".CODE"); // ICG.GEN("PUSH " + literal.getLexeme()); // } }
diff --git a/microemulator/microemu-javase-swing/src/main/java/org/microemu/device/j2se/J2SEButton.java b/microemulator/microemu-javase-swing/src/main/java/org/microemu/device/j2se/J2SEButton.java index da0950ac..46a6e90b 100644 --- a/microemulator/microemu-javase-swing/src/main/java/org/microemu/device/j2se/J2SEButton.java +++ b/microemulator/microemu-javase-swing/src/main/java/org/microemu/device/j2se/J2SEButton.java @@ -1,232 +1,232 @@ /* * MicroEmulator * Copyright (C) 2001 Bartek Teodorczyk <barteo@barteo.net> * * It is licensed under the following two licenses as alternatives: * 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version * 2. Apache License (the "AL") Version 2.0 * * You may not use this file except in compliance with at least one of * the above two licenses. * * You may obtain a copy of the LGPL at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * You may obtain a copy of the AL 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 LGPL or the AL for the specific language governing permissions and * limitations. * * @version $Id$ */ package org.microemu.device.j2se; import java.awt.event.KeyEvent; import java.util.Hashtable; import java.util.StringTokenizer; import org.microemu.device.InputMethod; import org.microemu.device.impl.Button; import org.microemu.device.impl.ButtonDetaultDeviceKeyCodes; import org.microemu.device.impl.ButtonName; import org.microemu.device.impl.Shape; public class J2SEButton implements Button { private String name; private ButtonName functionalName; private Shape shape; private int[] keyboardKeys; private String keyboardCharCodes; private int keyCode; private Hashtable inputToChars; private boolean modeChange; /** * Create special functional buttons. e.g. ButtonName.DELETE and * ButtonName.BACK_SPACE if not defined in 'device.xml' * * @param name */ J2SEButton(ButtonName functionalName) { this(20002, functionalName.getName(), null, Integer.MIN_VALUE, null, null, null, false); } /** * @param name * @param shape * @param keyCode - * Integer.MIN_VALUE when unspecified * @param keyName * @param chars */ public J2SEButton(int skinVersion, String name, Shape shape, int keyCode, String keyboardKeys, String keyboardChars, Hashtable inputToChars, boolean modeChange) { this.name = name; this.shape = shape; if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.functionalName = ButtonName.getButtonName(name); } else { this.functionalName = J2SEButtonDefaultKeyCodes.getBackwardCompatibleName(parseKeyboardKey(keyboardKeys)); if (this.functionalName == null) { this.functionalName = ButtonName.getButtonName(name); } } if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.modeChange = modeChange; } else { this.modeChange = (functionalName == ButtonName.KEY_POUND); } if (keyCode == Integer.MIN_VALUE) { this.keyCode = ButtonDetaultDeviceKeyCodes.getKeyCode(this.functionalName); } else { this.keyCode = keyCode; } if (keyboardKeys != null) { StringTokenizer st = new StringTokenizer(keyboardKeys, " "); while (st.hasMoreTokens()) { int key = parseKeyboardKey(st.nextToken()); if (key == -1) { continue; } if (this.keyboardKeys == null) { this.keyboardKeys = new int[1]; } else { int[] newKeyboardKeys = new int[this.keyboardKeys.length + 1]; - System.arraycopy(keyboardKeys, 0, newKeyboardKeys, 0, this.keyboardKeys.length); + System.arraycopy(this.keyboardKeys, 0, newKeyboardKeys, 0, this.keyboardKeys.length); this.keyboardKeys = newKeyboardKeys; } this.keyboardKeys[this.keyboardKeys.length - 1] = key; } } if ((this.keyboardKeys == null) || (this.keyboardKeys.length == 0)) { this.keyboardKeys = J2SEButtonDefaultKeyCodes.getKeyCodes(this.functionalName); } if (keyboardChars != null) { this.keyboardCharCodes = keyboardChars; } else { this.keyboardCharCodes = J2SEButtonDefaultKeyCodes.getCharCodes(this.functionalName); } this.inputToChars = inputToChars; } /** * @deprecated */ public int getKeyboardKey() { if (keyboardKeys.length == 0) { return 0; } return keyboardKeys[0]; } public int getKeyCode() { return keyCode; } public ButtonName getFunctionalName() { return functionalName; } public int[] getKeyboardKeyCodes() { return keyboardKeys; } /** * CharCodes do not depends on InputMode. This is computer keyboard codes * when it is impossible to map to VK keys. */ public char[] getKeyboardCharCodes() { if (keyboardCharCodes == null) { return new char[0]; } return keyboardCharCodes.toCharArray(); } public boolean isModeChange() { return modeChange; } void setModeChange() { modeChange = true; } public char[] getChars(int inputMode) { char[] result = null; switch (inputMode) { case InputMethod.INPUT_123: result = (char[]) inputToChars.get("123"); break; case InputMethod.INPUT_ABC_LOWER: result = (char[]) inputToChars.get("abc"); break; case InputMethod.INPUT_ABC_UPPER: result = (char[]) inputToChars.get("ABC"); break; } if (result == null) { result = (char[]) inputToChars.get("common"); } if (result == null) { result = new char[0]; } return result; } public boolean isChar(char c, int inputMode) { if (inputToChars == null) { return false; } c = Character.toLowerCase(c); char[] chars = getChars(inputMode); if (chars != null) { for (int i = 0; i < chars.length; i++) { if (c == Character.toLowerCase(chars[i])) { return true; } } } return false; } public String getName() { return name; } public Shape getShape() { return shape; } private static int parseKeyboardKey(String keyName) { int key; try { key = KeyEvent.class.getField(keyName).getInt(null); } catch (Exception e) { try { key = Integer.parseInt(keyName); } catch (NumberFormatException e1) { key = -1; } } return key; } }
true
true
public J2SEButton(int skinVersion, String name, Shape shape, int keyCode, String keyboardKeys, String keyboardChars, Hashtable inputToChars, boolean modeChange) { this.name = name; this.shape = shape; if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.functionalName = ButtonName.getButtonName(name); } else { this.functionalName = J2SEButtonDefaultKeyCodes.getBackwardCompatibleName(parseKeyboardKey(keyboardKeys)); if (this.functionalName == null) { this.functionalName = ButtonName.getButtonName(name); } } if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.modeChange = modeChange; } else { this.modeChange = (functionalName == ButtonName.KEY_POUND); } if (keyCode == Integer.MIN_VALUE) { this.keyCode = ButtonDetaultDeviceKeyCodes.getKeyCode(this.functionalName); } else { this.keyCode = keyCode; } if (keyboardKeys != null) { StringTokenizer st = new StringTokenizer(keyboardKeys, " "); while (st.hasMoreTokens()) { int key = parseKeyboardKey(st.nextToken()); if (key == -1) { continue; } if (this.keyboardKeys == null) { this.keyboardKeys = new int[1]; } else { int[] newKeyboardKeys = new int[this.keyboardKeys.length + 1]; System.arraycopy(keyboardKeys, 0, newKeyboardKeys, 0, this.keyboardKeys.length); this.keyboardKeys = newKeyboardKeys; } this.keyboardKeys[this.keyboardKeys.length - 1] = key; } } if ((this.keyboardKeys == null) || (this.keyboardKeys.length == 0)) { this.keyboardKeys = J2SEButtonDefaultKeyCodes.getKeyCodes(this.functionalName); } if (keyboardChars != null) { this.keyboardCharCodes = keyboardChars; } else { this.keyboardCharCodes = J2SEButtonDefaultKeyCodes.getCharCodes(this.functionalName); } this.inputToChars = inputToChars; }
public J2SEButton(int skinVersion, String name, Shape shape, int keyCode, String keyboardKeys, String keyboardChars, Hashtable inputToChars, boolean modeChange) { this.name = name; this.shape = shape; if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.functionalName = ButtonName.getButtonName(name); } else { this.functionalName = J2SEButtonDefaultKeyCodes.getBackwardCompatibleName(parseKeyboardKey(keyboardKeys)); if (this.functionalName == null) { this.functionalName = ButtonName.getButtonName(name); } } if (skinVersion >= NAME_RIMARY_SINCE_SKIN_VERSION) { this.modeChange = modeChange; } else { this.modeChange = (functionalName == ButtonName.KEY_POUND); } if (keyCode == Integer.MIN_VALUE) { this.keyCode = ButtonDetaultDeviceKeyCodes.getKeyCode(this.functionalName); } else { this.keyCode = keyCode; } if (keyboardKeys != null) { StringTokenizer st = new StringTokenizer(keyboardKeys, " "); while (st.hasMoreTokens()) { int key = parseKeyboardKey(st.nextToken()); if (key == -1) { continue; } if (this.keyboardKeys == null) { this.keyboardKeys = new int[1]; } else { int[] newKeyboardKeys = new int[this.keyboardKeys.length + 1]; System.arraycopy(this.keyboardKeys, 0, newKeyboardKeys, 0, this.keyboardKeys.length); this.keyboardKeys = newKeyboardKeys; } this.keyboardKeys[this.keyboardKeys.length - 1] = key; } } if ((this.keyboardKeys == null) || (this.keyboardKeys.length == 0)) { this.keyboardKeys = J2SEButtonDefaultKeyCodes.getKeyCodes(this.functionalName); } if (keyboardChars != null) { this.keyboardCharCodes = keyboardChars; } else { this.keyboardCharCodes = J2SEButtonDefaultKeyCodes.getCharCodes(this.functionalName); } this.inputToChars = inputToChars; }
diff --git a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/Openable.java b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/Openable.java index 82ac442f9..8ea24c4f6 100644 --- a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/Openable.java +++ b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/internal/core/Openable.java @@ -1,575 +1,578 @@ /******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation 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 * *******************************************************************************/ package org.eclipse.dltk.internal.core; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.dltk.codeassist.ICompletionEngine; import org.eclipse.dltk.codeassist.ISelectionEngine; import org.eclipse.dltk.core.BufferChangedEvent; import org.eclipse.dltk.core.CompletionRequestor; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.core.DLTKLanguageManager; import org.eclipse.dltk.core.IBuffer; import org.eclipse.dltk.core.IBufferChangedListener; import org.eclipse.dltk.core.IDLTKLanguageToolkit; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.core.IModelStatusConstants; import org.eclipse.dltk.core.IOpenable; import org.eclipse.dltk.core.ModelException; import org.eclipse.dltk.core.WorkingCopyOwner; /** * Abstract class for implementations of model elements which are IOpenable. * * @see IModelElement * @see IOpenable */ public abstract class Openable extends ModelElement implements IOpenable, IBufferChangedListener { protected Openable(ModelElement parent) { super(parent); } /** * The buffer associated with this element has changed. Registers this * element as being out of synch with its buffer's contents. If the buffer * has been closed, this element is set as NOT out of synch with the * contents. * * @see IBufferChangedListener */ public void bufferChanged(BufferChangedEvent event) { if (event.getBuffer().isClosed()) { ModelManager.getModelManager().getElementsOutOfSynchWithBuffers() .remove(this); getBufferManager().removeBuffer(event.getBuffer()); } else { ModelManager.getModelManager().getElementsOutOfSynchWithBuffers() .add(this); } } /** * Builds this element's structure and properties in the given info object, * based on this element's current contents (reuse buffer contents if this * element has an open buffer, or resource contents if this element does not * have an open buffer). Children are placed in the given newElements table * (note, this element has already been placed in the newElements table). * Returns true if successful, or false if an error is encountered while * determining the structure of this element. */ protected abstract boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws ModelException; /* * Returns whether this element can be removed from the model cache to make * space. */ public boolean canBeRemovedFromCache() { try { return !hasUnsavedChanges(); } catch (ModelException e) { return false; } } /* * Returns whether the buffer of this element can be removed from the Script * model cache to make space. */ public boolean canBufferBeRemovedFromCache(IBuffer buffer) { return !buffer.hasUnsavedChanges(); } /** * Close the buffer associated with this element, if any. */ protected void closeBuffer() { if (!hasBuffer()) return; // nothing to do IBuffer buffer = getBufferManager().getBuffer(this); if (buffer != null) { buffer.close(); buffer.removeBufferChangedListener(this); } } /** * This element is being closed. Do any necessary cleanup. */ protected void closing(Object info) { closeBuffer(); } /** * @see IModelElement */ public boolean exists() { ModelManager manager = ModelManager.getModelManager(); if (manager.getInfo(this) != null) return true; if (!parentExists()) return false; ProjectFragment root = getProjectFragment(); if (root != null && (root == this || !root.isArchive())) { return resourceExists(); } return super.exists(); } protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws ModelException { if (ModelManager.VERBOSE) { String element; switch (getElementType()) { case SCRIPT_PROJECT: element = "project"; //$NON-NLS-1$ break; case PROJECT_FRAGMENT: element = "fragment"; //$NON-NLS-1$ break; case SCRIPT_FOLDER: element = "folder"; //$NON-NLS-1$ break; case BINARY_MODULE: element = "binary module"; //$NON-NLS-1$ break; case SOURCE_MODULE: element = "source module"; //$NON-NLS-1$ break; default: element = "element"; //$NON-NLS-1$ } System.out .println(Thread.currentThread() + " OPENING " + element + " " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$ } // open the parent if necessary openParent(info, newElements, monitor); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // puts the info before building the structure so that questions to the // handle behave as if the element existed // (case of compilation units becoming working copies) newElements.put(this, info); // build the structure of the openable (this will open the buffer if // needed) try { OpenableElementInfo openableElementInfo = (OpenableElementInfo) info; boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource()); openableElementInfo.setIsStructureKnown(isStructureKnown); } catch (ModelException e) { newElements.remove(this); throw e; } // remove out of sync buffer for this element ModelManager.getModelManager().getElementsOutOfSynchWithBuffers() .remove(this); if (ModelManager.VERBOSE) { System.out.println(ModelManager.getModelManager().cache .toStringFillingRation("-> ")); //$NON-NLS-1$ } } /** * Note: a buffer with no unsaved changes can be closed by the Model since * it has a finite number of buffers allowed open at one time. If this is * the first time a request is being made for the buffer, an attempt is made * to create and fill this element's buffer. If the buffer has been closed * since it was first opened, the buffer is re-created. * * @see IOpenable */ public IBuffer getBuffer() throws ModelException { if (hasBuffer()) { // ensure element is open Object info = getElementInfo(); IBuffer buffer = getBufferManager().getBuffer(this); if (buffer == null) { // try to (re)open a buffer buffer = openBuffer(null, info); } return buffer; } else { return null; } } /** * Returns the buffer manager for this element. */ protected BufferManager getBufferManager() { return BufferManager.getDefaultBufferManager(); } /** * Return my underlying resource. Elements that may not have a corresponding * resource must override this method. * * @see IScriptElement */ public IResource getCorrespondingResource() throws ModelException { return getUnderlyingResource(); } /* * @see IModelElement */ public IOpenable getOpenable() { return this; } public IResource getUnderlyingResource() throws ModelException { IResource parentResource = this.parent.getUnderlyingResource(); if (parentResource == null) { return null; } int type = parentResource.getType(); if (type == IResource.FOLDER || type == IResource.PROJECT) { IContainer folder = (IContainer) parentResource; IResource resource = folder.findMember(getElementName()); if (resource == null) { throw newNotPresentException(); } else { return resource; } } else { return parentResource; } } /** * Returns true if this element may have an associated source buffer, * otherwise false. Subclasses must override as required. */ protected boolean hasBuffer() { return false; } /** * @see IOpenable */ public boolean hasUnsavedChanges() throws ModelException { if (isReadOnly() || !isOpen()) { return false; } IBuffer buf = this.getBuffer(); if (buf != null && buf.hasUnsavedChanges()) { return true; } // for package fragments, package fragment roots, and projects must // check open buffers // to see if they have an child with unsaved changes int elementType = getElementType(); if (elementType == SCRIPT_FOLDER || elementType == PROJECT_FRAGMENT || elementType == SCRIPT_PROJECT || elementType == SCRIPT_MODEL) { // fix // for // 1FWNMHH Enumeration openBuffers = getBufferManager().getOpenBuffers(); while (openBuffers.hasMoreElements()) { IBuffer buffer = (IBuffer) openBuffers.nextElement(); if (buffer.hasUnsavedChanges()) { IModelElement owner = buffer.getOwner(); if (isAncestorOf(owner)) { return true; } } } } return false; } /** * Subclasses must override as required. * * @see IOpenable */ public boolean isConsistent() { return true; } /** * * @see IOpenable */ public boolean isOpen() { return ModelManager.getModelManager().getInfo(this) != null; } /** * Returns true if this represents a source element. Openable source * elements have an associated buffer created when they are opened. */ protected boolean isSourceElement() { return false; } /** * @see IModelElement */ public boolean isStructureKnown() throws ModelException { return ((OpenableElementInfo) getElementInfo()).isStructureKnown(); } /** * @see IOpenable */ public void makeConsistent(IProgressMonitor monitor) throws ModelException { // only source modules can be inconsistent // other openables cannot be inconsistent so default is to do nothing } /** * @see IOpenable */ public void open(IProgressMonitor pm) throws ModelException { getElementInfo(pm); } /** * Opens a buffer on the contents of this element, and returns the buffer, * or returns <code>null</code> if opening fails. By default, do nothing - * subclasses that have buffers must override as required. */ protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws ModelException { return null; } /** * Open the parent element if necessary. */ protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws ModelException { Openable openableParent = (Openable) getOpenableParent(); if (openableParent != null && !openableParent.isOpen()) { openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm); } } /** * Answers true if the parent exists (null parent is answering true) * */ protected boolean parentExists() { IModelElement parentElement = getParent(); if (parentElement == null) return true; return parentElement.exists(); } /** * Returns whether the corresponding resource or associated file exists */ protected boolean resourceExists() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); if (workspace == null) return false; // workaround for // http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069 return Model.getTarget(workspace.getRoot(), this.getPath() .makeRelative(), // ensure path is relative (see // http://dev.eclipse.org/bugs/show_bug.cgi?id=22517) true) != null; } /** * @see IOpenable */ public void save(IProgressMonitor pm, boolean force) throws ModelException { if (isReadOnly()) { throw new ModelException(new ModelStatus( IModelStatusConstants.READ_ONLY, this)); } IBuffer buf = getBuffer(); if (buf != null) { // some Openables (like a ScriptProject) don't have a // buffer buf.save(pm, force); this.makeConsistent(pm); // update the element info of this // element } } /** * Find enclosing project fragment if any */ public ProjectFragment getProjectFragment() { return (ProjectFragment) getAncestor(IModelElement.PROJECT_FRAGMENT); } /** Code Completion */ protected void codeComplete(org.eclipse.dltk.compiler.env.ISourceModule cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner) throws ModelException { if (requestor == null) { throw new IllegalArgumentException("Completion requestor cannot be null"); } IBuffer buffer = getBuffer(); if (buffer == null) { return; } if (position < -1 || position > buffer.getLength()) { - throw new ModelException(new ModelStatus( - IModelStatusConstants.INDEX_OUT_OF_BOUNDS)); + if( DLTKCore.DEBUG) { + throw new ModelException(new ModelStatus( + IModelStatusConstants.INDEX_OUT_OF_BOUNDS)); + } + return; } ScriptProject project = (ScriptProject) getScriptProject(); //TODO: Add searchable environment support. SearchableEnvironment environment = project .newSearchableNameEnvironment(owner); // set unit to skip environment.unitToSkip = cu; IDLTKLanguageToolkit toolkit = null; //TODO: rewrite this ugly code try { toolkit = DLTKLanguageManager.getLanguageToolkit(this); } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } if (toolkit == null) { toolkit = DLTKLanguageManager.findToolkit(this.getResource()); if (toolkit == null) { return; } } // code complete ICompletionEngine engine = null; try { engine = DLTKLanguageManager.getCompletionEngine(toolkit.getNatureId()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if( engine == null ) { return; } engine.setEnvironment(environment); engine.setRequestor(requestor); engine.setOptions(project.getOptions(true)); engine.setProject(project); /*toolkit.createCompletionEngine(environment, requestor, project.getOptions(true), project);*/ engine.complete(cu, position, 0); if (NameLookup.VERBOSE) { System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } } protected IModelElement[] codeSelect( org.eclipse.dltk.compiler.env.ISourceModule cu, int offset, int length, WorkingCopyOwner owner) throws ModelException { ScriptProject project = (ScriptProject) getScriptProject(); SearchableEnvironment environment = null; try { environment = project.newSearchableNameEnvironment(owner); } catch (ModelException e) { // e.printStackTrace(); return new IModelElement[0]; } IBuffer buffer = getBuffer(); if (buffer == null) { return new IModelElement[0]; } IDLTKLanguageToolkit toolkit = null; try { toolkit = DLTKLanguageManager.getLanguageToolkit(this); } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } if (toolkit == null) { toolkit = DLTKLanguageManager.findToolkit(this.getResource()); if (toolkit == null) { if (DLTKCore.VERBOSE) { System.out .println("DLTK.Openable.VERBOSE: Failed to detect language toolkit... for module:" + this.getResource().getName()); } return new IModelElement[0]; } } int end = buffer.getLength(); if (offset < 0 || length < 0 || offset + length > end) { throw new ModelException(new ModelStatus( IModelStatusConstants.INDEX_OUT_OF_BOUNDS)); } ISelectionEngine engine = null; try { engine = DLTKLanguageManager.getSelectionEngine(toolkit.getNatureId()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (engine == null) { return new IModelElement[0]; } engine.setEnvironment(environment); engine.setOptions(project.getOptions(true)); // createSelectionEngine(environment, // project.getOptions(true)); IModelElement[] elements = engine.select(cu, offset, offset + length - 1); if (NameLookup.VERBOSE) { System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } return elements; } }
true
true
protected void codeComplete(org.eclipse.dltk.compiler.env.ISourceModule cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner) throws ModelException { if (requestor == null) { throw new IllegalArgumentException("Completion requestor cannot be null"); } IBuffer buffer = getBuffer(); if (buffer == null) { return; } if (position < -1 || position > buffer.getLength()) { throw new ModelException(new ModelStatus( IModelStatusConstants.INDEX_OUT_OF_BOUNDS)); } ScriptProject project = (ScriptProject) getScriptProject(); //TODO: Add searchable environment support. SearchableEnvironment environment = project .newSearchableNameEnvironment(owner); // set unit to skip environment.unitToSkip = cu; IDLTKLanguageToolkit toolkit = null; //TODO: rewrite this ugly code try { toolkit = DLTKLanguageManager.getLanguageToolkit(this); } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } if (toolkit == null) { toolkit = DLTKLanguageManager.findToolkit(this.getResource()); if (toolkit == null) { return; } } // code complete ICompletionEngine engine = null; try { engine = DLTKLanguageManager.getCompletionEngine(toolkit.getNatureId()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if( engine == null ) { return; } engine.setEnvironment(environment); engine.setRequestor(requestor); engine.setOptions(project.getOptions(true)); engine.setProject(project); /*toolkit.createCompletionEngine(environment, requestor, project.getOptions(true), project);*/ engine.complete(cu, position, 0); if (NameLookup.VERBOSE) { System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } }
protected void codeComplete(org.eclipse.dltk.compiler.env.ISourceModule cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner) throws ModelException { if (requestor == null) { throw new IllegalArgumentException("Completion requestor cannot be null"); } IBuffer buffer = getBuffer(); if (buffer == null) { return; } if (position < -1 || position > buffer.getLength()) { if( DLTKCore.DEBUG) { throw new ModelException(new ModelStatus( IModelStatusConstants.INDEX_OUT_OF_BOUNDS)); } return; } ScriptProject project = (ScriptProject) getScriptProject(); //TODO: Add searchable environment support. SearchableEnvironment environment = project .newSearchableNameEnvironment(owner); // set unit to skip environment.unitToSkip = cu; IDLTKLanguageToolkit toolkit = null; //TODO: rewrite this ugly code try { toolkit = DLTKLanguageManager.getLanguageToolkit(this); } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } if (toolkit == null) { toolkit = DLTKLanguageManager.findToolkit(this.getResource()); if (toolkit == null) { return; } } // code complete ICompletionEngine engine = null; try { engine = DLTKLanguageManager.getCompletionEngine(toolkit.getNatureId()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if( engine == null ) { return; } engine.setEnvironment(environment); engine.setRequestor(requestor); engine.setOptions(project.getOptions(true)); engine.setProject(project); /*toolkit.createCompletionEngine(environment, requestor, project.getOptions(true), project);*/ engine.complete(cu, position, 0); if (NameLookup.VERBOSE) { System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ System.out .println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } }
diff --git a/src/biblioteca/gui/catalogacion/Subir_Archivo.java b/src/biblioteca/gui/catalogacion/Subir_Archivo.java index 4eeb6bc..d4d968f 100644 --- a/src/biblioteca/gui/catalogacion/Subir_Archivo.java +++ b/src/biblioteca/gui/catalogacion/Subir_Archivo.java @@ -1,142 +1,142 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Subir_Archivo.java * * Created on 7/05/2011, 08:56:00 PM */ package biblioteca.gui.catalogacion; /** * * @author alejandro */ public class Subir_Archivo extends javax.swing.JPanel { /** Creates new form Subir_Archivo */ public Subir_Archivo() { initComponents(); } /** 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jTextField1 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Path = new javax.swing.JTextField(); Seleccionar_Archivo = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); Estado = new javax.swing.JLabel(); jTextField1.setText("jTextField1"); setLayout(new java.awt.GridBagLayout()); jLabel4.setFont(new java.awt.Font("Ubuntu", 1, 24)); jLabel4.setText("Subir un Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10); add(jLabel4, gridBagConstraints); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/biblioteca/gui/resources/logo.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 5; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; - gridBagConstraints.gridwidth = 4; + gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 0); add(Path, gridBagConstraints); Seleccionar_Archivo.setText("Seleccionar Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 10); add(Seleccionar_Archivo, gridBagConstraints); jLabel5.setFont(new java.awt.Font("Ubuntu", 0, 18)); jLabel5.setText("Por favor, seleccione el archivo o digite su path:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); add(jLabel5, gridBagConstraints); - jButton2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N + jButton2.setFont(new java.awt.Font("Ubuntu", 1, 15)); jButton2.setText("Finalizar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10); add(jButton2, gridBagConstraints); jSeparator1.setMinimumSize(new java.awt.Dimension(150, 6)); jSeparator1.setPreferredSize(new java.awt.Dimension(200, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(jSeparator1, gridBagConstraints); Estado.setFont(new java.awt.Font("Ubuntu", 0, 24)); Estado.setForeground(new java.awt.Color(255, 0, 0)); Estado.setText("[Sin Guardar]"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0); add(Estado, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Estado; private javax.swing.JTextField Path; private javax.swing.JButton Seleccionar_Archivo; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jTextField1 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Path = new javax.swing.JTextField(); Seleccionar_Archivo = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); Estado = new javax.swing.JLabel(); jTextField1.setText("jTextField1"); setLayout(new java.awt.GridBagLayout()); jLabel4.setFont(new java.awt.Font("Ubuntu", 1, 24)); jLabel4.setText("Subir un Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10); add(jLabel4, gridBagConstraints); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/biblioteca/gui/resources/logo.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 5; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 0); add(Path, gridBagConstraints); Seleccionar_Archivo.setText("Seleccionar Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 10); add(Seleccionar_Archivo, gridBagConstraints); jLabel5.setFont(new java.awt.Font("Ubuntu", 0, 18)); jLabel5.setText("Por favor, seleccione el archivo o digite su path:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); add(jLabel5, gridBagConstraints); jButton2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N jButton2.setText("Finalizar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10); add(jButton2, gridBagConstraints); jSeparator1.setMinimumSize(new java.awt.Dimension(150, 6)); jSeparator1.setPreferredSize(new java.awt.Dimension(200, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(jSeparator1, gridBagConstraints); Estado.setFont(new java.awt.Font("Ubuntu", 0, 24)); Estado.setForeground(new java.awt.Color(255, 0, 0)); Estado.setText("[Sin Guardar]"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0); add(Estado, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jTextField1 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); Path = new javax.swing.JTextField(); Seleccionar_Archivo = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); Estado = new javax.swing.JLabel(); jTextField1.setText("jTextField1"); setLayout(new java.awt.GridBagLayout()); jLabel4.setFont(new java.awt.Font("Ubuntu", 1, 24)); jLabel4.setText("Subir un Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10); add(jLabel4, gridBagConstraints); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/biblioteca/gui/resources/logo.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 5; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); add(jLabel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 0); add(Path, gridBagConstraints); Seleccionar_Archivo.setText("Seleccionar Archivo"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 10); add(Seleccionar_Archivo, gridBagConstraints); jLabel5.setFont(new java.awt.Font("Ubuntu", 0, 18)); jLabel5.setText("Por favor, seleccione el archivo o digite su path:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); add(jLabel5, gridBagConstraints); jButton2.setFont(new java.awt.Font("Ubuntu", 1, 15)); jButton2.setText("Finalizar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10); add(jButton2, gridBagConstraints); jSeparator1.setMinimumSize(new java.awt.Dimension(150, 6)); jSeparator1.setPreferredSize(new java.awt.Dimension(200, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); add(jSeparator1, gridBagConstraints); Estado.setFont(new java.awt.Font("Ubuntu", 0, 24)); Estado.setForeground(new java.awt.Color(255, 0, 0)); Estado.setText("[Sin Guardar]"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0); add(Estado, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
diff --git a/modules/org.restlet.ext.net/src/org/restlet/ext/net/internal/HttpUrlConnectionCall.java b/modules/org.restlet.ext.net/src/org/restlet/ext/net/internal/HttpUrlConnectionCall.java index 85b016a16..d6739ac74 100644 --- a/modules/org.restlet.ext.net/src/org/restlet/ext/net/internal/HttpUrlConnectionCall.java +++ b/modules/org.restlet.ext.net/src/org/restlet/ext/net/internal/HttpUrlConnectionCall.java @@ -1,412 +1,412 @@ /** * Copyright 2005-2010 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the * "Licenses"). You can select the license that you prefer but you may not use * this file except in compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package org.restlet.ext.net.internal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Level; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import org.restlet.Request; import org.restlet.Response; import org.restlet.Uniform; import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.engine.Edition; import org.restlet.engine.http.ClientCall; import org.restlet.engine.security.SslContextFactory; import org.restlet.engine.security.SslUtils; import org.restlet.engine.util.SystemUtils; import org.restlet.ext.net.HttpClientHelper; import org.restlet.representation.Representation; import org.restlet.util.Series; /** * HTTP client connector call based on JDK's java.net.HttpURLConnection class. * * @author Jerome Louvel */ public class HttpUrlConnectionCall extends ClientCall { /** The wrapped HTTP URL connection. */ private final HttpURLConnection connection; /** Indicates if the response headers were added. */ private volatile boolean responseHeadersAdded; /** * Constructor. * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpUrlConnectionCall(HttpClientHelper helper, String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); if (requestUri.startsWith("http")) { URL url = new URL(requestUri); this.connection = (HttpURLConnection) url.openConnection(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { this.connection.setConnectTimeout(getHelper() .getConnectTimeout()); this.connection.setReadTimeout(getHelper().getReadTimeout()); } // [ifndef gae] instruction this.connection.setAllowUserInteraction(getHelper() .isAllowUserInteraction()); this.connection.setDoOutput(hasEntity); this.connection.setInstanceFollowRedirects(getHelper() .isFollowRedirects()); this.connection.setUseCaches(getHelper().isUseCaches()); this.responseHeadersAdded = false; if (this.connection instanceof HttpsURLConnection) { setConfidential(true); HttpsURLConnection https = (HttpsURLConnection) this.connection; SslContextFactory sslContextFactory = SslUtils .getSslContextFactory(getHelper()); if (sslContextFactory != null) { try { SSLContext sslContext = sslContextFactory .createSslContext(); https .setSSLSocketFactory(sslContext .getSocketFactory()); } catch (Exception e) { throw new RuntimeException( "Unable to create SSLContext.", e); } } HostnameVerifier verifier = helper.getHostnameVerifier(); if (verifier != null) { https.setHostnameVerifier(verifier); } } } else { throw new IllegalArgumentException( "Only HTTP or HTTPS resource URIs are allowed here"); } } /** * Returns the connection. * * @return The connection. */ public HttpURLConnection getConnection() { return this.connection; } /** * Returns the HTTP client helper. * * @return The HTTP client helper. */ @Override public HttpClientHelper getHelper() { return (HttpClientHelper) super.getHelper(); } /** * Returns the response reason phrase. * * @return The response reason phrase. */ @Override public String getReasonPhrase() { try { return getConnection().getResponseMessage(); } catch (IOException e) { return null; } } @Override protected Representation getRepresentation(InputStream stream) { Representation r = super.getRepresentation(stream); return new ConnectionClosingRepresentation(r, getConnection()); } @Override public WritableByteChannel getRequestEntityChannel() { return null; } @Override public OutputStream getRequestEntityStream() { return getRequestStream(); } @Override public OutputStream getRequestHeadStream() { return getRequestStream(); } /** * Returns the request entity stream if it exists. * * @return The request entity stream if it exists. */ public OutputStream getRequestStream() { try { return getConnection().getOutputStream(); } catch (IOException ioe) { return null; } } @Override public ReadableByteChannel getResponseEntityChannel(long size) { return null; } @Override public InputStream getResponseEntityStream(long size) { InputStream result = null; try { result = getConnection().getInputStream(); } catch (IOException ioe) { result = getConnection().getErrorStream(); } if (result == null) { // Maybe an error stream is available instead result = getConnection().getErrorStream(); } return result; } /** * Returns the modifiable list of response headers. * * @return The modifiable list of response headers. */ @Override public Series<Parameter> getResponseHeaders() { Series<Parameter> result = super.getResponseHeaders(); if (!this.responseHeadersAdded) { // Read the response headers int i = 1; String headerName = getConnection().getHeaderFieldKey(i); String headerValue = getConnection().getHeaderField(i); while (headerName != null) { result.add(headerName, headerValue); i++; if (Edition.CURRENT != Edition.GAE) { headerName = getConnection().getHeaderFieldKey(i); headerValue = getConnection().getHeaderField(i); } else { try { headerName = getConnection().getHeaderFieldKey(i); headerValue = getConnection().getHeaderField(i); } catch (java.util.NoSuchElementException e) { headerName = null; } } } this.responseHeadersAdded = true; } return result; } /** * Returns the response address.<br> * Corresponds to the IP address of the responding server. * * @return The response address. */ @Override public String getServerAddress() { return getConnection().getURL().getHost(); } /** * Returns the response status code. * * @return The response status code. * @throws IOException * @throws IOException */ @Override public int getStatusCode() throws IOException { return getConnection().getResponseCode(); } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { if (request.isEntityAvailable()) { Representation entity = request.getEntity(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { // Adjust the streaming mode if (entity.getSize() != -1) { // The size of the entity is known in advance getConnection().setFixedLengthStreamingMode( (int) entity.getSize()); } else { // The size of the entity is not known in advance if (getHelper().getChunkLength() >= 0) { // Use chunked encoding getConnection().setChunkedStreamingMode( getHelper().getChunkLength()); } else { // Use entity buffering to determine the content // length } } } } // Set the request method getConnection().setRequestMethod(getMethod()); // Set the request headers for (Parameter header : getRequestHeaders()) { getConnection().addRequestProperty(header.getName(), header.getValue()); } - // Ensure that the connections is active + // Ensure that the connection is active getConnection().connect(); // Send the optional entity result = super.sendRequest(request); } catch (ConnectException ce) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the connection to the remote HTTP server.", ce); result = new Status(Status.CONNECTOR_ERROR_CONNECTION, ce); } catch (SocketTimeoutException ste) { getHelper() .getLogger() .log( Level.FINE, "An timeout error occurred during the communication with the remote HTTP server.", ste); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ste); } catch (FileNotFoundException fnfe) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", fnfe); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); } catch (Exception e) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", e); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e); } return result; } @Override public void sendRequest(Request request, Response response, Uniform callback) throws Exception { // Send the request sendRequest(request); if(request.getOnSent() != null){ request.getOnSent().handle(request, response); } if (callback != null) { // Transmit to the callback, if any. callback.handle(request, response); } } }
true
true
public Status sendRequest(Request request) { Status result = null; try { if (request.isEntityAvailable()) { Representation entity = request.getEntity(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { // Adjust the streaming mode if (entity.getSize() != -1) { // The size of the entity is known in advance getConnection().setFixedLengthStreamingMode( (int) entity.getSize()); } else { // The size of the entity is not known in advance if (getHelper().getChunkLength() >= 0) { // Use chunked encoding getConnection().setChunkedStreamingMode( getHelper().getChunkLength()); } else { // Use entity buffering to determine the content // length } } } } // Set the request method getConnection().setRequestMethod(getMethod()); // Set the request headers for (Parameter header : getRequestHeaders()) { getConnection().addRequestProperty(header.getName(), header.getValue()); } // Ensure that the connections is active getConnection().connect(); // Send the optional entity result = super.sendRequest(request); } catch (ConnectException ce) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the connection to the remote HTTP server.", ce); result = new Status(Status.CONNECTOR_ERROR_CONNECTION, ce); } catch (SocketTimeoutException ste) { getHelper() .getLogger() .log( Level.FINE, "An timeout error occurred during the communication with the remote HTTP server.", ste); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ste); } catch (FileNotFoundException fnfe) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", fnfe); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); } catch (Exception e) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", e); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e); } return result; }
public Status sendRequest(Request request) { Status result = null; try { if (request.isEntityAvailable()) { Representation entity = request.getEntity(); // These properties can only be used with Java 1.5 and upper // releases int majorVersionNumber = SystemUtils.getJavaMajorVersion(); int minorVersionNumber = SystemUtils.getJavaMinorVersion(); if ((majorVersionNumber > 1) || ((majorVersionNumber == 1) && (minorVersionNumber >= 5))) { // Adjust the streaming mode if (entity.getSize() != -1) { // The size of the entity is known in advance getConnection().setFixedLengthStreamingMode( (int) entity.getSize()); } else { // The size of the entity is not known in advance if (getHelper().getChunkLength() >= 0) { // Use chunked encoding getConnection().setChunkedStreamingMode( getHelper().getChunkLength()); } else { // Use entity buffering to determine the content // length } } } } // Set the request method getConnection().setRequestMethod(getMethod()); // Set the request headers for (Parameter header : getRequestHeaders()) { getConnection().addRequestProperty(header.getName(), header.getValue()); } // Ensure that the connection is active getConnection().connect(); // Send the optional entity result = super.sendRequest(request); } catch (ConnectException ce) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the connection to the remote HTTP server.", ce); result = new Status(Status.CONNECTOR_ERROR_CONNECTION, ce); } catch (SocketTimeoutException ste) { getHelper() .getLogger() .log( Level.FINE, "An timeout error occurred during the communication with the remote HTTP server.", ste); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ste); } catch (FileNotFoundException fnfe) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", fnfe); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, fnfe); } catch (IOException ioe) { getHelper() .getLogger() .log( Level.FINE, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); } catch (Exception e) { getHelper() .getLogger() .log( Level.FINE, "An unexpected error occurred during the sending of the HTTP request.", e); result = new Status(Status.CONNECTOR_ERROR_INTERNAL, e); } return result; }
diff --git a/src/jumble/fast/FastRunner.java b/src/jumble/fast/FastRunner.java index 908a071..a31aeb5 100644 --- a/src/jumble/fast/FastRunner.java +++ b/src/jumble/fast/FastRunner.java @@ -1,459 +1,462 @@ package jumble.fast; import com.reeltwo.util.Debug; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import jumble.mutation.Mutater; import jumble.mutation.Mutation; import jumble.util.IOThread; import jumble.util.JavaRunner; import junit.framework.TestResult; /** * A runner for the <CODE>FastJumbler</CODE>. Runs the FastJumbler in a new * JVM and detects timeouts. * * @author Tin Pavlinic * @version $Revision$ */ public class FastRunner { /** Filename for the cache */ public static final String CACHE_FILENAME = "jumble-cache.dat"; /** Whether to mutate constants */ private boolean mInlineConstants = true; /** Whether to mutate return values */ private boolean mReturnVals = true; /** Whether to mutate increments */ private boolean mIncrements = true; private boolean mOrdered = true; private boolean mLoadCache = true; private boolean mSaveCache = true; private boolean mUseCache = true; private Set mExcludeMethods = new HashSet(); /** The variable storing the failed tests - can get pretty big */ FailedTestMap mCache = null; /** * Gets whether inline constants will be mutated. * * @return true if inline constants will be mutated. */ public boolean isInlineConstants() { return mInlineConstants; } /** * Sets whether inline constants will be mutated. * * @param argInlineConstants true if inline constants should be mutated. */ public void setInlineConstants(final boolean argInlineConstants) { mInlineConstants = argInlineConstants; } /** * Gets whether return values will be mutated. * * @return true if return values will be mutated. */ public boolean isReturnVals() { return mReturnVals; } /** * Sets whether return values will be mutated. * * @param argReturnVals true return values should be mutated. */ public void setReturnVals(final boolean argReturnVals) { mReturnVals = argReturnVals; } /** * Gets whether increments will be mutated. * * @return true if increments will be mutated. */ public boolean isIncrements() { return mIncrements; } /** * Sets whether increments will be mutated. * * @param argIncrements true if increments will be mutated. */ public void setIncrements(final boolean argIncrements) { mIncrements = argIncrements; } /** * Gets whether tests are ordered by their run time. * * @return true if tests are ordered by their run time. */ public boolean isOrdered() { return mOrdered; } /** * Sets whether tests are ordered by their run time. * * @param argOrdered true if tests should be ordered by their run time. */ public void setOrdered(final boolean argOrdered) { mOrdered = argOrdered; } /** * Gets the value of loadCache * * @return the value of loadCache */ public boolean isLoadCache() { return mLoadCache; } /** * Sets the value of loadCache * * @param argLoadCache Value to assign to loadCache */ public void setLoadCache(final boolean argLoadCache) { mLoadCache = argLoadCache; } /** * Gets the value of saveCache * * @return the value of saveCache */ public boolean isSaveCache() { return mSaveCache; } /** * Sets the value of saveCache * * @param argSaveCache Value to assign to saveCache */ public void setSaveCache(final boolean argSaveCache) { mSaveCache = argSaveCache; } /** * Gets the value of useCache * * @return the value of useCache */ public boolean isUseCache() { return mUseCache; } /** * Sets the value of useCache * * @param argUseCache Value to assign to useCache */ public void setUseCache(final boolean argUseCache) { mUseCache = argUseCache; } /** * Gets the set of excluded method names * * @return the set of excluded method names */ public Set getExcludeMethods() { return mExcludeMethods; } /** * A function which computes the timeout for given that the original test took * <CODE>runtime</CODE> * * @param runtime * the original runtime * @return the computed timeout */ public static long computeTimeout(long runtime) { return runtime * 10 + 2000; } private void initCache() throws Exception { if (mUseCache) { boolean loaded = false; // Load the cache if it exists and is needed if (mLoadCache) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(CACHE_FILENAME)); mCache = (FailedTestMap) ois.readObject(); loaded = true; } catch (IOException e) { loaded = false; } } if (!loaded) { mCache = new FailedTestMap(); } } } private boolean writeCache(String cacheFileName) { try { File f = new File(cacheFileName); if (f.exists()) { f.delete(); } ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(cacheFileName)); o.writeObject(mCache); o.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } public void addExcludeMethod(String methodName) { mExcludeMethods.add(methodName); } /** Constructs arguments to the FastJumbler */ private String[] createArgs(String className, int currentMutation, String fileName, String cacheFileName) { ArrayList args = new ArrayList(); // class name args.add(className); // mutation point args.add(String.valueOf(currentMutation)); // test suite filename args.add(fileName); if (mUseCache) { // Write a temp cache if (writeCache(cacheFileName)) { args.add(cacheFileName); } } // exclude methods if (!mExcludeMethods.isEmpty()) { StringBuffer ex = new StringBuffer(); ex.append("-x "); Iterator it = mExcludeMethods.iterator(); for (int i = 0; i < mExcludeMethods.size(); i++) { if (i == 0) { ex.append(it.next()); } else { ex.append("," + it.next()); } } args.add(ex.toString()); } // inline constants if (mInlineConstants) { args.add("-k"); } // return values if (mReturnVals) { args.add("-r"); } // increments if (mIncrements) { args.add("-i"); } return (String[]) args.toArray(new String[args.size()]); } private int countMutationPoints(String className) { // Get the number of mutation points from the Jumbler final Mutater m = new Mutater(0); m.setIgnoredMethods(mExcludeMethods); m.setMutateIncrements(mIncrements); m.setMutateInlineConstants(mInlineConstants); m.setMutateReturnValues(mReturnVals); return m.countMutationPoints(className); } private boolean debugOutput(String out, String err) { if (out != null) { Debug.println("Child.out->" + out); } if (err != null) { Debug.println("Child.err->" + err); } return true; // So we can be enabled/disabled via assertion mechanism. } private void waitForStart(IOThread iot, IOThread eot) throws InterruptedException { // read the "START" to let us know the JVM has started // we don't want to time this. // FIXME this looks dangerous. What if the test can't even get to the point of outputting START (e.g. class loading issues) while (true) { String str = iot.getNext(); String err = eot.getNext(); assert debugOutput(str, err); if ((str == null) && (err == null)) { Thread.sleep(10); } else if ("START".equals(str)) { break; } else { throw new RuntimeException("jumble.fast.FastJumbler returned " + str + " instead of START"); } } } /** * Performs a Jumble run on the specified class with the specified tests. * * @param className the name of the class to Jumble * @param testClassNames the names of the associated test classes * @return the results of the Jumble run * @throws Exception if something goes wrong * @see JumbleResult */ public JumbleResult runJumble(final String className, final List testClassNames) throws Exception { final String cacheFileName = "cache" + System.currentTimeMillis() + ".dat"; initCache(); final int mutationCount = countMutationPoints(className); if (mutationCount == -1) { return new InterfaceResult(className); } Class[] testClasses = new Class[testClassNames.size()]; for (int i = 0; i < testClasses.length; i++) { try { testClasses[i] = Class.forName((String) testClassNames.get(i)); } catch (ClassNotFoundException e) { // test class did not exist return new FailedTestResult(className, testClassNames, null, mutationCount); } } final TestResult initialResult = new TestResult(); final TimingTestSuite timingSuite = new TimingTestSuite(testClasses); assert Debug.println("Parent. Starting initial run without mutating"); timingSuite.run(initialResult); assert Debug.println("Parent. Finished"); // Now, if the tests failed, can return straight away if (!initialResult.wasSuccessful()) { return new FailedTestResult(className, testClassNames, initialResult, mutationCount); } // Store the test suite information serialized in a temporary file final TestOrder order = timingSuite.getOrder(mOrdered); final String fileName = "testSuite" + System.currentTimeMillis() + ".dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(order); oos.close(); // compute the timeout long totalRuntime = timingSuite.getTotalRuntime(); final JavaRunner runner = new JavaRunner("jumble.fast.FastJumbler"); Process childProcess = null; IOThread iot = null; IOThread eot = null; final Mutation[] allMutations = new Mutation[mutationCount]; for (int currentMutation = 0; currentMutation < mutationCount; currentMutation++) { // If no process is running, start a new one if (childProcess == null) { // start process runner.setArguments(createArgs(className, currentMutation, fileName, cacheFileName)); childProcess = runner.start(); iot = new IOThread(childProcess.getInputStream()); iot.start(); eot = new IOThread(childProcess.getErrorStream()); eot.start(); waitForStart(iot, eot); } long before = System.currentTimeMillis(); long after = before; long timeout = computeTimeout(totalRuntime); // Run until we time out while (true) { String out = iot.getNext(); - String err = eot.getNext(); + String err; + while ((err = eot.getNext()) != null) { + assert debugOutput(null, err); + } assert debugOutput(out, err); if (out == null) { if (after - before > timeout) { allMutations[currentMutation] = new Mutation("TIMEOUT", className, currentMutation); childProcess.destroy(); childProcess = null; break; } else { Thread.sleep(50); after = System.currentTimeMillis(); } } else { try { // We have output so go to the next mutation allMutations[currentMutation] = new Mutation(out, className, currentMutation); if (mUseCache && allMutations[currentMutation].isPassed()) { // Remove "PASS: " and tokenize StringTokenizer tokens = new StringTokenizer(out.substring(6), ":"); String clazzName = tokens.nextToken(); assert clazzName.equals(className); String methodName = tokens.nextToken(); int mutPoint = Integer.parseInt(tokens.nextToken()); String testName = tokens.nextToken(); mCache.addFailure(className, methodName, mutPoint, testName); } } catch (RuntimeException e) { throw e; } break; } } } JumbleResult ret = new NormalJumbleResult(className, testClassNames, initialResult, allMutations, computeTimeout(totalRuntime)); // finally, delete the test suite file if (!new File(fileName).delete()) { System.err.println("Error: could not delete temporary file"); } // Also delete the temporary cache and save the cache if needed if (mUseCache) { if (!new File(cacheFileName).delete()) { System.err.println("Error: could not delete temporary cache file"); } if (mSaveCache) { writeCache(CACHE_FILENAME); } } mCache = null; return ret; } }
true
true
public JumbleResult runJumble(final String className, final List testClassNames) throws Exception { final String cacheFileName = "cache" + System.currentTimeMillis() + ".dat"; initCache(); final int mutationCount = countMutationPoints(className); if (mutationCount == -1) { return new InterfaceResult(className); } Class[] testClasses = new Class[testClassNames.size()]; for (int i = 0; i < testClasses.length; i++) { try { testClasses[i] = Class.forName((String) testClassNames.get(i)); } catch (ClassNotFoundException e) { // test class did not exist return new FailedTestResult(className, testClassNames, null, mutationCount); } } final TestResult initialResult = new TestResult(); final TimingTestSuite timingSuite = new TimingTestSuite(testClasses); assert Debug.println("Parent. Starting initial run without mutating"); timingSuite.run(initialResult); assert Debug.println("Parent. Finished"); // Now, if the tests failed, can return straight away if (!initialResult.wasSuccessful()) { return new FailedTestResult(className, testClassNames, initialResult, mutationCount); } // Store the test suite information serialized in a temporary file final TestOrder order = timingSuite.getOrder(mOrdered); final String fileName = "testSuite" + System.currentTimeMillis() + ".dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(order); oos.close(); // compute the timeout long totalRuntime = timingSuite.getTotalRuntime(); final JavaRunner runner = new JavaRunner("jumble.fast.FastJumbler"); Process childProcess = null; IOThread iot = null; IOThread eot = null; final Mutation[] allMutations = new Mutation[mutationCount]; for (int currentMutation = 0; currentMutation < mutationCount; currentMutation++) { // If no process is running, start a new one if (childProcess == null) { // start process runner.setArguments(createArgs(className, currentMutation, fileName, cacheFileName)); childProcess = runner.start(); iot = new IOThread(childProcess.getInputStream()); iot.start(); eot = new IOThread(childProcess.getErrorStream()); eot.start(); waitForStart(iot, eot); } long before = System.currentTimeMillis(); long after = before; long timeout = computeTimeout(totalRuntime); // Run until we time out while (true) { String out = iot.getNext(); String err = eot.getNext(); assert debugOutput(out, err); if (out == null) { if (after - before > timeout) { allMutations[currentMutation] = new Mutation("TIMEOUT", className, currentMutation); childProcess.destroy(); childProcess = null; break; } else { Thread.sleep(50); after = System.currentTimeMillis(); } } else { try { // We have output so go to the next mutation allMutations[currentMutation] = new Mutation(out, className, currentMutation); if (mUseCache && allMutations[currentMutation].isPassed()) { // Remove "PASS: " and tokenize StringTokenizer tokens = new StringTokenizer(out.substring(6), ":"); String clazzName = tokens.nextToken(); assert clazzName.equals(className); String methodName = tokens.nextToken(); int mutPoint = Integer.parseInt(tokens.nextToken()); String testName = tokens.nextToken(); mCache.addFailure(className, methodName, mutPoint, testName); } } catch (RuntimeException e) { throw e; } break; } } } JumbleResult ret = new NormalJumbleResult(className, testClassNames, initialResult, allMutations, computeTimeout(totalRuntime)); // finally, delete the test suite file if (!new File(fileName).delete()) { System.err.println("Error: could not delete temporary file"); } // Also delete the temporary cache and save the cache if needed if (mUseCache) { if (!new File(cacheFileName).delete()) { System.err.println("Error: could not delete temporary cache file"); } if (mSaveCache) { writeCache(CACHE_FILENAME); } } mCache = null; return ret; }
public JumbleResult runJumble(final String className, final List testClassNames) throws Exception { final String cacheFileName = "cache" + System.currentTimeMillis() + ".dat"; initCache(); final int mutationCount = countMutationPoints(className); if (mutationCount == -1) { return new InterfaceResult(className); } Class[] testClasses = new Class[testClassNames.size()]; for (int i = 0; i < testClasses.length; i++) { try { testClasses[i] = Class.forName((String) testClassNames.get(i)); } catch (ClassNotFoundException e) { // test class did not exist return new FailedTestResult(className, testClassNames, null, mutationCount); } } final TestResult initialResult = new TestResult(); final TimingTestSuite timingSuite = new TimingTestSuite(testClasses); assert Debug.println("Parent. Starting initial run without mutating"); timingSuite.run(initialResult); assert Debug.println("Parent. Finished"); // Now, if the tests failed, can return straight away if (!initialResult.wasSuccessful()) { return new FailedTestResult(className, testClassNames, initialResult, mutationCount); } // Store the test suite information serialized in a temporary file final TestOrder order = timingSuite.getOrder(mOrdered); final String fileName = "testSuite" + System.currentTimeMillis() + ".dat"; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(order); oos.close(); // compute the timeout long totalRuntime = timingSuite.getTotalRuntime(); final JavaRunner runner = new JavaRunner("jumble.fast.FastJumbler"); Process childProcess = null; IOThread iot = null; IOThread eot = null; final Mutation[] allMutations = new Mutation[mutationCount]; for (int currentMutation = 0; currentMutation < mutationCount; currentMutation++) { // If no process is running, start a new one if (childProcess == null) { // start process runner.setArguments(createArgs(className, currentMutation, fileName, cacheFileName)); childProcess = runner.start(); iot = new IOThread(childProcess.getInputStream()); iot.start(); eot = new IOThread(childProcess.getErrorStream()); eot.start(); waitForStart(iot, eot); } long before = System.currentTimeMillis(); long after = before; long timeout = computeTimeout(totalRuntime); // Run until we time out while (true) { String out = iot.getNext(); String err; while ((err = eot.getNext()) != null) { assert debugOutput(null, err); } assert debugOutput(out, err); if (out == null) { if (after - before > timeout) { allMutations[currentMutation] = new Mutation("TIMEOUT", className, currentMutation); childProcess.destroy(); childProcess = null; break; } else { Thread.sleep(50); after = System.currentTimeMillis(); } } else { try { // We have output so go to the next mutation allMutations[currentMutation] = new Mutation(out, className, currentMutation); if (mUseCache && allMutations[currentMutation].isPassed()) { // Remove "PASS: " and tokenize StringTokenizer tokens = new StringTokenizer(out.substring(6), ":"); String clazzName = tokens.nextToken(); assert clazzName.equals(className); String methodName = tokens.nextToken(); int mutPoint = Integer.parseInt(tokens.nextToken()); String testName = tokens.nextToken(); mCache.addFailure(className, methodName, mutPoint, testName); } } catch (RuntimeException e) { throw e; } break; } } } JumbleResult ret = new NormalJumbleResult(className, testClassNames, initialResult, allMutations, computeTimeout(totalRuntime)); // finally, delete the test suite file if (!new File(fileName).delete()) { System.err.println("Error: could not delete temporary file"); } // Also delete the temporary cache and save the cache if needed if (mUseCache) { if (!new File(cacheFileName).delete()) { System.err.println("Error: could not delete temporary cache file"); } if (mSaveCache) { writeCache(CACHE_FILENAME); } } mCache = null; return ret; }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/font/FontMappingManagerFactory.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/font/FontMappingManagerFactory.java index 53e314e16..00b1b202e 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/font/FontMappingManagerFactory.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/font/FontMappingManagerFactory.java @@ -1,526 +1,527 @@ /******************************************************************************* * Copyright (c) 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.layout.pdf.font; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; import com.lowagie.text.FontFactory; import com.lowagie.text.pdf.BaseFont; /** * FontMappingManagerFactory used to created all font mapping managers. * <p> * The user can define multiple font mapping configurations in * org.eclipse.birt.report.fonts fragment. The configuration has parent-child * relation ship. The configurations defined in the child configuration update * the one defined in the parent configurations. The inherit sequence of the * configurations are: * <li>format_os_language_country_variant</li> * <li>format_os_language_country</li> * <li>format_os_language</li> * <li>format_os</li> * <li>format</li> * <li>os_language_country_variant * <li>os_language_country</li> * <li>os_lanauge</li> * <li>os</li> * <li>fontsConfig</li> * </ul> * * The OS name is getting from either osgi.os or os.name. If it is getting from * the osgi.os property, the names can be (see the * <code>Platform.knownOSValues()</code> ): * <ul> * <li>win32</li> * <li>linux</li> * <li>aix</li> * <li>solaris</li> * <li>hpux</li> * <li>qnx</li> * <li>macosx</li> * </ul> * */ public class FontMappingManagerFactory { /** the logger logging the error, debug, warning messages. */ protected static Logger logger = Logger.getLogger( FontConfigReader.class .getName( ) ); protected static FontMappingManagerFactory instance; public static synchronized FontMappingManagerFactory getInstance( ) { if ( instance == null ) { instance = new FontMappingManagerFactory( ); } return instance; } /** * all font paths registered by this factory */ protected HashSet fontPathes = new HashSet( ); /** * font encodings, it is used by iText to load the Type1 fonts */ protected HashMap fontEncodings = new HashMap( ); /** * all loaded configurations * * the structure of the cache is: * <ul> * <li>key: configuration name</li> * <li>value: FontMappingConfig</li> * </ul> */ protected HashMap cachedConfigs = new HashMap( ); /** * all created mapping managers. * * <p> * The cache has two kind keys: * <p> * cached by the font mapping config * <ul> * <li> key: FontMappingConfig</li> * <li>value: each value is a HashMap * <ul> * <li>key: String[] sequence</li> * <li>value: FontMappingManager</li> * </ul> * </li> * </ul> * * cached by the format. * <ul> * <li>key: format</li> * <li>value: HashMap * <ul> * <li>key: locale</li> * <li>value: FontMappingManager</li> * </ul> * </li> * </ul> * */ protected HashMap cachedManagers = new HashMap( ); protected FontMappingManagerFactory( ) { // Register java fonts. registerJavaFonts(); // register the embedded font directorys String embeddedFonts = getEmbededFontPath( ); if ( embeddedFonts != null ) { registerFontPath( embeddedFonts ); } } public synchronized FontMappingManager getFontMappingManager( String format, Locale locale ) { HashMap managers = (HashMap) cachedManagers.get( format ); if ( managers == null ) { managers = new HashMap( ); cachedManagers.put( format, managers ); } FontMappingManager manager = (FontMappingManager) managers.get( locale ); if ( manager == null ) { manager = createFontMappingManager( format, locale ); managers.put( locale, manager ); } return manager; } public FontMappingManager createFontMappingManager( FontMappingConfig config, Locale locale ) { // Register the fonts defined in JRE fonts directory. registerJavaFonts( ); // register the fonts defined in the configuration Iterator iter = config.fontPaths.iterator( ); while ( iter.hasNext( ) ) { String fontPath = (String) iter.next( ); if ( !fontPathes.contains( fontPath ) ) { fontPathes.add( fontPath ); registerFontPath( fontPath ); } } // add the font encodings to the global encoding fontEncodings.putAll( config.fontEncodings ); return new FontMappingManager( this, null, config, locale ); } private void registerJavaFonts( ) { String javaHome = System.getProperty( "java.home" ); String fontsFolder = javaHome + File.separatorChar + "lib" + File.separatorChar + "fonts"; FontFactory.registerDirectory( fontsFolder ); } protected FontMappingManager createFontMappingManager( String format, Locale locale ) { + String formatString = format.toLowerCase(); // we have max 19 configs String[] configNames = new String[19]; int count = 0; String osgiName = getOSGIOSName( ); String osName = getOSName( ); String language = locale.getLanguage( ); String country = locale.getCountry( ); String variant = locale.getVariant( ); StringBuffer sb = new StringBuffer( ); // fontsConfig.xml configNames[count++] = sb.append( CONFIG_NAME ).toString( ); // fontsConfig_<osgi-os>.xml if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fontsConfig_<java-os>.xml if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); sb.append( CONFIG_NAME ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } sb.setLength( 0 ); // fontsConfig_format_<osgi-os> configNames[count++] = sb.append( CONFIG_NAME ).append( '_' ).append( - format ).toString( ); + formatString ).toString( ); if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fongsConfig_format_<java-os> if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); - sb.append( CONFIG_NAME ).append( '_' ).append( format ); + sb.append( CONFIG_NAME ).append( '_' ).append( formatString ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } FontMappingManager manager = null; for ( int i = 0; i < count; i++ ) { FontMappingConfig config = loadFontMappingConfig( configNames[i] ); if ( config != null ) { manager = createFontMappingManager( manager, config, locale ); } } return manager; } protected FontMappingManager createFontMappingManager( FontMappingManager parent, FontMappingConfig config, Locale locale ) { HashMap managers = (HashMap) cachedManagers.get( config ); if ( managers == null ) { managers = new HashMap( ); cachedManagers.put( config, managers ); } FontMappingManager manager = (FontMappingManager) managers.get( locale ); if ( manager == null ) { manager = new FontMappingManager( this, parent, config, locale ); managers.put( locale, manager ); } return manager; } static final String CONFIG_NAME = "fontsConfig"; private String getOSName( ) { String osName = System.getProperty( "os.name" ); if ( osName != null ) { return osName.replace( ' ', '_' ); } return null; } private String getOSGIOSName( ) { String osName = Platform.getOS( ); if ( Platform.OS_UNKNOWN.equals( osName ) ) { return null; } return osName; } protected FontMappingConfig getFontMappingConfig( String configName ) { FontMappingConfig config = (FontMappingConfig) cachedConfigs .get( configName ); if ( config == null ) { if ( !cachedConfigs.containsKey( configName ) ) { config = loadFontMappingConfig( configName ); cachedConfigs.put( configName, config ); } } return config; } /** * load the configuration file in the following order: * * @param format */ protected FontMappingConfig loadFontMappingConfig( String configName ) { // try to load the format specific configuration URL url = getConfigURL( configName ); if ( url != null ) { try { long start = System.currentTimeMillis( ); FontMappingConfig config = new FontConfigReader( ) .parseConfig( url ); long end = System.currentTimeMillis( ); logger.info( "load font config in " + url + " cost " + ( end - start ) + "ms" ); if ( config != null ) { // try to load the font in the fontPaths Iterator iter = config.fontPaths.iterator( ); while ( iter.hasNext( ) ) { String fontPath = (String) iter.next( ); if ( !fontPathes.contains( fontPath ) ) { fontPathes.add( fontPath ); registerFontPath( fontPath ); } } // add the font encodings to the global encoding fontEncodings.putAll( config.fontEncodings ); return config; } } catch ( Exception ex ) { logger.log( Level.WARNING, configName + ":" + ex.getMessage( ), ex ); } } return null; } protected URL getConfigURL( String configName ) { // try to load the format specific configuration Bundle bundle = Platform .getBundle( "org.eclipse.birt.report.engine.fonts" ); //$NON-NLS-1$ if ( bundle != null ) { return bundle.getEntry( configName + ".xml" ); } return null; } /** * All generated composite fonts. * * <p> * composite font are generated by the composite font configuration and the * search sequence. Each composite font also contains a parent. * * <p> * the cache structures are: * <ul> * <li>key: composite font configuration</li> * <li>value: HashMap which contains: * <ul> * <li>key: String[] search sequence</li> * <li>value: Composite font object</li> * </ul> * </li> * </ul> */ HashMap cachedCompositeFonts = new HashMap( ); CompositeFont createCompositeFont( FontMappingManager manager, CompositeFontConfig fontConfig, String[] sequence ) { HashMap fonts = (HashMap) cachedCompositeFonts.get( fontConfig ); if ( fonts == null ) { fonts = new HashMap( ); cachedCompositeFonts.put( fontConfig, fonts ); } CompositeFont font = (CompositeFont) fonts.get( sequence ); if ( font == null ) { font = new CompositeFont( manager, fontConfig, sequence ); fonts.put( sequence, font ); } return font; } private HashMap baseFonts = new HashMap( ); /** * Creates iText BaseFont with the given font family name. * * @param ffn * the specified font family name. * @return the created BaseFont. */ public BaseFont createFont( String familyName, int fontStyle ) { String key = familyName + fontStyle; synchronized ( baseFonts ) { BaseFont font = (BaseFont) baseFonts.get( key ); if ( font == null ) { try { String fontEncoding = (String) fontEncodings .get( familyName ); if ( fontEncoding == null ) { fontEncoding = BaseFont.IDENTITY_H; } // FIXME: code view verify if BaseFont.NOT_EMBEDDED or // BaseFont.EMBEDDED should be used. font = FontFactory.getFont( familyName, fontEncoding, BaseFont.NOT_EMBEDDED, 14, fontStyle ) .getBaseFont( ); if ( font != null ) { baseFonts.put( key, font ); } } catch ( Throwable de ) { return null; } } return font; } } private void registerFontPath( String fontPath ) { long start = System.currentTimeMillis( ); File file = new File( fontPath ); if ( file.exists( ) ) { if ( file.isDirectory( ) ) { FontFactory.registerDirectory( fontPath ); } else { FontFactory.register( fontPath ); } } long end = System.currentTimeMillis( ); logger.info( "register fonts in " + fontPath + " cost:" + ( end - start ) + "ms" ); } protected String getEmbededFontPath( ) { Bundle bundle = Platform .getBundle( "org.eclipse.birt.report.engine.fonts" ); //$NON-NLS-1$ Path path = new Path( "/fonts" ); //$NON-NLS-1$ URL fileURL = FileLocator.find( bundle, path, null ); if ( null == fileURL ) return null; String fontPath = null; try { // 171369 patch provided by Arne Degenring <public@degenring.de> fontPath = FileLocator.toFileURL( fileURL ).getPath( ); if ( fontPath != null && fontPath.length( ) >= 3 && fontPath.charAt( 2 ) == ':' ) { // truncate the first '/'; return fontPath.substring( 1 ); } else { return fontPath; } } catch ( IOException ioe ) { logger.log( Level.WARNING, ioe.getMessage( ), ioe ); return null; } } }
false
true
protected FontMappingManager createFontMappingManager( String format, Locale locale ) { // we have max 19 configs String[] configNames = new String[19]; int count = 0; String osgiName = getOSGIOSName( ); String osName = getOSName( ); String language = locale.getLanguage( ); String country = locale.getCountry( ); String variant = locale.getVariant( ); StringBuffer sb = new StringBuffer( ); // fontsConfig.xml configNames[count++] = sb.append( CONFIG_NAME ).toString( ); // fontsConfig_<osgi-os>.xml if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fontsConfig_<java-os>.xml if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); sb.append( CONFIG_NAME ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } sb.setLength( 0 ); // fontsConfig_format_<osgi-os> configNames[count++] = sb.append( CONFIG_NAME ).append( '_' ).append( format ).toString( ); if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fongsConfig_format_<java-os> if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); sb.append( CONFIG_NAME ).append( '_' ).append( format ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } FontMappingManager manager = null; for ( int i = 0; i < count; i++ ) { FontMappingConfig config = loadFontMappingConfig( configNames[i] ); if ( config != null ) { manager = createFontMappingManager( manager, config, locale ); } } return manager; }
protected FontMappingManager createFontMappingManager( String format, Locale locale ) { String formatString = format.toLowerCase(); // we have max 19 configs String[] configNames = new String[19]; int count = 0; String osgiName = getOSGIOSName( ); String osName = getOSName( ); String language = locale.getLanguage( ); String country = locale.getCountry( ); String variant = locale.getVariant( ); StringBuffer sb = new StringBuffer( ); // fontsConfig.xml configNames[count++] = sb.append( CONFIG_NAME ).toString( ); // fontsConfig_<osgi-os>.xml if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fontsConfig_<java-os>.xml if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); sb.append( CONFIG_NAME ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } sb.setLength( 0 ); // fontsConfig_format_<osgi-os> configNames[count++] = sb.append( CONFIG_NAME ).append( '_' ).append( formatString ).toString( ); if ( osgiName != null ) { configNames[count++] = sb.append( '_' ).append( osgiName ) .toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } // fongsConfig_format_<java-os> if ( osName != null && !osName.equals( osgiName ) ) { sb.setLength( 0 ); sb.append( CONFIG_NAME ).append( '_' ).append( formatString ); configNames[count++] = sb.append( '_' ).append( osName ).toString( ); configNames[count++] = sb.append( '_' ).append( language ) .toString( ); configNames[count++] = sb.append( '_' ).append( country ) .toString( ); configNames[count++] = sb.append( '_' ).append( variant ) .toString( ); } FontMappingManager manager = null; for ( int i = 0; i < count; i++ ) { FontMappingConfig config = loadFontMappingConfig( configNames[i] ); if ( config != null ) { manager = createFontMappingManager( manager, config, locale ); } } return manager; }
diff --git a/MobileWiki/src/com/mobilewiki/RequestHandler.java b/MobileWiki/src/com/mobilewiki/RequestHandler.java index 997a394..424044a 100644 --- a/MobileWiki/src/com/mobilewiki/RequestHandler.java +++ b/MobileWiki/src/com/mobilewiki/RequestHandler.java @@ -1,214 +1,214 @@ package com.mobilewiki; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONObject; import com.mobilewiki.controls.WebserviceAdapter; public class RequestHandler { private static RequestHandler _instance; private static WebserviceAdapter webserivce_adapter = new WebserviceAdapter(); public static RequestHandler getInstance() { if(null == _instance) { _instance = new RequestHandler(); } return _instance; } private RequestHandler() { _instance = this; } @SuppressWarnings("unchecked") public List<Integer> getArticleIds() { List<Integer> result = new ArrayList<Integer>(); try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getArticleIds"); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (List<Integer>) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } public String getTitleForArticleId(int article_id) { String result = ""; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getTitleForArticleId"); jsonobject_request.put("article_id", article_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (String) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } public int getArticleIdForTitle(String title) { int result = 0; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getArticleIdForTitle"); jsonobject_request.put("title", title); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = Integer.parseInt(jsonobject_response.get("result").toString()); } } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public List<Integer> getContentIdsforArticleId(int article_id) { List<Integer> result = new ArrayList<Integer>(); try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getContentIdsforArticleId"); jsonobject_request.put("article_id", article_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (List<Integer>) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } public String getDateChangeForContentId(int content_id) { String result = ""; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getDateChangeForContentId"); jsonobject_request.put("content_id", content_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (String) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } public int getArticleIdForContentId(int content_id) { int result = 0; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getArticleIdForContentId"); jsonobject_request.put("content_id", content_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = Integer.parseInt(jsonobject_response.get("result").toString()); } } catch (Exception e) { e.printStackTrace(); } return result; } public String getContentForContentId(int content_id) { String result = ""; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getContentForContentId"); jsonobject_request.put("content_id", content_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (String) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } public String getTagForContentId(int content_id) { String result = ""; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getTagForContentId"); jsonobject_request.put("content_id", content_id); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { result = (String) jsonobject_response.get("result"); } } catch (Exception e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") public Map<String, String> get_all_titles_with_tags() { Map<String, String> result = new HashMap<>(); String resultString; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getAllTitlesWithTags"); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { resultString = jsonobject_response.get("result").toString(); String[] resultArray = resultString.split("\n"); - for(int i = 0; i < result.size(); i += 2) { + for(int i = 0; i < resultArray.length; i += 2) { result.put(resultArray[i], resultArray[i + 1]); } } } catch (Exception e) { e.printStackTrace(); } return result; } }
true
true
public Map<String, String> get_all_titles_with_tags() { Map<String, String> result = new HashMap<>(); String resultString; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getAllTitlesWithTags"); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { resultString = jsonobject_response.get("result").toString(); String[] resultArray = resultString.split("\n"); for(int i = 0; i < result.size(); i += 2) { result.put(resultArray[i], resultArray[i + 1]); } } } catch (Exception e) { e.printStackTrace(); } return result; }
public Map<String, String> get_all_titles_with_tags() { Map<String, String> result = new HashMap<>(); String resultString; try { JSONObject jsonobject_request = new JSONObject(); jsonobject_request.put("function", "getAllTitlesWithTags"); JSONObject jsonobject_response = webserivce_adapter.callWebservice(jsonobject_request); if (jsonobject_response.get("result") != null) { resultString = jsonobject_response.get("result").toString(); String[] resultArray = resultString.split("\n"); for(int i = 0; i < resultArray.length; i += 2) { result.put(resultArray[i], resultArray[i + 1]); } } } catch (Exception e) { e.printStackTrace(); } return result; }
diff --git a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/AvailableServiceBindingController.java b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/AvailableServiceBindingController.java index df57d75c3..5ca4d9623 100755 --- a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/AvailableServiceBindingController.java +++ b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/AvailableServiceBindingController.java @@ -1,430 +1,431 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including 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.infoglue.cms.controllers.kernel.impl.simple; import java.util.Collection; import java.util.List; import org.apache.log4j.Logger; import org.exolab.castor.jdo.Database; import org.exolab.castor.jdo.OQLQuery; import org.exolab.castor.jdo.QueryResults; import org.infoglue.cms.entities.kernel.BaseEntityVO; import org.infoglue.cms.entities.management.AvailableServiceBinding; import org.infoglue.cms.entities.management.AvailableServiceBindingVO; import org.infoglue.cms.entities.management.SiteNodeTypeDefinition; import org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl; import org.infoglue.cms.entities.management.impl.simple.ServiceDefinitionImpl; import org.infoglue.cms.entities.management.impl.simple.SmallAvailableServiceBindingImpl; import org.infoglue.cms.exception.Bug; import org.infoglue.cms.exception.ConstraintException; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.util.ConstraintExceptionBuffer; import org.infoglue.deliver.util.CacheController; /** * This controller handles all available service bindings persistence and logic * * @author mattias */ public class AvailableServiceBindingController extends BaseController { private final static Logger logger = Logger.getLogger(AvailableServiceBindingController.class.getName()); /* * Factory method */ public static AvailableServiceBindingController getController() { return new AvailableServiceBindingController(); } public AvailableServiceBindingVO getAvailableServiceBindingVOWithId(Integer availableServiceBindingId) throws SystemException, Bug { return (AvailableServiceBindingVO)getVOWithId(SmallAvailableServiceBindingImpl.class, availableServiceBindingId); } public AvailableServiceBindingVO create(AvailableServiceBindingVO vo) throws ConstraintException, SystemException { AvailableServiceBinding ent = new AvailableServiceBindingImpl(); ent.setValueObject(vo); ent = (AvailableServiceBinding) createEntity(ent); return ent.getValueObject(); } /** * This method deletes an available service binding but only as long as * there are no siteNodes which has serviceBindings referencing it. */ public void delete(AvailableServiceBindingVO availableServiceBindingVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { AvailableServiceBinding availableServiceBinding = getAvailableServiceBindingWithId(availableServiceBindingVO.getAvailableServiceBindingId(), db); if(availableServiceBinding.getServiceBindings() != null && availableServiceBinding.getServiceBindings().size() > 0) { throw new ConstraintException("AvailableServiceBinding.deleteAction", "3100"); } } catch(ConstraintException ce) { throw ce; } catch(SystemException se) { throw se; } catch(Exception e) { throw new SystemException("An error occurred in AvailableServiceBindingController.delete(). Reason:" + e.getMessage(), e); } finally { commitTransaction(db); } deleteEntity(AvailableServiceBindingImpl.class, availableServiceBindingVO.getAvailableServiceBindingId()); } public AvailableServiceBinding getAvailableServiceBindingWithId(Integer availableServiceBindingId, Database db) throws SystemException, Bug { return (AvailableServiceBinding) getObjectWithId(AvailableServiceBindingImpl.class, availableServiceBindingId, db); } public AvailableServiceBinding getReadOnlyAvailableServiceBindingWithId(Integer availableServiceBindingId, Database db) throws SystemException, Bug { return (AvailableServiceBinding) getObjectWithIdAsReadOnly(AvailableServiceBindingImpl.class, availableServiceBindingId, db); } public List getAvailableServiceBindingVOList() throws SystemException, Bug { return getAllVOObjects(SmallAvailableServiceBindingImpl.class, "availableServiceBindingId"); } /** * This method fetches an available service binding with the given name. * * @throws SystemException * @throws Bug */ public AvailableServiceBindingVO getAvailableServiceBindingVOWithName(String name) throws SystemException, Bug { String key = "" + name; logger.info("key:" + key); AvailableServiceBindingVO availableServiceBindingVO = (AvailableServiceBindingVO)CacheController.getCachedObject("availableServiceBindingCache", key); if(availableServiceBindingVO != null) { logger.info("There was an cached availableServiceBindingVO:" + availableServiceBindingVO); } else { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { availableServiceBindingVO = getAvailableServiceBindingVOWithName(name, db); CacheController.cacheObject("availableServiceBindingCache", key, availableServiceBindingVO); commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException("An error occurred when we tried to fetch a list of AvailableServiceBinding. Reason:" + e.getMessage(), e); } } return availableServiceBindingVO; } /** * This method fetches an available service binding with the given name. * * @throws SystemException * @throws Bug */ public AvailableServiceBindingVO getAvailableServiceBindingVOWithName(String name, Database db) throws SystemException, Bug, Exception { String key = "" + name; logger.info("key:" + key); AvailableServiceBindingVO availableServiceBindingVO = (AvailableServiceBindingVO)CacheController.getCachedObject("availableServiceBindingCache", key); if(availableServiceBindingVO != null) { logger.info("There was an cached availableServiceBindingVO:" + availableServiceBindingVO); } else { OQLQuery oql = db.getOQLQuery( "SELECT asb FROM org.infoglue.cms.entities.management.impl.simple.SmallAvailableServiceBindingImpl asb WHERE asb.name = $1"); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { AvailableServiceBinding availableServiceBinding = (AvailableServiceBinding)results.next(); availableServiceBindingVO = availableServiceBinding.getValueObject(); logger.info("Found availableServiceBinding:" + availableServiceBindingVO.getName()); } results.close(); oql.close(); /* AvailableServiceBinding AvailableServiceBinding = getAvailableServiceBindingWithName(name, db, true); if(AvailableServiceBinding != null) availableServiceBindingVO = AvailableServiceBinding.getValueObject(); */ CacheController.cacheObject("availableServiceBindingCache", key, availableServiceBindingVO); } return availableServiceBindingVO; } /** * Returns the AvailableServiceBinding with the given name fetched within a given transaction. * * @param name * @param database * @return * @throws SystemException * @throws Bug */ public AvailableServiceBinding getAvailableServiceBindingWithName(String name, Database db, boolean readOnly) throws SystemException, Bug { AvailableServiceBinding availableServiceBinding = null; try { System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); - OQLQuery oql = db.getOQLQuery("SELECT a FROM org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl a WHERE a.name = $1"); + OQLQuery oql = db.getOQLQuery("SELECT a FROM org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl a WHERE a.name = $1 LIMIT $2"); oql.bind(name); + oql.bind(1); QueryResults results = null; if(readOnly) results = oql.execute(Database.ReadOnly); else { this.logger.info("Fetching entity in read/write mode:" + name); results = oql.execute(); } if(results.hasMore()) { availableServiceBinding = (AvailableServiceBinding)results.next(); } System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); results.close(); oql.close(); } catch(Exception e) { throw new SystemException("An error occurred when we tried to fetch a named AvailableServiceBinding. Reason:" + e.getMessage(), e); } //try{ throw new Exception("Hepp1"); }catch(Exception e){e.printStackTrace();} return availableServiceBinding; } /** * This method returns a List of all assigned AvailableServiceBindings available for a certain Repository. */ public List getAssignedAvailableServiceBindings(Integer siteNodeTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List assignedAvailableServiceBindingVOList = null; beginTransaction(db); try { SiteNodeTypeDefinition siteNodeTypeDefinition = SiteNodeTypeDefinitionController.getController().getSiteNodeTypeDefinitionWithId(siteNodeTypeDefinitionId, db); Collection assignedAvailableServiceBinding = siteNodeTypeDefinition.getAvailableServiceBindings(); assignedAvailableServiceBindingVOList = AvailableServiceBindingController.toVOList(assignedAvailableServiceBinding); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return assignedAvailableServiceBindingVOList; } public AvailableServiceBindingVO update(AvailableServiceBindingVO availableServiceBindingVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); AvailableServiceBinding availableServiceBinding = null; beginTransaction(db); try { //add validation here if needed availableServiceBinding = getAvailableServiceBindingWithId(availableServiceBindingVO.getAvailableServiceBindingId(), db); availableServiceBinding.setValueObject(availableServiceBindingVO); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return availableServiceBinding.getValueObject(); } public AvailableServiceBindingVO update(AvailableServiceBindingVO availableServiceBindingVO, String[] values) throws ConstraintException, SystemException { return (AvailableServiceBindingVO) updateEntity(AvailableServiceBindingImpl.class, (BaseEntityVO)availableServiceBindingVO, "setServiceDefinitions", ServiceDefinitionImpl.class, values ); } public AvailableServiceBinding update(Integer availableServiceBindingId, String[] values, Database db) throws ConstraintException, SystemException { AvailableServiceBinding availableServiceBinding = getAvailableServiceBindingWithId(availableServiceBindingId, db); return (AvailableServiceBinding) updateEntity(AvailableServiceBindingImpl.class, (BaseEntityVO)availableServiceBinding.getVO(), "setServiceDefinitions", ServiceDefinitionImpl.class, values ); } /** * This method returns a list of ServiceDefinitionVO-objects which are available for the * availableServiceBinding sent in. */ public List getServiceDefinitionVOList(Integer availableServiceBindingId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List serviceDefinitionVOList = null; beginTransaction(db); try { serviceDefinitionVOList = getServiceDefinitionVOList(db, availableServiceBindingId); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return serviceDefinitionVOList; } /** * This method returns a list of ServiceDefinitionVO-objects which are available for the * availableServiceBinding sent in. */ public List getServiceDefinitionVOList(Database db, Integer availableServiceBindingId) throws ConstraintException, SystemException { List serviceDefinitionVOList = null; AvailableServiceBinding availableServiceBinding = getReadOnlyAvailableServiceBindingWithId(availableServiceBindingId, db); Collection serviceDefinitionList = availableServiceBinding.getServiceDefinitions(); serviceDefinitionVOList = toVOList(serviceDefinitionList); return serviceDefinitionVOList; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new AvailableServiceBindingVO(); } }
false
true
public AvailableServiceBinding getAvailableServiceBindingWithName(String name, Database db, boolean readOnly) throws SystemException, Bug { AvailableServiceBinding availableServiceBinding = null; try { System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); OQLQuery oql = db.getOQLQuery("SELECT a FROM org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl a WHERE a.name = $1"); oql.bind(name); QueryResults results = null; if(readOnly) results = oql.execute(Database.ReadOnly); else { this.logger.info("Fetching entity in read/write mode:" + name); results = oql.execute(); } if(results.hasMore()) { availableServiceBinding = (AvailableServiceBinding)results.next(); } System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); results.close(); oql.close(); } catch(Exception e) { throw new SystemException("An error occurred when we tried to fetch a named AvailableServiceBinding. Reason:" + e.getMessage(), e); } //try{ throw new Exception("Hepp1"); }catch(Exception e){e.printStackTrace();} return availableServiceBinding; }
public AvailableServiceBinding getAvailableServiceBindingWithName(String name, Database db, boolean readOnly) throws SystemException, Bug { AvailableServiceBinding availableServiceBinding = null; try { System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); OQLQuery oql = db.getOQLQuery("SELECT a FROM org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl a WHERE a.name = $1 LIMIT $2"); oql.bind(name); oql.bind(1); QueryResults results = null; if(readOnly) results = oql.execute(Database.ReadOnly); else { this.logger.info("Fetching entity in read/write mode:" + name); results = oql.execute(); } if(results.hasMore()) { availableServiceBinding = (AvailableServiceBinding)results.next(); } System.out.println("\n\n\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); results.close(); oql.close(); } catch(Exception e) { throw new SystemException("An error occurred when we tried to fetch a named AvailableServiceBinding. Reason:" + e.getMessage(), e); } //try{ throw new Exception("Hepp1"); }catch(Exception e){e.printStackTrace();} return availableServiceBinding; }
diff --git a/core/src/main/java/org/apache/accumulo/core/util/shell/commands/MergeCommand.java b/core/src/main/java/org/apache/accumulo/core/util/shell/commands/MergeCommand.java index dae87dcfd..c3ca4adc6 100644 --- a/core/src/main/java/org/apache/accumulo/core/util/shell/commands/MergeCommand.java +++ b/core/src/main/java/org/apache/accumulo/core/util/shell/commands/MergeCommand.java @@ -1,112 +1,112 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.core.util.shell.commands; import java.io.IOException; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.util.Merge; import org.apache.accumulo.core.util.shell.Shell; import org.apache.accumulo.core.util.shell.Shell.Command; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.hadoop.io.Text; public class MergeCommand extends Command { private Option verboseOpt, forceOpt, sizeOpt, allOpt; @Override public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { boolean verbose = shellState.isVerbose(); boolean force = false; boolean all = false; long size = -1; final String tableName = OptUtil.getTableOpt(cl, shellState); final Text startRow = OptUtil.getStartRow(cl); final Text endRow = OptUtil.getEndRow(cl); if (cl.hasOption(verboseOpt.getOpt())) { verbose = true; } if (cl.hasOption(forceOpt.getOpt())) { force = true; } if (cl.hasOption(allOpt.getOpt())) { force = true; } if (cl.hasOption(sizeOpt.getOpt())) { size = AccumuloConfiguration.getMemoryInBytes(cl.getOptionValue(sizeOpt.getOpt())); } - if (startRow == null && endRow == null && size < 0 && all) { + if (startRow == null && endRow == null && size < 0 && !force) { shellState.getReader().flushConsole(); String line = shellState.getReader().readLine("Merge the entire table { " + tableName + " } into one tablet (yes|no)? "); if (line == null) return 0; if (!line.equalsIgnoreCase("y") && !line.equalsIgnoreCase("yes")) return 0; } if (size < 0) { shellState.getConnector().tableOperations().merge(tableName, startRow, endRow); } else { final boolean finalVerbose = verbose; final Merge merge = new Merge() { protected void message(String fmt, Object... args) { if (finalVerbose) { try { shellState.getReader().printString(String.format(fmt, args)); shellState.getReader().printNewline(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }; merge.mergomatic(shellState.getConnector(), tableName, startRow, endRow, size, force); } return 0; } @Override public String description() { return "merges tablets in a table"; } @Override public int numArgs() { return 0; } @Override public Options getOptions() { final Options o = new Options(); verboseOpt = new Option("v", "verbose", false, "verbose output during merge"); sizeOpt = new Option("s", "size", true, "merge tablets to the given size over the entire table"); forceOpt = new Option("f", "force", false, "merge small tablets to large tablets, even if it goes over the given size"); allOpt = new Option("", "all", false, "allow an entire table to be merged into one tablet without prompting the user for confirmation"); Option startRowOpt = OptUtil.startRowOpt(); startRowOpt.setDescription("begin row (NOT inclusive)"); o.addOption(startRowOpt); o.addOption(OptUtil.endRowOpt()); o.addOption(OptUtil.tableOpt("table to be merged")); o.addOption(verboseOpt); o.addOption(sizeOpt); o.addOption(forceOpt); o.addOption(allOpt); return o; } }
true
true
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { boolean verbose = shellState.isVerbose(); boolean force = false; boolean all = false; long size = -1; final String tableName = OptUtil.getTableOpt(cl, shellState); final Text startRow = OptUtil.getStartRow(cl); final Text endRow = OptUtil.getEndRow(cl); if (cl.hasOption(verboseOpt.getOpt())) { verbose = true; } if (cl.hasOption(forceOpt.getOpt())) { force = true; } if (cl.hasOption(allOpt.getOpt())) { force = true; } if (cl.hasOption(sizeOpt.getOpt())) { size = AccumuloConfiguration.getMemoryInBytes(cl.getOptionValue(sizeOpt.getOpt())); } if (startRow == null && endRow == null && size < 0 && all) { shellState.getReader().flushConsole(); String line = shellState.getReader().readLine("Merge the entire table { " + tableName + " } into one tablet (yes|no)? "); if (line == null) return 0; if (!line.equalsIgnoreCase("y") && !line.equalsIgnoreCase("yes")) return 0; } if (size < 0) { shellState.getConnector().tableOperations().merge(tableName, startRow, endRow); } else { final boolean finalVerbose = verbose; final Merge merge = new Merge() { protected void message(String fmt, Object... args) { if (finalVerbose) { try { shellState.getReader().printString(String.format(fmt, args)); shellState.getReader().printNewline(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }; merge.mergomatic(shellState.getConnector(), tableName, startRow, endRow, size, force); } return 0; }
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { boolean verbose = shellState.isVerbose(); boolean force = false; boolean all = false; long size = -1; final String tableName = OptUtil.getTableOpt(cl, shellState); final Text startRow = OptUtil.getStartRow(cl); final Text endRow = OptUtil.getEndRow(cl); if (cl.hasOption(verboseOpt.getOpt())) { verbose = true; } if (cl.hasOption(forceOpt.getOpt())) { force = true; } if (cl.hasOption(allOpt.getOpt())) { force = true; } if (cl.hasOption(sizeOpt.getOpt())) { size = AccumuloConfiguration.getMemoryInBytes(cl.getOptionValue(sizeOpt.getOpt())); } if (startRow == null && endRow == null && size < 0 && !force) { shellState.getReader().flushConsole(); String line = shellState.getReader().readLine("Merge the entire table { " + tableName + " } into one tablet (yes|no)? "); if (line == null) return 0; if (!line.equalsIgnoreCase("y") && !line.equalsIgnoreCase("yes")) return 0; } if (size < 0) { shellState.getConnector().tableOperations().merge(tableName, startRow, endRow); } else { final boolean finalVerbose = verbose; final Merge merge = new Merge() { protected void message(String fmt, Object... args) { if (finalVerbose) { try { shellState.getReader().printString(String.format(fmt, args)); shellState.getReader().printNewline(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }; merge.mergomatic(shellState.getConnector(), tableName, startRow, endRow, size, force); } return 0; }
diff --git a/tiling/src/com/razh/tiling/Actor3D.java b/tiling/src/com/razh/tiling/Actor3D.java index 6352819..4f1782d 100644 --- a/tiling/src/com/razh/tiling/Actor3D.java +++ b/tiling/src/com/razh/tiling/Actor3D.java @@ -1,65 +1,65 @@ package com.razh.tiling; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Actor; public class Actor3D extends Actor { private float mZ; private float mDepth; public float getZ() { return mZ; } public void setZ(float z) { mZ = z; } public Vector2 getPosition2D() { return new Vector2(getX(), getY()); } public Vector3 getPosition() { return new Vector3(getX(), getY(), getZ()); } public void setPosition(Vector3 position) { super.setPosition(position.x, position.y); setZ(position.z); } @Override public void setPosition(float x, float y) { super.setPosition(x, y); } public void setPosition(float x, float y, float z) { super.setPosition(x, y); setZ(z); } public void translate(float x, float y, float z) { super.translate(x, y); setZ(getZ() + z); } public float getDepth() { return mDepth; } public void setDepth(float depth) { mDepth = depth; } /** * @param actor * @return Normalized vector from this to actor. */ public Vector3 vectorTo(Actor3D actor) { return actor.getPosition() - .cpy() + .cpy() .sub(getPosition()) .nor(); } }
true
true
public Vector3 vectorTo(Actor3D actor) { return actor.getPosition() .cpy() .sub(getPosition()) .nor(); }
public Vector3 vectorTo(Actor3D actor) { return actor.getPosition() .cpy() .sub(getPosition()) .nor(); }
diff --git a/src/main/java/org/sonar/ide/intellij/worker/RefreshSonarFileWorker.java b/src/main/java/org/sonar/ide/intellij/worker/RefreshSonarFileWorker.java index b0f8ec2..d0ca2c9 100644 --- a/src/main/java/org/sonar/ide/intellij/worker/RefreshSonarFileWorker.java +++ b/src/main/java/org/sonar/ide/intellij/worker/RefreshSonarFileWorker.java @@ -1,66 +1,66 @@ package org.sonar.ide.intellij.worker; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.sonar.ide.intellij.component.SonarModuleComponent; import org.sonar.ide.intellij.listener.RefreshListener; import org.sonar.ide.intellij.utils.SonarResourceKeyUtils; import org.sonar.wsclient.Sonar; import org.sonar.wsclient.services.Model; import org.sonar.wsclient.services.Query; import javax.swing.*; import java.util.ArrayList; import java.util.List; public abstract class RefreshSonarFileWorker<T extends Model> extends SwingWorker<List<T>, Void> { private Project project; protected VirtualFile virtualFile; private List<RefreshListener<T>> listeners = new ArrayList<RefreshListener<T>>(); protected RefreshSonarFileWorker(Project project, VirtualFile virtualFile) { this.project = project; this.virtualFile = virtualFile; } public void addListener(RefreshListener<T> listener) { listeners.add(listener); } @Override protected List<T> doInBackground() throws Exception { String resourceKey = getResourceKey(); if (resourceKey == null) { - return null; + return new ArrayList<T>(); } Sonar sonar = getSonar(); Query<T> query = getQuery(resourceKey); return sonar.findAll(query); } protected void notifyListeners(List<T> results) { for (RefreshListener<T> listener : this.listeners) { listener.doneRefresh(this.virtualFile, results); } } protected abstract Query<T> getQuery(String resourceKey); private Sonar getSonar() { return getSonarModuleComponent().getSonar(); } protected String getResourceKey() { return SonarResourceKeyUtils.createFileResourceKey(this.project, virtualFile); } private SonarModuleComponent getSonarModuleComponent() { return SonarResourceKeyUtils.getSonarModuleComponent(project, virtualFile); } protected Project getProject() { return project; } }
true
true
protected List<T> doInBackground() throws Exception { String resourceKey = getResourceKey(); if (resourceKey == null) { return null; } Sonar sonar = getSonar(); Query<T> query = getQuery(resourceKey); return sonar.findAll(query); }
protected List<T> doInBackground() throws Exception { String resourceKey = getResourceKey(); if (resourceKey == null) { return new ArrayList<T>(); } Sonar sonar = getSonar(); Query<T> query = getQuery(resourceKey); return sonar.findAll(query); }
diff --git a/pixi/src/main/java/org/openpixi/pixi/ui/MainBatch.java b/pixi/src/main/java/org/openpixi/pixi/ui/MainBatch.java index 8f3bc4f1..bef781c0 100644 --- a/pixi/src/main/java/org/openpixi/pixi/ui/MainBatch.java +++ b/pixi/src/main/java/org/openpixi/pixi/ui/MainBatch.java @@ -1,113 +1,113 @@ /* * OpenPixi - Open Particle-In-Cell (PIC) Simulator * Copyright (C) 2012 OpenPixi.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.openpixi.pixi.ui; import org.openpixi.pixi.physics.Debug; import org.openpixi.pixi.physics.Settings; import org.openpixi.pixi.physics.Simulation; import org.openpixi.pixi.diagnostics.Diagnostics; import org.openpixi.pixi.diagnostics.methods.KineticEnergy; import org.openpixi.pixi.diagnostics.methods.Potential; import org.openpixi.pixi.profile.ProfileInfo; import org.openpixi.pixi.ui.util.*; import java.io.IOException; public class MainBatch { /**Total number of iterations*/ public static int iterations; public static int particleDiagnosticsIntervall; public static int gridDiagnosticsIntervall; private static String runid; private static Simulation s; private static Diagnostics diagnostics; private static EmptyParticleDataOutput pdo; private static EmptyGridDataOutput gdo; public static void main(String[] args) { Debug.checkAssertsEnabled(); Settings settings = new Settings(); if (args.length != 0){ Parser parser = new Parser(settings); parser.parse(args[0]); } iterations = settings.getIterations(); particleDiagnosticsIntervall = settings.getParticleDiagnosticsIntervall(); gridDiagnosticsIntervall = settings.getGridDiagnosticsIntervall(); runid = settings.getRunid(); s = new Simulation(settings); settings.getGridDiagnostics().add(new Potential(s.grid)); diagnostics = new Diagnostics(s.grid, s.particles, settings); if (args.length < 2) { pdo = new EmptyParticleDataOutput(); gdo = new EmptyGridDataOutput(); } else { if (args[1].substring(args[1].length() -1) != System.getProperty("file.separator")) { args[1] = args[1] + System.getProperty("file.separator"); } try { pdo = new ParticleDataOutput(args[1], runid); gdo = new GridDataOutput(args[1], runid, s.grid); } catch (IOException e) { System.err.print("Something went wrong when creating output files for diagnostics! \n" + "Please specify an output directory with write access rights!\n" + "The directory that you specified was " + args[1] + "\n" + "Aborting..."); return; } } pdo.startIteration(0); diagnostics.particles(); diagnostics.outputParticles(pdo); gdo.startIteration(0); diagnostics.grid(); diagnostics.outputGrid(gdo); for (int i = 0; i < iterations; i++) { s.step(); if ( i == particleDiagnosticsIntervall) { pdo.startIteration(i); diagnostics.particles(); diagnostics.outputParticles(pdo); - particleDiagnosticsIntervall *= 2; + particleDiagnosticsIntervall += particleDiagnosticsIntervall; } if ( i == gridDiagnosticsIntervall) { gdo.startIteration(i); diagnostics.grid(); diagnostics.outputGrid(gdo); - gridDiagnosticsIntervall *= 2; + gridDiagnosticsIntervall += gridDiagnosticsIntervall; } } pdo.closeStreams(); gdo.closeStreams(); ProfileInfo.printProfileInfo(); } }
false
true
public static void main(String[] args) { Debug.checkAssertsEnabled(); Settings settings = new Settings(); if (args.length != 0){ Parser parser = new Parser(settings); parser.parse(args[0]); } iterations = settings.getIterations(); particleDiagnosticsIntervall = settings.getParticleDiagnosticsIntervall(); gridDiagnosticsIntervall = settings.getGridDiagnosticsIntervall(); runid = settings.getRunid(); s = new Simulation(settings); settings.getGridDiagnostics().add(new Potential(s.grid)); diagnostics = new Diagnostics(s.grid, s.particles, settings); if (args.length < 2) { pdo = new EmptyParticleDataOutput(); gdo = new EmptyGridDataOutput(); } else { if (args[1].substring(args[1].length() -1) != System.getProperty("file.separator")) { args[1] = args[1] + System.getProperty("file.separator"); } try { pdo = new ParticleDataOutput(args[1], runid); gdo = new GridDataOutput(args[1], runid, s.grid); } catch (IOException e) { System.err.print("Something went wrong when creating output files for diagnostics! \n" + "Please specify an output directory with write access rights!\n" + "The directory that you specified was " + args[1] + "\n" + "Aborting..."); return; } } pdo.startIteration(0); diagnostics.particles(); diagnostics.outputParticles(pdo); gdo.startIteration(0); diagnostics.grid(); diagnostics.outputGrid(gdo); for (int i = 0; i < iterations; i++) { s.step(); if ( i == particleDiagnosticsIntervall) { pdo.startIteration(i); diagnostics.particles(); diagnostics.outputParticles(pdo); particleDiagnosticsIntervall *= 2; } if ( i == gridDiagnosticsIntervall) { gdo.startIteration(i); diagnostics.grid(); diagnostics.outputGrid(gdo); gridDiagnosticsIntervall *= 2; } } pdo.closeStreams(); gdo.closeStreams(); ProfileInfo.printProfileInfo(); }
public static void main(String[] args) { Debug.checkAssertsEnabled(); Settings settings = new Settings(); if (args.length != 0){ Parser parser = new Parser(settings); parser.parse(args[0]); } iterations = settings.getIterations(); particleDiagnosticsIntervall = settings.getParticleDiagnosticsIntervall(); gridDiagnosticsIntervall = settings.getGridDiagnosticsIntervall(); runid = settings.getRunid(); s = new Simulation(settings); settings.getGridDiagnostics().add(new Potential(s.grid)); diagnostics = new Diagnostics(s.grid, s.particles, settings); if (args.length < 2) { pdo = new EmptyParticleDataOutput(); gdo = new EmptyGridDataOutput(); } else { if (args[1].substring(args[1].length() -1) != System.getProperty("file.separator")) { args[1] = args[1] + System.getProperty("file.separator"); } try { pdo = new ParticleDataOutput(args[1], runid); gdo = new GridDataOutput(args[1], runid, s.grid); } catch (IOException e) { System.err.print("Something went wrong when creating output files for diagnostics! \n" + "Please specify an output directory with write access rights!\n" + "The directory that you specified was " + args[1] + "\n" + "Aborting..."); return; } } pdo.startIteration(0); diagnostics.particles(); diagnostics.outputParticles(pdo); gdo.startIteration(0); diagnostics.grid(); diagnostics.outputGrid(gdo); for (int i = 0; i < iterations; i++) { s.step(); if ( i == particleDiagnosticsIntervall) { pdo.startIteration(i); diagnostics.particles(); diagnostics.outputParticles(pdo); particleDiagnosticsIntervall += particleDiagnosticsIntervall; } if ( i == gridDiagnosticsIntervall) { gdo.startIteration(i); diagnostics.grid(); diagnostics.outputGrid(gdo); gridDiagnosticsIntervall += gridDiagnosticsIntervall; } } pdo.closeStreams(); gdo.closeStreams(); ProfileInfo.printProfileInfo(); }
diff --git a/src/nl/b3p/viewer/config/services/JDBCFeatureSource.java b/src/nl/b3p/viewer/config/services/JDBCFeatureSource.java index 9e7cf6ba1..4505ceefc 100644 --- a/src/nl/b3p/viewer/config/services/JDBCFeatureSource.java +++ b/src/nl/b3p/viewer/config/services/JDBCFeatureSource.java @@ -1,212 +1,212 @@ /* * Copyright (C) 2011 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.config.services; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.*; import nl.b3p.web.WaitPageStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.json.JSONException; import org.json.JSONObject; import org.opengis.feature.type.AttributeType; /** * * @author jytte * @author Matthijs Laan */ @Entity @DiscriminatorValue(JDBCFeatureSource.PROTOCOL) public class JDBCFeatureSource extends FeatureSource { private static final Log log = LogFactory.getLog(JDBCFeatureSource.class); public static final String PROTOCOL = "jdbc"; @Column(name="db_schema") private String schema; public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public JDBCFeatureSource(){ super(); } public JDBCFeatureSource(Map params) throws JSONException { super(); JSONObject urlObj = new JSONObject(); urlObj.put("dbtype", params.get("dbtype")); urlObj.put("host", params.get("host")); urlObj.put("port", params.get("port")); urlObj.put("database", params.get("database")); setUrl(urlObj.toString()); schema = (String)params.get("schema"); setUsername((String)params.get("user")); setPassword((String)params.get("passwd")); } public void loadFeatureTypes() throws Exception { loadFeatureTypes(new WaitPageStatus()); } public void loadFeatureTypes(WaitPageStatus status) throws Exception { status.setCurrentAction("Databaseverbinding maken..."); DataStore store = null; try { store = createDataStore(); status.setProgress(10); status.setCurrentAction("Lijst van tabellen met geo-informatie ophalen..."); String[] typeNames = store.getTypeNames(); status.setProgress(20); if(typeNames.length != 0) { double progress = 20.0; double progressPerTypeName = (80.0/typeNames.length); for(String typeName: typeNames) { status.setCurrentAction("Inladen schema van tabel \"" + typeName + "\"..."); log.debug("Loading feature source " + typeName + " for JDBCFeatureSource " + getName()); SimpleFeatureSource gtFs = store.getFeatureSource(typeName); SimpleFeatureType sft = new SimpleFeatureType(); sft.setTypeName(typeName); sft.setFeatureSource(this); sft.setWriteable(true); if(gtFs.getInfo() != null) { sft.setDescription(gtFs.getInfo().getDescription()); } org.opengis.feature.simple.SimpleFeatureType gtFt = gtFs.getSchema(); for(org.opengis.feature.type.AttributeDescriptor gtAtt: gtFt.getAttributeDescriptors()) { AttributeDescriptor att = new AttributeDescriptor(); sft.getAttributes().add(att); att.setName(gtAtt.getLocalName()); AttributeType gtType = gtAtt.getType(); String binding = gtType.getBinding().getName(); /* XXX use instanceof... */ String type = ""; if(binding.equals("com.vividsolutions.jts.geom.MultiPolygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Polygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Geometry")){ type = AttributeDescriptor.TYPE_GEOMETRY; }else if(binding.equals("com.vividsolutions.jts.geom.LineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.Point")){ type = AttributeDescriptor.TYPE_GEOMETRY_POINT; }else if(binding.equals("com.vividsolutions.jts.geom.MultiLineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_MLINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.MultiPoint")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT; }else if(binding.equals("java.lang.Boolean")){ type = AttributeDescriptor.TYPE_BOOLEAN; }else if(binding.equals("java.lang.Long")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.String")){ type = AttributeDescriptor.TYPE_STRING; }else if(binding.equals("java.lang.Integer")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Short")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Double")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.lang.Float")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.sql.Timestamp")){ type = AttributeDescriptor.TYPE_TIMESTAMP; }else if(binding.equals("java.sql.Date")){ type = AttributeDescriptor.TYPE_DATE; }else if(binding.equals("java.math.BigDecimal")){ type = AttributeDescriptor.TYPE_DOUBLE; } - if(sft.getGeometryAttribute() == null && type.startsWith("com.vividsolutions.jts.geom")) { + if(sft.getGeometryAttribute() == null && binding.startsWith("com.vividsolutions.jts.geom")) { sft.setGeometryAttribute(att.getName()); } att.setType(type); } this.getFeatureTypes().add(sft); progress += progressPerTypeName; status.setProgress((int)progress); } } } finally { status.setProgress(100); status.setCurrentAction("Databasegegevens ingeladen"); status.setFinished(true); if(store != null) { store.dispose(); } } } public DataStore createDataStore() throws Exception { Map params = new HashMap(); JSONObject urlObj = new JSONObject(getUrl()); params.put("dbtype", urlObj.get("dbtype")); params.put("host", urlObj.get("host")); params.put("port", urlObj.get("port")); params.put("database", urlObj.get("database")); params.put("schema", schema); params.put("user", getUsername()); params.put("passwd", getPassword()); log.debug("Opening datastore using parameters: " + params); try { DataStore ds = DataStoreFinder.getDataStore(params); if(ds == null) { throw new Exception("Cannot open datastore using parameters " + params); } return ds; } catch(Exception e) { throw new Exception("Cannot open datastore using parameters " + params, e); } } @Override List<String> calculateUniqueValues(SimpleFeatureType sft, String attributeName, int maxFeatures) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override org.geotools.data.FeatureSource openGeoToolsFeatureSource(SimpleFeatureType sft) throws Exception { DataStore ds = createDataStore(); return ds.getFeatureSource(sft.getTypeName()); } }
true
true
public void loadFeatureTypes(WaitPageStatus status) throws Exception { status.setCurrentAction("Databaseverbinding maken..."); DataStore store = null; try { store = createDataStore(); status.setProgress(10); status.setCurrentAction("Lijst van tabellen met geo-informatie ophalen..."); String[] typeNames = store.getTypeNames(); status.setProgress(20); if(typeNames.length != 0) { double progress = 20.0; double progressPerTypeName = (80.0/typeNames.length); for(String typeName: typeNames) { status.setCurrentAction("Inladen schema van tabel \"" + typeName + "\"..."); log.debug("Loading feature source " + typeName + " for JDBCFeatureSource " + getName()); SimpleFeatureSource gtFs = store.getFeatureSource(typeName); SimpleFeatureType sft = new SimpleFeatureType(); sft.setTypeName(typeName); sft.setFeatureSource(this); sft.setWriteable(true); if(gtFs.getInfo() != null) { sft.setDescription(gtFs.getInfo().getDescription()); } org.opengis.feature.simple.SimpleFeatureType gtFt = gtFs.getSchema(); for(org.opengis.feature.type.AttributeDescriptor gtAtt: gtFt.getAttributeDescriptors()) { AttributeDescriptor att = new AttributeDescriptor(); sft.getAttributes().add(att); att.setName(gtAtt.getLocalName()); AttributeType gtType = gtAtt.getType(); String binding = gtType.getBinding().getName(); /* XXX use instanceof... */ String type = ""; if(binding.equals("com.vividsolutions.jts.geom.MultiPolygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Polygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Geometry")){ type = AttributeDescriptor.TYPE_GEOMETRY; }else if(binding.equals("com.vividsolutions.jts.geom.LineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.Point")){ type = AttributeDescriptor.TYPE_GEOMETRY_POINT; }else if(binding.equals("com.vividsolutions.jts.geom.MultiLineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_MLINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.MultiPoint")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT; }else if(binding.equals("java.lang.Boolean")){ type = AttributeDescriptor.TYPE_BOOLEAN; }else if(binding.equals("java.lang.Long")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.String")){ type = AttributeDescriptor.TYPE_STRING; }else if(binding.equals("java.lang.Integer")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Short")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Double")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.lang.Float")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.sql.Timestamp")){ type = AttributeDescriptor.TYPE_TIMESTAMP; }else if(binding.equals("java.sql.Date")){ type = AttributeDescriptor.TYPE_DATE; }else if(binding.equals("java.math.BigDecimal")){ type = AttributeDescriptor.TYPE_DOUBLE; } if(sft.getGeometryAttribute() == null && type.startsWith("com.vividsolutions.jts.geom")) { sft.setGeometryAttribute(att.getName()); } att.setType(type); } this.getFeatureTypes().add(sft); progress += progressPerTypeName; status.setProgress((int)progress); } } } finally { status.setProgress(100); status.setCurrentAction("Databasegegevens ingeladen"); status.setFinished(true); if(store != null) { store.dispose(); } } }
public void loadFeatureTypes(WaitPageStatus status) throws Exception { status.setCurrentAction("Databaseverbinding maken..."); DataStore store = null; try { store = createDataStore(); status.setProgress(10); status.setCurrentAction("Lijst van tabellen met geo-informatie ophalen..."); String[] typeNames = store.getTypeNames(); status.setProgress(20); if(typeNames.length != 0) { double progress = 20.0; double progressPerTypeName = (80.0/typeNames.length); for(String typeName: typeNames) { status.setCurrentAction("Inladen schema van tabel \"" + typeName + "\"..."); log.debug("Loading feature source " + typeName + " for JDBCFeatureSource " + getName()); SimpleFeatureSource gtFs = store.getFeatureSource(typeName); SimpleFeatureType sft = new SimpleFeatureType(); sft.setTypeName(typeName); sft.setFeatureSource(this); sft.setWriteable(true); if(gtFs.getInfo() != null) { sft.setDescription(gtFs.getInfo().getDescription()); } org.opengis.feature.simple.SimpleFeatureType gtFt = gtFs.getSchema(); for(org.opengis.feature.type.AttributeDescriptor gtAtt: gtFt.getAttributeDescriptors()) { AttributeDescriptor att = new AttributeDescriptor(); sft.getAttributes().add(att); att.setName(gtAtt.getLocalName()); AttributeType gtType = gtAtt.getType(); String binding = gtType.getBinding().getName(); /* XXX use instanceof... */ String type = ""; if(binding.equals("com.vividsolutions.jts.geom.MultiPolygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Polygon")){ type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON; }else if(binding.equals("com.vividsolutions.jts.geom.Geometry")){ type = AttributeDescriptor.TYPE_GEOMETRY; }else if(binding.equals("com.vividsolutions.jts.geom.LineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.Point")){ type = AttributeDescriptor.TYPE_GEOMETRY_POINT; }else if(binding.equals("com.vividsolutions.jts.geom.MultiLineString")){ type = AttributeDescriptor.TYPE_GEOMETRY_MLINESTRING; }else if(binding.equals("com.vividsolutions.jts.geom.MultiPoint")){ type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT; }else if(binding.equals("java.lang.Boolean")){ type = AttributeDescriptor.TYPE_BOOLEAN; }else if(binding.equals("java.lang.Long")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.String")){ type = AttributeDescriptor.TYPE_STRING; }else if(binding.equals("java.lang.Integer")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Short")){ type = AttributeDescriptor.TYPE_INTEGER; }else if(binding.equals("java.lang.Double")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.lang.Float")){ type = AttributeDescriptor.TYPE_DOUBLE; }else if(binding.equals("java.sql.Timestamp")){ type = AttributeDescriptor.TYPE_TIMESTAMP; }else if(binding.equals("java.sql.Date")){ type = AttributeDescriptor.TYPE_DATE; }else if(binding.equals("java.math.BigDecimal")){ type = AttributeDescriptor.TYPE_DOUBLE; } if(sft.getGeometryAttribute() == null && binding.startsWith("com.vividsolutions.jts.geom")) { sft.setGeometryAttribute(att.getName()); } att.setType(type); } this.getFeatureTypes().add(sft); progress += progressPerTypeName; status.setProgress((int)progress); } } } finally { status.setProgress(100); status.setCurrentAction("Databasegegevens ingeladen"); status.setFinished(true); if(store != null) { store.dispose(); } } }
diff --git a/src/com/jbalboni/vacation/LeaveStateManager.java b/src/com/jbalboni/vacation/LeaveStateManager.java index 2a04b7d..9351c3a 100644 --- a/src/com/jbalboni/vacation/LeaveStateManager.java +++ b/src/com/jbalboni/vacation/LeaveStateManager.java @@ -1,47 +1,55 @@ package com.jbalboni.vacation; import java.util.ArrayList; import java.util.List; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public final class LeaveStateManager { private static final DateTimeFormatter fmt = ISODateTimeFormat.localDateParser(); public static VacationTracker createVacationTracker(SharedPreferences prefs, String categoryPrefix) { String startDateStr = prefs.getString("startDate",null); String leaveInterval = prefs.getString("leaveInterval", "Daily"); + if (leaveInterval.equals("Day")) + leaveInterval = "Daily"; + else if (leaveInterval.equals("Week")) + leaveInterval = "Weekly"; + else if (leaveInterval.equals("Month")) + leaveInterval = "Monthly"; + else + leaveInterval = "Daily"; LocalDate startDate = startDateStr == null ? new LocalDate() : fmt.parseLocalDate(startDateStr); Float hoursUsed = Float.parseFloat(prefs.getString(categoryPrefix+"hoursUsed", "0")); float hoursPerYear = Float.parseFloat(prefs.getString(categoryPrefix+"hoursPerYear", "80")); float initialHours = Float.parseFloat(prefs.getString(categoryPrefix+"initialHours", "0")); boolean accrualOn = prefs.getBoolean(categoryPrefix+"accrualOn", true); return new VacationTracker(startDate,hoursUsed,hoursPerYear,initialHours,leaveInterval,accrualOn); } public static void saveVacationTracker(VacationTracker vacationTracker, SharedPreferences prefs, String categoryPrefix) { Editor prefsEditor = prefs.edit(); prefsEditor.putString(categoryPrefix+"hoursUsed", Float.toString(vacationTracker.getHoursUsed())); prefsEditor.putString(categoryPrefix+"hoursPerYear", Float.toString(vacationTracker.getHoursPerYear())); prefsEditor.putString(categoryPrefix+"intialHours", Float.toString(vacationTracker.getInitialHours())); prefsEditor.putBoolean(categoryPrefix+"accrualOn", vacationTracker.isAccrualOn()); prefsEditor.putString("startDate", String.format("%4d-%02d-%02d",vacationTracker.getStartDate().getYear(),vacationTracker.getStartDate().getMonthOfYear() ,vacationTracker.getStartDate().getDayOfMonth())); prefsEditor.commit(); } public static List<String> getTitles(SharedPreferences prefs, Context ctxt) { List<String> titles = new ArrayList<String>(); titles.add(prefs.getString(LeaveCategory.LEFT.getPrefix()+"title", ctxt.getString(R.string.default_left_name))); titles.add(prefs.getString(LeaveCategory.CENTER.getPrefix()+"title", ctxt.getString(R.string.default_center_name))); titles.add(prefs.getString(LeaveCategory.RIGHT.getPrefix()+"title", ctxt.getString(R.string.default_right_name))); return titles; } }
true
true
public static VacationTracker createVacationTracker(SharedPreferences prefs, String categoryPrefix) { String startDateStr = prefs.getString("startDate",null); String leaveInterval = prefs.getString("leaveInterval", "Daily"); LocalDate startDate = startDateStr == null ? new LocalDate() : fmt.parseLocalDate(startDateStr); Float hoursUsed = Float.parseFloat(prefs.getString(categoryPrefix+"hoursUsed", "0")); float hoursPerYear = Float.parseFloat(prefs.getString(categoryPrefix+"hoursPerYear", "80")); float initialHours = Float.parseFloat(prefs.getString(categoryPrefix+"initialHours", "0")); boolean accrualOn = prefs.getBoolean(categoryPrefix+"accrualOn", true); return new VacationTracker(startDate,hoursUsed,hoursPerYear,initialHours,leaveInterval,accrualOn); }
public static VacationTracker createVacationTracker(SharedPreferences prefs, String categoryPrefix) { String startDateStr = prefs.getString("startDate",null); String leaveInterval = prefs.getString("leaveInterval", "Daily"); if (leaveInterval.equals("Day")) leaveInterval = "Daily"; else if (leaveInterval.equals("Week")) leaveInterval = "Weekly"; else if (leaveInterval.equals("Month")) leaveInterval = "Monthly"; else leaveInterval = "Daily"; LocalDate startDate = startDateStr == null ? new LocalDate() : fmt.parseLocalDate(startDateStr); Float hoursUsed = Float.parseFloat(prefs.getString(categoryPrefix+"hoursUsed", "0")); float hoursPerYear = Float.parseFloat(prefs.getString(categoryPrefix+"hoursPerYear", "80")); float initialHours = Float.parseFloat(prefs.getString(categoryPrefix+"initialHours", "0")); boolean accrualOn = prefs.getBoolean(categoryPrefix+"accrualOn", true); return new VacationTracker(startDate,hoursUsed,hoursPerYear,initialHours,leaveInterval,accrualOn); }
diff --git a/JavaClass.java b/JavaClass.java index 156d915..2382973 100644 --- a/JavaClass.java +++ b/JavaClass.java @@ -1,483 +1,481 @@ /* * Copyright (c) 2011 Xamarin Inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package jar2xml; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.w3c.dom.Document; import org.w3c.dom.Element; public class JavaClass implements Comparable<JavaClass> { private Class jclass; private List<String> deprecatedFields; private List<String> deprecatedMethods; public JavaClass (Class jclass) { this.jclass = jclass; deprecatedFields = AndroidDocScraper.getDeprecatedFields (jclass); deprecatedMethods = AndroidDocScraper.getDeprecatedMethods (jclass); } public int compareTo (JavaClass jc) { return getName ().compareTo (jc.getName ()); } public String getName () { return jclass.getName (); } String[] getParameterNames (String name, Type[] types, boolean isVarArgs) { for (IDocScraper s : scrapers) { String[] names = s.getParameterNames (jclass, name, types, isVarArgs); if (names != null && names.length > 0) return names; } return null; } void appendParameters (String name, Type[] types, boolean isVarArgs, Document doc, Element parent) { if (types == null || types.length == 0) return; String[] names = getParameterNames (name, types, isVarArgs); int cnt = 0; for (int i = 0; i < types.length; i++) { Element e = doc.createElement ("parameter"); e.setAttribute ("name", names == null ? "p" + i : names [i]); String type = getGenericTypeName (types [i]); if (isVarArgs && i == types.length - 1) type = type.replace ("[]", "..."); e.setAttribute ("type", type); e.appendChild (doc.createTextNode ("\n")); parent.appendChild (e); } } String getConstructorName (Class c) { String n = ""; Class e = c.getEnclosingClass (); if (e != null) n = getConstructorName (e); return (n != "" ? n + "." : n) + c.getSimpleName (); } void appendCtor (Constructor ctor, Document doc, Element parent) { int mods = ctor.getModifiers (); if (!Modifier.isPublic (mods) && !Modifier.isProtected (mods)) return; Element e = doc.createElement ("constructor"); e.setAttribute ("name", getConstructorName (jclass)); e.setAttribute ("type", getClassName (jclass, true)); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : "protected"); setDeprecatedAttr (e, ctor.getDeclaredAnnotations ()); appendParameters (parent.getAttribute ("name"), ctor.getGenericParameterTypes (), ctor.isVarArgs (), doc, e); e.appendChild (doc.createTextNode ("\n")); parent.appendChild (e); } void appendField (Field field, Document doc, Element parent) { int mods = field.getModifiers (); if (!Modifier.isPublic (mods) && !Modifier.isProtected (mods)) return; Element e = doc.createElement ("field"); e.setAttribute ("name", field.getName ()); e.setAttribute ("type", getGenericTypeName (field.getGenericType ())); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); if (Modifier.isAbstract (mods)) e.setAttribute ("abstract", "true"); e.setAttribute ("transient", Modifier.isTransient (mods) ? "true" : "false"); e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : "protected"); e.setAttribute ("volatile", Modifier.isVolatile (mods) ? "true" : "false"); setDeprecatedAttr (e, field.getDeclaredAnnotations ()); if (Modifier.isStatic (mods) && Modifier.isFinal (mods) && Modifier.isPublic (mods)) { String type = e.getAttribute ("type"); try { if (type == "int") e.setAttribute ("value", String.format ("%d", field.getInt (null))); else if (type == "byte") e.setAttribute ("value", String.format ("%d", field.getByte (null))); else if (type == "short") e.setAttribute ("value", String.format ("%d", field.getShort (null))); else if (type == "long") e.setAttribute ("value", String.format ("%d", field.getLong (null))); else if (type == "float") e.setAttribute ("value", String.format ("%f", field.getFloat (null))); else if (type == "double") { // see java.lang.Double constants. double dvalue = field.getDouble (null); String svalue; if (dvalue == Double.MAX_VALUE) svalue = "1.7976931348623157E308"; else if (dvalue == Double.MIN_VALUE) svalue = "4.9E-324"; else if (Double.isNaN (dvalue)) svalue = "(0.0 / 0.0)"; else if (dvalue == Double.POSITIVE_INFINITY) svalue = "(1.0 / 0.0)"; else if (dvalue == Double.NEGATIVE_INFINITY) svalue = "(-1.0 / 0.0)"; else svalue = String.format ("%f", dvalue); e.setAttribute ("value", svalue); } else if (type == "boolean") e.setAttribute ("value", field.getBoolean (null) ? "true" : "false"); else if (type == "java.lang.String") e.setAttribute ("value", "\"" + ((String) field.get (null)).replace ("\\", "\\\\") + "\""); } catch (Exception exc) { System.err.println ("Error accessing constant field " + field.getName () + " value for class " + getName ()); } } e.appendChild (doc.createTextNode ("\n")); parent.appendChild (e); } void appendMethod (Method method, Document doc, Element parent) { int mods = method.getModifiers (); if (!Modifier.isPublic (mods) && !Modifier.isProtected (mods)) return; Element e = doc.createElement ("method"); e.setAttribute ("name", method.getName ()); Element typeParameters = getTypeParametersNode (doc, method.getTypeParameters ()); if (typeParameters != null) e.appendChild (typeParameters); e.setAttribute ("return", getGenericTypeName (method.getGenericReturnType ())); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); e.setAttribute ("abstract", Modifier.isAbstract (mods) ? "true" : "false"); e.setAttribute ("native", Modifier.isNative (mods) ? "true" : "false"); e.setAttribute ("synchronized", Modifier.isSynchronized (mods) ? "true" : "false"); e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : "protected"); setDeprecatedAttr (e, method.getDeclaredAnnotations ()); appendParameters (method.getName (), method.getGenericParameterTypes (), method.isVarArgs (), doc, e); Class [] excTypes = method.getExceptionTypes (); sortClasses (excTypes); for (Class exc : excTypes) { Element exe = doc.createElement ("exception"); exe.setAttribute ("name", getClassName (exc, false)); exe.setAttribute ("type", getClassName (exc, true)); exe.appendChild (doc.createTextNode ("\n")); e.appendChild (exe); } e.appendChild (doc.createTextNode ("\n")); parent.appendChild (e); } static void sortClasses (Class [] classes) { java.util.Arrays.sort (classes, new java.util.Comparator () { public int compare (Object o1, Object o2) { return ((Class) o1).getSimpleName ().compareTo (((Class) o2).getSimpleName ()); } public boolean equals (Object obj) { return super.equals (obj); } }); } static void sortTypes (Type [] types) { java.util.Arrays.sort (types, new java.util.Comparator () { public int compare (Object o1, Object o2) { if (o1 instanceof Class && o2 instanceof Class) return ((Class) o1).getSimpleName ().compareTo (((Class) o2).getSimpleName ()); else return getGenericTypeName ((Type) o1).compareTo (getGenericTypeName ((Type) o2)); } public boolean equals (Object obj) { return super.equals (obj); } }); } static String getTypeParameters (TypeVariable<?>[] typeParameters) { if (typeParameters.length == 0) return ""; StringBuffer type_params = new StringBuffer (); type_params.append ("<"); for (TypeVariable tp : typeParameters) { if (type_params.length () > 1) type_params.append (", "); type_params.append (tp.getName ()); Type[] bounds = tp.getBounds (); if (bounds.length == 1 && bounds [0] == Object.class) continue; type_params.append (" extends ").append (getGenericTypeName (bounds [0])); for (int i = 1; i < bounds.length; i++) { type_params.append (" & ").append (getGenericTypeName (bounds [i])); } } type_params.append (">"); return type_params.toString (); } static Element getTypeParametersNode (Document doc, TypeVariable<Method>[] tps) { if (tps.length == 0) return null; Element tps_elem = doc.createElement ("typeParameters"); for (TypeVariable<?> tp : tps) { Element tp_elem = doc.createElement ("typeParameter"); tp_elem.setAttribute ("name", tp.getName ()); if (tp.getBounds ().length != 1 || tp.getBounds () [0].equals (Object.class)) { Element tcs_elem = doc.createElement ("genericConstraints"); for (Type tc : tp.getBounds ()) { if (tc.equals (Object.class)) continue; Element tc_elem = doc.createElement ("genericConstraint"); Class tcc = tc instanceof Class ? (Class) tc : null; ParameterizedType pt = tc instanceof ParameterizedType ? (ParameterizedType) tc : null; if (tcc != null) tc_elem.setAttribute ("type", tcc.getName ()); else if (pt != null) tc_elem.setAttribute ("type", pt.toString ()); // FIXME: this is not strictly compliant to the ParameterizedType API (no assured tostring() behavior to return type name) else throw new UnsupportedOperationException ("Type is " + tc.getClass ()); tcs_elem.appendChild (tc_elem); } if (tcs_elem != null) tp_elem.appendChild (tcs_elem); } tps_elem.appendChild (tp_elem); } return tps_elem; } String getSignature (Method method) { StringBuffer sig = new StringBuffer (); sig.append (method.getName ()); for (Type t : method.getGenericParameterTypes ()) { sig.append (":"); sig.append (getGenericTypeName (t)); } return sig.toString (); } static String getClassName (Class jclass, boolean isFullname) { String qualname = jclass.getName (); String basename = isFullname ? qualname : qualname.substring (jclass.getPackage ().getName ().length () + 1, qualname.length ()); return basename.replace ("$", "."); } public void appendToDocument (Document doc, Element parent) { int mods = jclass.getModifiers (); - if (!Modifier.isPublic (mods) && !Modifier.isProtected (mods)) - return; Element e = doc.createElement (jclass.isInterface () ? "interface" : "class"); if (!jclass.isInterface ()) { Type t = jclass.getGenericSuperclass (); if (t != null) e.setAttribute ("extends", getGenericTypeName (t)); } e.setAttribute ("name", getClassName (jclass, false)); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); e.setAttribute ("abstract", Modifier.isAbstract (mods) ? "true" : "false"); - e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : "protected"); + e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : Modifier.isProtected (mods) ? "protected" : ""); Element typeParameters = getTypeParametersNode (doc, jclass.getTypeParameters ()); if (typeParameters != null) e.appendChild (typeParameters); setDeprecatedAttr (e, jclass.getDeclaredAnnotations ()); Type [] ifaces = jclass.getGenericInterfaces (); sortTypes (ifaces); for (Type iface : ifaces) { Element iface_elem = doc.createElement ("implements"); iface_elem.setAttribute ("name", getGenericTypeName (iface)); iface_elem.appendChild (doc.createTextNode ("\n")); e.appendChild (iface_elem); } for (Constructor ctor : jclass.getDeclaredConstructors ()) appendCtor (ctor, doc, e); Class base_class = jclass.getSuperclass (); Map<String, Method> methods = new HashMap <String, Method> (); for (Method method : jclass.getDeclaredMethods ()) { int mmods = method.getModifiers (); if (base_class != null && !Modifier.isFinal (mmods)) { Method base_method = null; Class ancestor = base_class; while (ancestor != null && base_method == null) { try { base_method = ancestor.getDeclaredMethod (method.getName (), method.getParameterTypes ()); } catch (Exception ex) { } ancestor = ancestor.getSuperclass (); } if (base_method != null) { if (Modifier.isAbstract (mmods)) continue; // FIXME: this causes GridView.setAdapter() skipped. // Removing this entire block however results in more confusion. See README. int base_mods = base_method.getModifiers (); if (!Modifier.isAbstract (base_mods) && (Modifier.isPublic (mmods) == Modifier.isPublic (base_mods))) continue; } } String key = getSignature (method); if (methods.containsKey (key)) { Type method_type = method.getGenericReturnType (); Method hashed = methods.get (key); Type hashed_type = hashed.getGenericReturnType (); Class mret = method_type instanceof Class ? (Class) method_type : null; Class hret = hashed_type instanceof Class ? (Class) hashed_type : null; if (mret == null || (hret != null && hret.isAssignableFrom (mret))) methods.put (key, method); else if (hret != null && !mret.isAssignableFrom (hret)) { System.out.println ("method collision: " + jclass.getName () + "." + key); System.out.println (" " + hashed.getGenericReturnType ().toString () + " ----- " + method.getGenericReturnType ().toString ()); } } else { methods.put (key, method); } } ArrayList <String> sigs = new ArrayList<String> (methods.keySet ()); java.util.Collections.sort (sigs); for (String sig : sigs) appendMethod (methods.get (sig), doc, e); if (!jclass.isEnum ()) // enums are somehow skipped. for (Field field : jclass.getDeclaredFields ()) appendField (field, doc, e); parent.appendChild (e); } public static String getGenericTypeName (Type type) { if (type instanceof Class) { String name = ((Class) type).getName (); if (name.charAt (0) == '[') { // Array types report a jni formatted name String suffix = ""; while (name.charAt (0) == '[') { name = name.substring (1); suffix = suffix + "[]"; } if (name.equals ("B")) return "byte" + suffix; else if (name.equals ("C")) return "char" + suffix; else if (name.equals ("D")) return "double" + suffix; else if (name.equals ("I")) return "int" + suffix; else if (name.equals ("F")) return "float" + suffix; else if (name.equals ("J")) return "long" + suffix; else if (name.equals ("S")) return "short" + suffix; else if (name.equals ("Z")) return "boolean" + suffix; else if (name.charAt (0) == 'L') return name.substring (1, name.length () - 1).replace ('$', '.') + suffix; else { System.err.println ("Unexpected array type name '" + name + "'"); return ""; } } return name.replace ('$', '.'); } else if (type.getClass ().toString ().equals ("class sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl")) { String name = duplicatePackageAndClass.matcher (type.toString ()).replaceAll ("$1"); return name.replace ('$', '.'); } else { return type.toString ().replace ('$', '.'); } } static final Pattern duplicatePackageAndClass = Pattern.compile ("([a-z0-9.]+[A-Z][a-z0-9]+)\\.\\1"); void setDeprecatedAttr (Element elem, Annotation[] annotations) { boolean isDeprecated = false; // by reference document (they may be excessive on old versions though) isDeprecated = deprecatedFields != null && deprecatedFields.indexOf (elem.getAttribute ("name")) >= 0; // by annotations (they might not exist though) for (Annotation a : annotations) if (a instanceof java.lang.Deprecated) isDeprecated = true; elem.setAttribute ("deprecated", isDeprecated ? "deprecated" : "not deprecated"); } static ArrayList<IDocScraper> scrapers; public static void addDocScraper (IDocScraper scraper) { scrapers.add (scraper); } static { scrapers = new ArrayList<IDocScraper> (); } }
false
true
public void appendToDocument (Document doc, Element parent) { int mods = jclass.getModifiers (); if (!Modifier.isPublic (mods) && !Modifier.isProtected (mods)) return; Element e = doc.createElement (jclass.isInterface () ? "interface" : "class"); if (!jclass.isInterface ()) { Type t = jclass.getGenericSuperclass (); if (t != null) e.setAttribute ("extends", getGenericTypeName (t)); } e.setAttribute ("name", getClassName (jclass, false)); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); e.setAttribute ("abstract", Modifier.isAbstract (mods) ? "true" : "false"); e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : "protected"); Element typeParameters = getTypeParametersNode (doc, jclass.getTypeParameters ()); if (typeParameters != null) e.appendChild (typeParameters); setDeprecatedAttr (e, jclass.getDeclaredAnnotations ()); Type [] ifaces = jclass.getGenericInterfaces (); sortTypes (ifaces); for (Type iface : ifaces) { Element iface_elem = doc.createElement ("implements"); iface_elem.setAttribute ("name", getGenericTypeName (iface)); iface_elem.appendChild (doc.createTextNode ("\n")); e.appendChild (iface_elem); } for (Constructor ctor : jclass.getDeclaredConstructors ()) appendCtor (ctor, doc, e); Class base_class = jclass.getSuperclass (); Map<String, Method> methods = new HashMap <String, Method> (); for (Method method : jclass.getDeclaredMethods ()) { int mmods = method.getModifiers (); if (base_class != null && !Modifier.isFinal (mmods)) { Method base_method = null; Class ancestor = base_class; while (ancestor != null && base_method == null) { try { base_method = ancestor.getDeclaredMethod (method.getName (), method.getParameterTypes ()); } catch (Exception ex) { } ancestor = ancestor.getSuperclass (); } if (base_method != null) { if (Modifier.isAbstract (mmods)) continue; // FIXME: this causes GridView.setAdapter() skipped. // Removing this entire block however results in more confusion. See README. int base_mods = base_method.getModifiers (); if (!Modifier.isAbstract (base_mods) && (Modifier.isPublic (mmods) == Modifier.isPublic (base_mods))) continue; } } String key = getSignature (method); if (methods.containsKey (key)) { Type method_type = method.getGenericReturnType (); Method hashed = methods.get (key); Type hashed_type = hashed.getGenericReturnType (); Class mret = method_type instanceof Class ? (Class) method_type : null; Class hret = hashed_type instanceof Class ? (Class) hashed_type : null; if (mret == null || (hret != null && hret.isAssignableFrom (mret))) methods.put (key, method); else if (hret != null && !mret.isAssignableFrom (hret)) { System.out.println ("method collision: " + jclass.getName () + "." + key); System.out.println (" " + hashed.getGenericReturnType ().toString () + " ----- " + method.getGenericReturnType ().toString ()); } } else { methods.put (key, method); } } ArrayList <String> sigs = new ArrayList<String> (methods.keySet ()); java.util.Collections.sort (sigs); for (String sig : sigs) appendMethod (methods.get (sig), doc, e); if (!jclass.isEnum ()) // enums are somehow skipped. for (Field field : jclass.getDeclaredFields ()) appendField (field, doc, e); parent.appendChild (e); }
public void appendToDocument (Document doc, Element parent) { int mods = jclass.getModifiers (); Element e = doc.createElement (jclass.isInterface () ? "interface" : "class"); if (!jclass.isInterface ()) { Type t = jclass.getGenericSuperclass (); if (t != null) e.setAttribute ("extends", getGenericTypeName (t)); } e.setAttribute ("name", getClassName (jclass, false)); e.setAttribute ("final", Modifier.isFinal (mods) ? "true" : "false"); e.setAttribute ("static", Modifier.isStatic (mods) ? "true" : "false"); e.setAttribute ("abstract", Modifier.isAbstract (mods) ? "true" : "false"); e.setAttribute ("visibility", Modifier.isPublic (mods) ? "public" : Modifier.isProtected (mods) ? "protected" : ""); Element typeParameters = getTypeParametersNode (doc, jclass.getTypeParameters ()); if (typeParameters != null) e.appendChild (typeParameters); setDeprecatedAttr (e, jclass.getDeclaredAnnotations ()); Type [] ifaces = jclass.getGenericInterfaces (); sortTypes (ifaces); for (Type iface : ifaces) { Element iface_elem = doc.createElement ("implements"); iface_elem.setAttribute ("name", getGenericTypeName (iface)); iface_elem.appendChild (doc.createTextNode ("\n")); e.appendChild (iface_elem); } for (Constructor ctor : jclass.getDeclaredConstructors ()) appendCtor (ctor, doc, e); Class base_class = jclass.getSuperclass (); Map<String, Method> methods = new HashMap <String, Method> (); for (Method method : jclass.getDeclaredMethods ()) { int mmods = method.getModifiers (); if (base_class != null && !Modifier.isFinal (mmods)) { Method base_method = null; Class ancestor = base_class; while (ancestor != null && base_method == null) { try { base_method = ancestor.getDeclaredMethod (method.getName (), method.getParameterTypes ()); } catch (Exception ex) { } ancestor = ancestor.getSuperclass (); } if (base_method != null) { if (Modifier.isAbstract (mmods)) continue; // FIXME: this causes GridView.setAdapter() skipped. // Removing this entire block however results in more confusion. See README. int base_mods = base_method.getModifiers (); if (!Modifier.isAbstract (base_mods) && (Modifier.isPublic (mmods) == Modifier.isPublic (base_mods))) continue; } } String key = getSignature (method); if (methods.containsKey (key)) { Type method_type = method.getGenericReturnType (); Method hashed = methods.get (key); Type hashed_type = hashed.getGenericReturnType (); Class mret = method_type instanceof Class ? (Class) method_type : null; Class hret = hashed_type instanceof Class ? (Class) hashed_type : null; if (mret == null || (hret != null && hret.isAssignableFrom (mret))) methods.put (key, method); else if (hret != null && !mret.isAssignableFrom (hret)) { System.out.println ("method collision: " + jclass.getName () + "." + key); System.out.println (" " + hashed.getGenericReturnType ().toString () + " ----- " + method.getGenericReturnType ().toString ()); } } else { methods.put (key, method); } } ArrayList <String> sigs = new ArrayList<String> (methods.keySet ()); java.util.Collections.sort (sigs); for (String sig : sigs) appendMethod (methods.get (sig), doc, e); if (!jclass.isEnum ()) // enums are somehow skipped. for (Field field : jclass.getDeclaredFields ()) appendField (field, doc, e); parent.appendChild (e); }
diff --git a/java/server/src/test/java/org/apache/shindig/server/JettyLauncher.java b/java/server/src/test/java/org/apache/shindig/server/JettyLauncher.java index fd115560c..f77dfd309 100644 --- a/java/server/src/test/java/org/apache/shindig/server/JettyLauncher.java +++ b/java/server/src/test/java/org/apache/shindig/server/JettyLauncher.java @@ -1,170 +1,170 @@ /* * 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.shindig.server; import org.apache.shindig.auth.AuthenticationServletFilter; import org.apache.shindig.common.PropertiesModule; import org.apache.shindig.common.servlet.GuiceServletContextListener; import org.apache.shindig.gadgets.DefaultGuiceModule; import org.apache.shindig.gadgets.oauth.OAuthModule; import org.apache.shindig.gadgets.servlet.ConcatProxyServlet; import org.apache.shindig.gadgets.servlet.GadgetRenderingServlet; import org.apache.shindig.gadgets.servlet.JsServlet; import org.apache.shindig.gadgets.servlet.MakeRequestServlet; import org.apache.shindig.gadgets.servlet.ProxyServlet; import org.apache.shindig.gadgets.servlet.RpcServlet; import org.apache.shindig.protocol.DataServiceServlet; import org.apache.shindig.protocol.JsonRpcServlet; import org.apache.shindig.social.sample.SampleModule; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.DefaultServlet; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.resource.Resource; import java.io.IOException; import java.util.Map; import com.google.common.base.Joiner; import com.google.common.collect.Maps; /** * Simple programmatic initialization of Shindig using Jetty and common paths. */ public class JettyLauncher { private static final String GADGET_BASE = "/gadgets/ifr"; private static final String PROXY_BASE = "/gadgets/proxy"; private static final String MAKEREQUEST_BASE = "/gadgets/makeRequest"; private static final String GADGETS_RPC_BASE = "/gadgets/api/rpc/*"; private static final String GADGETS_REST_BASE = "/gadgets/api/rest/*"; private static final String REST_BASE = "/social/rest/*"; private static final String JSON_RPC_BASE = "/social/rpc/*"; private static final String CONCAT_BASE = "/gadgets/concat"; private static final String GADGETS_FILES = "/gadgets/files/*"; private static final String JS_BASE = "/gadgets/js/*"; private static final String METADATA_BASE = "/gadgets/metadata/*"; private Server server; private JettyLauncher(int port, final String trunk) throws IOException { server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); //context.setBaseResource(Resource.newClassPathResource("/endtoend")); context.setResourceBase(Resource.newClassPathResource("/endtoend").getFile().getAbsolutePath()); ServletHolder defaultHolder = new ServletHolder(new DefaultServlet()); context.addServlet(defaultHolder, "/"); context.addEventListener(new GuiceServletContextListener()); Map<String, String> initParams = Maps.newHashMap(); String modules = Joiner.on(":") .join(SampleModule.class.getName(), DefaultGuiceModule.class.getName(), PropertiesModule.class.getName(), OAuthModule.class.getName()); initParams.put(GuiceServletContextListener.MODULES_ATTRIBUTE, modules); context.setInitParams(initParams); // Attach the ConcatProxyServlet - needed for rewriting ServletHolder concatHolder = new ServletHolder(new ConcatProxyServlet()); context.addServlet(concatHolder, CONCAT_BASE); // Attach the JS ServletHolder jsHolder = new ServletHolder(new JsServlet()); context.addServlet(jsHolder, JS_BASE); // Attach the metatdata handler ServletHolder metadataHolder = new ServletHolder(new RpcServlet()); context.addServlet(metadataHolder, METADATA_BASE); // Attach the Proxy ServletHolder proxyHolder = new ServletHolder(new ProxyServlet()); context.addServlet(proxyHolder, PROXY_BASE); // Attach the gadget rendering servlet ServletHolder gadgetServletHolder = new ServletHolder(new GadgetRenderingServlet()); context.addServlet(gadgetServletHolder, GADGET_BASE); context.addFilter(AuthenticationServletFilter.class, GADGET_BASE, 0); // Attach the make-request servlet ServletHolder makeRequestHolder = new ServletHolder(new MakeRequestServlet()); context.addServlet(makeRequestHolder, MAKEREQUEST_BASE); context.addFilter(AuthenticationServletFilter.class, MAKEREQUEST_BASE, 0); // Attach the gadgets rpc servlet ServletHolder gadgetsRpcServletHolder = new ServletHolder(new JsonRpcServlet()); gadgetsRpcServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRpcServletHolder, GADGETS_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_RPC_BASE, 0); // Attach the gadgets rest servlet ServletHolder gadgetsRestServletHolder = new ServletHolder(new DataServiceServlet()); - gadgetsRpcServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); + gadgetsRestServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRestServletHolder, GADGETS_REST_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_REST_BASE, 0); // Attach DataServiceServlet ServletHolder restServletHolder = new ServletHolder(new DataServiceServlet()); restServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(restServletHolder, REST_BASE); context.addFilter(AuthenticationServletFilter.class, REST_BASE, 0); // Attach JsonRpcServlet ServletHolder rpcServletHolder = new ServletHolder(new JsonRpcServlet()); rpcServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(rpcServletHolder, JSON_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, JSON_RPC_BASE, 0); DefaultServlet defaultServlet = new DefaultServlet() { public Resource getResource(String s) { // Skip Gzip if (s.endsWith(".gz")) return null; String stripped = s.substring("/gadgets/files/".length()); try { Resource resource = Resource.newResource(trunk + "/javascript/" + stripped); // Try to open it. resource.getInputStream(); return resource; } catch (IOException ioe) { return Resource.newClassPathResource(stripped); } } }; ServletHolder gadgetFiles = new ServletHolder(defaultServlet); context.addServlet(gadgetFiles, GADGETS_FILES); } public void start() throws Exception { server.start(); server.join(); } /** * Takes a single path which is the trunk root directory. Uses * current root otherwise */ public static void main(String[] argv) throws Exception { String trunk = argv.length == 0 ? System.getProperty("user.dir") : argv[0]; JettyLauncher server = new JettyLauncher(8080, trunk); server.start(); } }
true
true
private JettyLauncher(int port, final String trunk) throws IOException { server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); //context.setBaseResource(Resource.newClassPathResource("/endtoend")); context.setResourceBase(Resource.newClassPathResource("/endtoend").getFile().getAbsolutePath()); ServletHolder defaultHolder = new ServletHolder(new DefaultServlet()); context.addServlet(defaultHolder, "/"); context.addEventListener(new GuiceServletContextListener()); Map<String, String> initParams = Maps.newHashMap(); String modules = Joiner.on(":") .join(SampleModule.class.getName(), DefaultGuiceModule.class.getName(), PropertiesModule.class.getName(), OAuthModule.class.getName()); initParams.put(GuiceServletContextListener.MODULES_ATTRIBUTE, modules); context.setInitParams(initParams); // Attach the ConcatProxyServlet - needed for rewriting ServletHolder concatHolder = new ServletHolder(new ConcatProxyServlet()); context.addServlet(concatHolder, CONCAT_BASE); // Attach the JS ServletHolder jsHolder = new ServletHolder(new JsServlet()); context.addServlet(jsHolder, JS_BASE); // Attach the metatdata handler ServletHolder metadataHolder = new ServletHolder(new RpcServlet()); context.addServlet(metadataHolder, METADATA_BASE); // Attach the Proxy ServletHolder proxyHolder = new ServletHolder(new ProxyServlet()); context.addServlet(proxyHolder, PROXY_BASE); // Attach the gadget rendering servlet ServletHolder gadgetServletHolder = new ServletHolder(new GadgetRenderingServlet()); context.addServlet(gadgetServletHolder, GADGET_BASE); context.addFilter(AuthenticationServletFilter.class, GADGET_BASE, 0); // Attach the make-request servlet ServletHolder makeRequestHolder = new ServletHolder(new MakeRequestServlet()); context.addServlet(makeRequestHolder, MAKEREQUEST_BASE); context.addFilter(AuthenticationServletFilter.class, MAKEREQUEST_BASE, 0); // Attach the gadgets rpc servlet ServletHolder gadgetsRpcServletHolder = new ServletHolder(new JsonRpcServlet()); gadgetsRpcServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRpcServletHolder, GADGETS_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_RPC_BASE, 0); // Attach the gadgets rest servlet ServletHolder gadgetsRestServletHolder = new ServletHolder(new DataServiceServlet()); gadgetsRpcServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRestServletHolder, GADGETS_REST_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_REST_BASE, 0); // Attach DataServiceServlet ServletHolder restServletHolder = new ServletHolder(new DataServiceServlet()); restServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(restServletHolder, REST_BASE); context.addFilter(AuthenticationServletFilter.class, REST_BASE, 0); // Attach JsonRpcServlet ServletHolder rpcServletHolder = new ServletHolder(new JsonRpcServlet()); rpcServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(rpcServletHolder, JSON_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, JSON_RPC_BASE, 0); DefaultServlet defaultServlet = new DefaultServlet() { public Resource getResource(String s) { // Skip Gzip if (s.endsWith(".gz")) return null; String stripped = s.substring("/gadgets/files/".length()); try { Resource resource = Resource.newResource(trunk + "/javascript/" + stripped); // Try to open it. resource.getInputStream(); return resource; } catch (IOException ioe) { return Resource.newClassPathResource(stripped); } } }; ServletHolder gadgetFiles = new ServletHolder(defaultServlet); context.addServlet(gadgetFiles, GADGETS_FILES); }
private JettyLauncher(int port, final String trunk) throws IOException { server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); //context.setBaseResource(Resource.newClassPathResource("/endtoend")); context.setResourceBase(Resource.newClassPathResource("/endtoend").getFile().getAbsolutePath()); ServletHolder defaultHolder = new ServletHolder(new DefaultServlet()); context.addServlet(defaultHolder, "/"); context.addEventListener(new GuiceServletContextListener()); Map<String, String> initParams = Maps.newHashMap(); String modules = Joiner.on(":") .join(SampleModule.class.getName(), DefaultGuiceModule.class.getName(), PropertiesModule.class.getName(), OAuthModule.class.getName()); initParams.put(GuiceServletContextListener.MODULES_ATTRIBUTE, modules); context.setInitParams(initParams); // Attach the ConcatProxyServlet - needed for rewriting ServletHolder concatHolder = new ServletHolder(new ConcatProxyServlet()); context.addServlet(concatHolder, CONCAT_BASE); // Attach the JS ServletHolder jsHolder = new ServletHolder(new JsServlet()); context.addServlet(jsHolder, JS_BASE); // Attach the metatdata handler ServletHolder metadataHolder = new ServletHolder(new RpcServlet()); context.addServlet(metadataHolder, METADATA_BASE); // Attach the Proxy ServletHolder proxyHolder = new ServletHolder(new ProxyServlet()); context.addServlet(proxyHolder, PROXY_BASE); // Attach the gadget rendering servlet ServletHolder gadgetServletHolder = new ServletHolder(new GadgetRenderingServlet()); context.addServlet(gadgetServletHolder, GADGET_BASE); context.addFilter(AuthenticationServletFilter.class, GADGET_BASE, 0); // Attach the make-request servlet ServletHolder makeRequestHolder = new ServletHolder(new MakeRequestServlet()); context.addServlet(makeRequestHolder, MAKEREQUEST_BASE); context.addFilter(AuthenticationServletFilter.class, MAKEREQUEST_BASE, 0); // Attach the gadgets rpc servlet ServletHolder gadgetsRpcServletHolder = new ServletHolder(new JsonRpcServlet()); gadgetsRpcServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRpcServletHolder, GADGETS_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_RPC_BASE, 0); // Attach the gadgets rest servlet ServletHolder gadgetsRestServletHolder = new ServletHolder(new DataServiceServlet()); gadgetsRestServletHolder.setInitParameter("handlers", "org.apache.shindig.gadgets.handlers"); context.addServlet(gadgetsRestServletHolder, GADGETS_REST_BASE); context.addFilter(AuthenticationServletFilter.class, GADGETS_REST_BASE, 0); // Attach DataServiceServlet ServletHolder restServletHolder = new ServletHolder(new DataServiceServlet()); restServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(restServletHolder, REST_BASE); context.addFilter(AuthenticationServletFilter.class, REST_BASE, 0); // Attach JsonRpcServlet ServletHolder rpcServletHolder = new ServletHolder(new JsonRpcServlet()); rpcServletHolder.setInitParameter("handlers", "org.apache.shindig.social.handlers"); context.addServlet(rpcServletHolder, JSON_RPC_BASE); context.addFilter(AuthenticationServletFilter.class, JSON_RPC_BASE, 0); DefaultServlet defaultServlet = new DefaultServlet() { public Resource getResource(String s) { // Skip Gzip if (s.endsWith(".gz")) return null; String stripped = s.substring("/gadgets/files/".length()); try { Resource resource = Resource.newResource(trunk + "/javascript/" + stripped); // Try to open it. resource.getInputStream(); return resource; } catch (IOException ioe) { return Resource.newClassPathResource(stripped); } } }; ServletHolder gadgetFiles = new ServletHolder(defaultServlet); context.addServlet(gadgetFiles, GADGETS_FILES); }
diff --git a/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java b/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java index 399d2f7e3f..d67cd18823 100644 --- a/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java +++ b/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java @@ -1,122 +1,122 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions 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 distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.id.generationmappings; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.enhanced.OptimizerFactory; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableGenerator; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.test.annotations.TestCase; /** * Test mapping the {@link javax.persistence.GenerationType GenerationTypes} to the corresponding * hibernate generators using the new scheme * * @author Steve Ebersole */ public class NewGeneratorMappingsTest extends TestCase { @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] { MinimalSequenceEntity.class, CompleteSequenceEntity.class, AutoEntity.class, MinimalTableEntity.class }; } @Override protected void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); cfg.setProperty( Environment.HBM2DDL_AUTO, "" ); } @Override protected boolean recreateSchema() { return false; } @Override protected void runSchemaGeneration() { } @Override protected void runSchemaDrop() { } public void testMinimalSequenceEntity() { final EntityPersister persister = sfi().getEntityPersister( MinimalSequenceEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; assertEquals( MinimalSequenceEntity.SEQ_NAME, seqGenerator.getDatabaseStructure().getName() ); // 1 is the annotation default assertEquals( 1, seqGenerator.getDatabaseStructure().getInitialValue() ); // 50 is the annotation default assertEquals( 50, seqGenerator.getDatabaseStructure().getIncrementSize() ); assertFalse( OptimizerFactory.NoopOptimizer.class.isInstance( seqGenerator.getOptimizer() ) ); } public void testCompleteSequenceEntity() { final EntityPersister persister = sfi().getEntityPersister( CompleteSequenceEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; assertEquals( "my_catalog.my_schema."+CompleteSequenceEntity.SEQ_NAME, seqGenerator.getDatabaseStructure().getName() ); assertEquals( 1000, seqGenerator.getDatabaseStructure().getInitialValue() ); assertEquals( 52, seqGenerator.getDatabaseStructure().getIncrementSize() ); assertFalse( OptimizerFactory.NoopOptimizer.class.isInstance( seqGenerator.getOptimizer() ) ); } public void testAutoEntity() { final EntityPersister persister = sfi().getEntityPersister( AutoEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( SequenceStyleGenerator.class.isInstance( generator ) ); SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator; assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, seqGenerator.getDatabaseStructure().getName() ); assertEquals( SequenceStyleGenerator.DEFAULT_INITIAL_VALUE, seqGenerator.getDatabaseStructure().getInitialValue() ); assertEquals( SequenceStyleGenerator.DEFAULT_INCREMENT_SIZE, seqGenerator.getDatabaseStructure().getIncrementSize() ); } public void testMinimalTableEntity() { final EntityPersister persister = sfi().getEntityPersister( MinimalTableEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( TableGenerator.class.isInstance( generator ) ); TableGenerator tabGenerator = (TableGenerator) generator; assertEquals( MinimalTableEntity.TBL_NAME, tabGenerator.getTableName() ); assertEquals( TableGenerator.DEF_SEGMENT_COLUMN, tabGenerator.getSegmentColumnName() ); assertEquals( "MINIMAL_TBL", tabGenerator.getSegmentValue() ); assertEquals( TableGenerator.DEF_VALUE_COLUMN, tabGenerator.getValueColumnName() ); - // 0 is the annotation default - assertEquals( 0, tabGenerator.getInitialValue() ); + // 0 is the annotation default, but its expected to be treated as 1 + assertEquals( 1, tabGenerator.getInitialValue() ); // 50 is the annotation default assertEquals( 50, tabGenerator.getIncrementSize() ); assertTrue( OptimizerFactory.PooledOptimizer.class.isInstance( tabGenerator.getOptimizer() ) ); } }
true
true
public void testMinimalTableEntity() { final EntityPersister persister = sfi().getEntityPersister( MinimalTableEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( TableGenerator.class.isInstance( generator ) ); TableGenerator tabGenerator = (TableGenerator) generator; assertEquals( MinimalTableEntity.TBL_NAME, tabGenerator.getTableName() ); assertEquals( TableGenerator.DEF_SEGMENT_COLUMN, tabGenerator.getSegmentColumnName() ); assertEquals( "MINIMAL_TBL", tabGenerator.getSegmentValue() ); assertEquals( TableGenerator.DEF_VALUE_COLUMN, tabGenerator.getValueColumnName() ); // 0 is the annotation default assertEquals( 0, tabGenerator.getInitialValue() ); // 50 is the annotation default assertEquals( 50, tabGenerator.getIncrementSize() ); assertTrue( OptimizerFactory.PooledOptimizer.class.isInstance( tabGenerator.getOptimizer() ) ); }
public void testMinimalTableEntity() { final EntityPersister persister = sfi().getEntityPersister( MinimalTableEntity.class.getName() ); IdentifierGenerator generator = persister.getIdentifierGenerator(); assertTrue( TableGenerator.class.isInstance( generator ) ); TableGenerator tabGenerator = (TableGenerator) generator; assertEquals( MinimalTableEntity.TBL_NAME, tabGenerator.getTableName() ); assertEquals( TableGenerator.DEF_SEGMENT_COLUMN, tabGenerator.getSegmentColumnName() ); assertEquals( "MINIMAL_TBL", tabGenerator.getSegmentValue() ); assertEquals( TableGenerator.DEF_VALUE_COLUMN, tabGenerator.getValueColumnName() ); // 0 is the annotation default, but its expected to be treated as 1 assertEquals( 1, tabGenerator.getInitialValue() ); // 50 is the annotation default assertEquals( 50, tabGenerator.getIncrementSize() ); assertTrue( OptimizerFactory.PooledOptimizer.class.isInstance( tabGenerator.getOptimizer() ) ); }
diff --git a/stripes/src/net/sourceforge/stripes/tag/FieldMetadataTag.java b/stripes/src/net/sourceforge/stripes/tag/FieldMetadataTag.java index 1bfb6fc..bd6ff5d 100644 --- a/stripes/src/net/sourceforge/stripes/tag/FieldMetadataTag.java +++ b/stripes/src/net/sourceforge/stripes/tag/FieldMetadataTag.java @@ -1,442 +1,444 @@ package net.sourceforge.stripes.tag; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTag; import net.sourceforge.stripes.action.ActionBean; import net.sourceforge.stripes.ajax.JavaScriptBuilder; import net.sourceforge.stripes.controller.ParameterName; import net.sourceforge.stripes.controller.StripesFilter; import net.sourceforge.stripes.exception.StripesJspException; import net.sourceforge.stripes.localization.LocalizationUtility; import net.sourceforge.stripes.util.Log; import net.sourceforge.stripes.util.bean.PropertyExpression; import net.sourceforge.stripes.util.bean.PropertyExpressionEvaluation; import net.sourceforge.stripes.validation.ValidationMetadata; import net.sourceforge.stripes.validation.ValidationMetadataProvider; /** * <p>Field metadata tag for use with the Stripes framework. Exposes field properties via JavaScript to * allow client side validation. If this tag has a body it will be wrapped with JavaScript tags for * convenience.</p> * * @author Aaron Porter * */ public class FieldMetadataTag extends HtmlTagSupport implements BodyTag { /** Log used to log error and debugging information for this class. */ private static final Log log = Log.getInstance(FormTag.class); /** Name of variable to hold metadata. */ private String var; /** Optional comma separated list of additional fields to expose. */ private String fields; /** Set to true to include type information for all fields. */ private boolean includeType = false; /** Set to true to include the fully qualified class name for all fields. */ private boolean fqn = false; /** Stores the value of the action attribute before the context gets appended. */ private String actionWithoutContext; public FormTag getForm() { return getParentTag(FormTag.class); } /** * Builds a string that contains field metadata in a JavaScript object. * * @return JavaScript object containing field metadata */ private String getMetadata() { ActionBean bean = null; String action = getAction(); FormTag form = getForm(); if (form != null) { if (action != null) log.warn("Parameters action and/or beanclass specified but field-metadata tag is inside of a Stripes form tag. The bean will be pulled from the form tag."); action = form.getAction(); } if (form != null) bean = form.getActionBean(); Class<? extends ActionBean> beanClass = null; if (bean != null) beanClass = bean.getClass(); else if (action != null) { beanClass = StripesFilter.getConfiguration().getActionResolver().getActionBeanType(action); if (beanClass != null) { try { bean = StripesFilter.getConfiguration().getObjectFactory().newInstance(beanClass); } catch (Exception e) { log.error(e); return null; } } } if (beanClass == null) { log.error("Couldn't determine ActionBean class from FormTag! One of the following conditions must be met:\r\n\t", "1. Include this tag inside of a stripes:form tag\r\n\t", "2. Use the action parameter\r\n\t", "3. Use the beanclass parameter"); return null; } ValidationMetadataProvider metadataProvider = StripesFilter.getConfiguration() .getValidationMetadataProvider(); if (metadataProvider == null) { log.error("Couldn't get ValidationMetadataProvider!"); return null; } Map<String, ValidationMetadata> metadata = metadataProvider .getValidationMetadata(beanClass); StringBuilder sb = new StringBuilder("{\r\n\t\t"); Set<String> fields = new HashSet<String>(); if (form != null) { for (String field : form.getRegisteredFields()) { fields.add(new ParameterName(field).getStrippedName()); } } if ((this.fields != null) && (this.fields.trim().length() > 0)) fields.addAll(Arrays.asList(this.fields.split(","))); else if (form == null) { log.error("Fields attribute is required when field-metadata tag isn't inside of a Stripes form tag."); return null; } boolean first = true; Locale locale = getPageContext().getRequest().getLocale(); for (String field : fields) { PropertyExpressionEvaluation eval = null; try { eval = new PropertyExpressionEvaluation(PropertyExpression.getExpression(field), bean); } catch (Exception e) { continue; } Class<?> fieldType = eval.getType(); ValidationMetadata data = metadata.get(field); StringBuilder fieldInfo = new StringBuilder(); if (fieldType.isPrimitive() || Number.class.isAssignableFrom(fieldType) || Date.class.isAssignableFrom(fieldType) || includeType) { fieldInfo.append("type:").append( JavaScriptBuilder.quote(fqn ? fieldType.getName() : fieldType .getSimpleName())); } Class<?> typeConverterClass = null; if (data != null) { if (data.encrypted()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("encrypted:") .append(data.encrypted()); if (data.required()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("required:").append( data.required()); if (data.on() != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("on:["); Iterator<String> it = data.on().iterator(); while (it.hasNext()) { fieldInfo.append(JavaScriptBuilder.quote(it.next())); if (it.hasNext()) fieldInfo.append(","); } fieldInfo.append("]"); } if (data.trim()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("trim:").append( data.trim()); if (data.mask() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("mask:") - .append("/^").append(data.mask()).append("$/"); + .append("new RegExp(") + .append(JavaScriptBuilder.quote("^" + data.mask().toString() + "$")) + .append(")"); if (data.minlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minlength:") .append(data.minlength()); if (data.maxlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxlength:") .append(data.maxlength()); if (data.minvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minvalue:").append( data.minvalue()); if (data.maxvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxvalue:").append( data.maxvalue()); String label = data.label(); if (data.label() == null) { label = LocalizationUtility.getLocalizedFieldName(field, form == null ? null : form.getAction(), form == null ? null : form.getActionBeanClass(), locale); } if (label != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("label:").append( JavaScriptBuilder.quote(label)); typeConverterClass = data.converter(); } // If we couldn't get the converter from the validation annotation // try to get it from the TypeConverterFactory if (typeConverterClass == null) { try { typeConverterClass = StripesFilter.getConfiguration().getTypeConverterFactory() .getTypeConverter(fieldType, pageContext.getRequest().getLocale()) .getClass(); } catch (Exception e) { // Just ignore it } } if (typeConverterClass != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("typeConverter:") .append( JavaScriptBuilder.quote(fqn ? typeConverterClass.getName() : typeConverterClass.getSimpleName())); } if (fieldInfo.length() > 0) { if (first) first = false; else sb.append(",\r\n\t\t"); sb.append(JavaScriptBuilder.quote(field)).append(":{"); sb.append(fieldInfo); sb.append("}"); } } sb.append("\r\n\t}"); return sb.toString(); } public FieldMetadataTag() { getAttributes().put("type", "text/javascript"); } public void doInitBody() throws JspException { } public int doAfterBody() throws JspException { return SKIP_BODY; } @Override public int doStartTag() throws JspException { getPageContext().setAttribute(getVar(), new Var(getMetadata())); return EVAL_BODY_BUFFERED; } @Override public int doEndTag() throws JspException { JspWriter writer = getPageContext().getOut(); String body = getBodyContentAsString(); if (body != null) { try { String contentType = getPageContext().getResponse().getContentType(); // Catches application/x-javascript, text/javascript, and text/ecmascript boolean pageIsScript = contentType != null && contentType.toLowerCase().contains("ascript"); // Don't write the script tags if this page is a script if (!pageIsScript) { writeOpenTag(writer, "script"); writer.write("//<![CDATA[\r\n"); } writer.write(body); if (!pageIsScript) { writer.write("\r\n//]]>"); writeCloseTag(writer, "script"); } } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } } // Only keep the type attribute between uses String type = getAttributes().get("type"); getAttributes().clear(); getAttributes().put("type", type); return SKIP_BODY; } public String getVar() { return var; } /** * Sets the name of the variable to hold metadata. * * @param var the name of the attribute that will contain field metadata */ public void setVar(String var) { this.var = var; } public String getFields() { return fields; } /** * Optional comma separated list of additional fields to expose. Any fields that have * already been added to the Stripes form tag will automatically be included. * * @param fields comma separated list of field names */ public void setFields(String fields) { this.fields = fields; } public boolean isIncludeType() { return includeType; } /** * Set to true to include type information for all fields. By default, type information is only * included for primitives, numbers, and dates. * * @param includeType include type info for all fields */ public void setIncludeType(boolean includeType) { this.includeType = includeType; } public boolean isFqn() { return fqn; } /** * Set to true to include the fully qualified class name for all fields. * * @param fqn include fully qualified class name for all fields */ public void setFqn(boolean fqn) { this.fqn = fqn; } /** * Sets the action for the form. If the form action begins with a slash, and does not already * contain the context path, then the context path of the web application will get prepended to * the action before it is set. In general actions should be specified as &quot;absolute&quot; * paths within the web application, therefore allowing them to function correctly regardless of * the address currently shown in the browser&apos;s address bar. * * @param action the action path, relative to the root of the web application */ public void setAction(String action) { // Use the action resolver to figure out what the appropriate URL binding if for // this path and use that if there is one, otherwise just use the action passed in String binding = StripesFilter.getConfiguration().getActionResolver() .getUrlBindingFromPath(action); if (binding != null) { this.actionWithoutContext = binding; } else { this.actionWithoutContext = action; } } public String getAction() { return this.actionWithoutContext; } /** * Sets the 'action' attribute by inspecting the bean class provided and asking the current * ActionResolver what the appropriate URL is. * * @param beanclass the String FQN of the class, or a Class representing the class * @throws StripesJspException if the URL cannot be determined for any reason, most likely * because of a mis-spelled class name, or a class that's not an ActionBean */ public void setBeanclass(Object beanclass) throws StripesJspException { String url = getActionBeanUrl(beanclass); if (url == null) { throw new StripesJspException( "Could not determine action from 'beanclass' supplied. " + "The value supplied was '" + beanclass + "'. Please ensure that this bean type " + "exists and is in the classpath. If you are developing a page and the ActionBean " + "does not yet exist, consider using the 'action' attribute instead for now."); } else { setAction(url); } } /** Corresponding getter for 'beanclass', will always return null. */ public Object getBeanclass() { return null; } /** * This is what is placed into the request attribute. It allows us to * get the field metadata as well as the form id. */ public class Var { private String fieldMetadata, formId; private Var(String fieldMetadata) { this.fieldMetadata = fieldMetadata; FormTag form = getForm(); if (form != null) { if (form.getId() == null) form.setId("stripes-" + new Random().nextInt()); this.formId = form.getId(); } } @Override public String toString() { return fieldMetadata; } public String getFormId() { return formId; } } }
true
true
private String getMetadata() { ActionBean bean = null; String action = getAction(); FormTag form = getForm(); if (form != null) { if (action != null) log.warn("Parameters action and/or beanclass specified but field-metadata tag is inside of a Stripes form tag. The bean will be pulled from the form tag."); action = form.getAction(); } if (form != null) bean = form.getActionBean(); Class<? extends ActionBean> beanClass = null; if (bean != null) beanClass = bean.getClass(); else if (action != null) { beanClass = StripesFilter.getConfiguration().getActionResolver().getActionBeanType(action); if (beanClass != null) { try { bean = StripesFilter.getConfiguration().getObjectFactory().newInstance(beanClass); } catch (Exception e) { log.error(e); return null; } } } if (beanClass == null) { log.error("Couldn't determine ActionBean class from FormTag! One of the following conditions must be met:\r\n\t", "1. Include this tag inside of a stripes:form tag\r\n\t", "2. Use the action parameter\r\n\t", "3. Use the beanclass parameter"); return null; } ValidationMetadataProvider metadataProvider = StripesFilter.getConfiguration() .getValidationMetadataProvider(); if (metadataProvider == null) { log.error("Couldn't get ValidationMetadataProvider!"); return null; } Map<String, ValidationMetadata> metadata = metadataProvider .getValidationMetadata(beanClass); StringBuilder sb = new StringBuilder("{\r\n\t\t"); Set<String> fields = new HashSet<String>(); if (form != null) { for (String field : form.getRegisteredFields()) { fields.add(new ParameterName(field).getStrippedName()); } } if ((this.fields != null) && (this.fields.trim().length() > 0)) fields.addAll(Arrays.asList(this.fields.split(","))); else if (form == null) { log.error("Fields attribute is required when field-metadata tag isn't inside of a Stripes form tag."); return null; } boolean first = true; Locale locale = getPageContext().getRequest().getLocale(); for (String field : fields) { PropertyExpressionEvaluation eval = null; try { eval = new PropertyExpressionEvaluation(PropertyExpression.getExpression(field), bean); } catch (Exception e) { continue; } Class<?> fieldType = eval.getType(); ValidationMetadata data = metadata.get(field); StringBuilder fieldInfo = new StringBuilder(); if (fieldType.isPrimitive() || Number.class.isAssignableFrom(fieldType) || Date.class.isAssignableFrom(fieldType) || includeType) { fieldInfo.append("type:").append( JavaScriptBuilder.quote(fqn ? fieldType.getName() : fieldType .getSimpleName())); } Class<?> typeConverterClass = null; if (data != null) { if (data.encrypted()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("encrypted:") .append(data.encrypted()); if (data.required()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("required:").append( data.required()); if (data.on() != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("on:["); Iterator<String> it = data.on().iterator(); while (it.hasNext()) { fieldInfo.append(JavaScriptBuilder.quote(it.next())); if (it.hasNext()) fieldInfo.append(","); } fieldInfo.append("]"); } if (data.trim()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("trim:").append( data.trim()); if (data.mask() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("mask:") .append("/^").append(data.mask()).append("$/"); if (data.minlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minlength:") .append(data.minlength()); if (data.maxlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxlength:") .append(data.maxlength()); if (data.minvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minvalue:").append( data.minvalue()); if (data.maxvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxvalue:").append( data.maxvalue()); String label = data.label(); if (data.label() == null) { label = LocalizationUtility.getLocalizedFieldName(field, form == null ? null : form.getAction(), form == null ? null : form.getActionBeanClass(), locale); } if (label != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("label:").append( JavaScriptBuilder.quote(label)); typeConverterClass = data.converter(); } // If we couldn't get the converter from the validation annotation // try to get it from the TypeConverterFactory if (typeConverterClass == null) { try { typeConverterClass = StripesFilter.getConfiguration().getTypeConverterFactory() .getTypeConverter(fieldType, pageContext.getRequest().getLocale()) .getClass(); } catch (Exception e) { // Just ignore it } } if (typeConverterClass != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("typeConverter:") .append( JavaScriptBuilder.quote(fqn ? typeConverterClass.getName() : typeConverterClass.getSimpleName())); } if (fieldInfo.length() > 0) { if (first) first = false; else sb.append(",\r\n\t\t"); sb.append(JavaScriptBuilder.quote(field)).append(":{"); sb.append(fieldInfo); sb.append("}"); } } sb.append("\r\n\t}"); return sb.toString(); }
private String getMetadata() { ActionBean bean = null; String action = getAction(); FormTag form = getForm(); if (form != null) { if (action != null) log.warn("Parameters action and/or beanclass specified but field-metadata tag is inside of a Stripes form tag. The bean will be pulled from the form tag."); action = form.getAction(); } if (form != null) bean = form.getActionBean(); Class<? extends ActionBean> beanClass = null; if (bean != null) beanClass = bean.getClass(); else if (action != null) { beanClass = StripesFilter.getConfiguration().getActionResolver().getActionBeanType(action); if (beanClass != null) { try { bean = StripesFilter.getConfiguration().getObjectFactory().newInstance(beanClass); } catch (Exception e) { log.error(e); return null; } } } if (beanClass == null) { log.error("Couldn't determine ActionBean class from FormTag! One of the following conditions must be met:\r\n\t", "1. Include this tag inside of a stripes:form tag\r\n\t", "2. Use the action parameter\r\n\t", "3. Use the beanclass parameter"); return null; } ValidationMetadataProvider metadataProvider = StripesFilter.getConfiguration() .getValidationMetadataProvider(); if (metadataProvider == null) { log.error("Couldn't get ValidationMetadataProvider!"); return null; } Map<String, ValidationMetadata> metadata = metadataProvider .getValidationMetadata(beanClass); StringBuilder sb = new StringBuilder("{\r\n\t\t"); Set<String> fields = new HashSet<String>(); if (form != null) { for (String field : form.getRegisteredFields()) { fields.add(new ParameterName(field).getStrippedName()); } } if ((this.fields != null) && (this.fields.trim().length() > 0)) fields.addAll(Arrays.asList(this.fields.split(","))); else if (form == null) { log.error("Fields attribute is required when field-metadata tag isn't inside of a Stripes form tag."); return null; } boolean first = true; Locale locale = getPageContext().getRequest().getLocale(); for (String field : fields) { PropertyExpressionEvaluation eval = null; try { eval = new PropertyExpressionEvaluation(PropertyExpression.getExpression(field), bean); } catch (Exception e) { continue; } Class<?> fieldType = eval.getType(); ValidationMetadata data = metadata.get(field); StringBuilder fieldInfo = new StringBuilder(); if (fieldType.isPrimitive() || Number.class.isAssignableFrom(fieldType) || Date.class.isAssignableFrom(fieldType) || includeType) { fieldInfo.append("type:").append( JavaScriptBuilder.quote(fqn ? fieldType.getName() : fieldType .getSimpleName())); } Class<?> typeConverterClass = null; if (data != null) { if (data.encrypted()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("encrypted:") .append(data.encrypted()); if (data.required()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("required:").append( data.required()); if (data.on() != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("on:["); Iterator<String> it = data.on().iterator(); while (it.hasNext()) { fieldInfo.append(JavaScriptBuilder.quote(it.next())); if (it.hasNext()) fieldInfo.append(","); } fieldInfo.append("]"); } if (data.trim()) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("trim:").append( data.trim()); if (data.mask() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("mask:") .append("new RegExp(") .append(JavaScriptBuilder.quote("^" + data.mask().toString() + "$")) .append(")"); if (data.minlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minlength:") .append(data.minlength()); if (data.maxlength() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxlength:") .append(data.maxlength()); if (data.minvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("minvalue:").append( data.minvalue()); if (data.maxvalue() != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("maxvalue:").append( data.maxvalue()); String label = data.label(); if (data.label() == null) { label = LocalizationUtility.getLocalizedFieldName(field, form == null ? null : form.getAction(), form == null ? null : form.getActionBeanClass(), locale); } if (label != null) fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("label:").append( JavaScriptBuilder.quote(label)); typeConverterClass = data.converter(); } // If we couldn't get the converter from the validation annotation // try to get it from the TypeConverterFactory if (typeConverterClass == null) { try { typeConverterClass = StripesFilter.getConfiguration().getTypeConverterFactory() .getTypeConverter(fieldType, pageContext.getRequest().getLocale()) .getClass(); } catch (Exception e) { // Just ignore it } } if (typeConverterClass != null) { fieldInfo.append(fieldInfo.length() > 0 ? "," : "").append("typeConverter:") .append( JavaScriptBuilder.quote(fqn ? typeConverterClass.getName() : typeConverterClass.getSimpleName())); } if (fieldInfo.length() > 0) { if (first) first = false; else sb.append(",\r\n\t\t"); sb.append(JavaScriptBuilder.quote(field)).append(":{"); sb.append(fieldInfo); sb.append("}"); } } sb.append("\r\n\t}"); return sb.toString(); }
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSetSpawn.java b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSetSpawn.java index cd0ba7abb..d879edb73 100644 --- a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSetSpawn.java +++ b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSetSpawn.java @@ -1,478 +1,478 @@ package com.ForgeEssentials.commands; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import com.ForgeEssentials.api.permissions.Group; import com.ForgeEssentials.api.permissions.PermissionsAPI; import com.ForgeEssentials.api.permissions.RegGroup; import com.ForgeEssentials.api.permissions.Zone; import com.ForgeEssentials.api.permissions.ZoneManager; import com.ForgeEssentials.commands.util.FEcmdModuleCommands; import com.ForgeEssentials.util.FunctionHelper; import com.ForgeEssentials.util.Localization; import com.ForgeEssentials.util.OutputHandler; import com.ForgeEssentials.util.AreaSelector.WarpPoint; import com.ForgeEssentials.util.AreaSelector.WorldPoint; import cpw.mods.fml.common.FMLCommonHandler; public class CommandSetSpawn extends FEcmdModuleCommands { public static HashMap<String, WarpPoint> spawns = new HashMap<String, WarpPoint>(); public static final String SPAWN_PROP = "ForgeEssentials.BasicCommands.spawnPoint"; public static final String SPAWN_TYPE_PROP = "ForgeEssentials.BasicCommands.spawnType"; public static HashSet<Integer> dimsWithProp = new HashSet<Integer>(); @Override public String getCommandName() { return "setspawn"; } @Override public void processCommandPlayer(EntityPlayer sender, String[] args) { - if (args.length <= 1) + if (args.length <= 0) { error(sender); return; } if (args.length == 1) { if (args[0].equalsIgnoreCase("help")) { OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.1")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.2")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.3")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.4")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.5")); return; } else error(sender); } else if (args.length < 4 || args.length > 7) { error(sender); return; } // check point or type. String permProp = null; String prop = null; String output = ""; if (args[0].equalsIgnoreCase("point")) { permProp = SPAWN_PROP; int dim = 0, x = 0, y = 0, z = 0; if (args.length >= 6) { dim = sender.worldObj.provider.dimensionId; x = parseInt(sender, args[3], sender.posX); y = parseInt(sender, args[4], sender.posY); z = parseInt(sender, args[5], sender.posZ); } else if (args.length >= 4) { if (args[3].equalsIgnoreCase("here")) { WorldPoint p = new WorldPoint(sender); x = p.x; y = p.y; z = p.z; dim = p.dim; } else error(sender); } else error(sender); prop = dim + ";" + x + ";" + y + ";" + z; output = Localization.format("command.setspawn.setPoint", x, y, z); } else if (args[0].equalsIgnoreCase("type")) { permProp = SPAWN_TYPE_PROP; if (args[3].equalsIgnoreCase("none")) { prop = "none"; } else if (args[3].equalsIgnoreCase("none")) { prop = "bed"; } else if (args[3].equalsIgnoreCase("none")) { prop = "point"; } else error(sender); output = Localization.format("command.setspawn.setType", prop); } else { error(sender); } // calc zone. Zone zone = ZoneManager.getGLOBAL(); if (args.length == 5) { if (ZoneManager.doesZoneExist(args[4])) { zone = ZoneManager.getZone(args[4]); } else if (args[4].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[5])); return; } } else if(args.length == 7) { if (ZoneManager.doesZoneExist(args[6])) { zone = ZoneManager.getZone(args[6]); } else if (args[6].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[7])); return; } } if (args[1].equalsIgnoreCase("user")) { String name = args[1]; if (args[2].equalsIgnoreCase("_ME_")) { name = sender.username; } else { EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]); if (player == null) { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); OutputHandler.chatConfirmation(sender, args[0] + " will be used, but may be inaccurate."); } else { name = player.username; } } PermissionsAPI.setPlayerPermissionProp(name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("group")) { if (PermissionsAPI.getGroupForName(args[2]) == null) { OutputHandler.chatError(sender, args[2] + " does not exist as a group!"); return; } PermissionsAPI.setGroupPermissionProp(args[2], permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("zone")) { if (ZoneManager.doesZoneExist(args[2])) { zone = ZoneManager.getZone(args[2]); } else if (args[5].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[2])); return; } PermissionsAPI.setGroupPermissionProp(PermissionsAPI.getDEFAULT().name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else error(sender); } @Override public void processCommandConsole(ICommandSender sender, String[] args) { if (args.length <= 1) { error(sender); return; } if (args.length == 1) { if (args[0].equalsIgnoreCase("help")) { OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.1")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.2")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.3")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.4")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.5")); return; } else error(sender); } else if (args.length < 4 || args.length > 7) { error(sender); return; } // check point or type. String permProp = null; String prop = null; String output = ""; if (args[0].equalsIgnoreCase("point")) { permProp = SPAWN_PROP; int dim = 0, x = 0, y = 0, z = 0; if (args.length >= 7) { dim = parseInt(sender, args[6]); x = parseInt(sender, args[3]); y = parseInt(sender, args[4]); z = parseInt(sender, args[5]); } prop = dim + ";" + x + ";" + y + ";" + z; output = Localization.format("command.setspawn.setPoint", x, y, z); } else if (args[0].equalsIgnoreCase("type")) { permProp = SPAWN_TYPE_PROP; if (args[3].equalsIgnoreCase("none")) { prop = "none"; } else if (args[3].equalsIgnoreCase("none")) { prop = "bed"; } else if (args[3].equalsIgnoreCase("none")) { prop = "point"; } else error(sender); output = Localization.format("command.setspawn.setType", prop); } else { error(sender); } // calc zone. Zone zone = ZoneManager.getGLOBAL(); if (args.length == 6) { if (ZoneManager.doesZoneExist(args[5])) { zone = ZoneManager.getZone(args[5]); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[5])); return; } } else if(args.length == 8) { if (ZoneManager.doesZoneExist(args[7])) { zone = ZoneManager.getZone(args[7]); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[7])); return; } } if (args[1].equalsIgnoreCase("user")) { String name = args[1]; EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]); if (player == null) { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); OutputHandler.chatConfirmation(sender, args[0] + " will be used, but may be inaccurate."); } else { name = player.username; } PermissionsAPI.setPlayerPermissionProp(name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("group")) { if (PermissionsAPI.getGroupForName(args[2]) == null) { OutputHandler.chatError(sender, args[2] + " does not exist as a group!"); return; } PermissionsAPI.setGroupPermissionProp(args[2], permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("zone")) { if (ZoneManager.doesZoneExist(args[2])) { zone = ZoneManager.getZone(args[2]); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[2])); return; } PermissionsAPI.setGroupPermissionProp(PermissionsAPI.getDEFAULT().name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else error(sender); } public static void setSpawnPoint(WorldPoint p, Zone zone) { String val = p.dim + ";" + p.x + ";" + p.y + ";" + p.z; PermissionsAPI.setGroupPermissionProp(PermissionsAPI.getDEFAULT().name, SPAWN_PROP, val, zone.getZoneName()); } @Override public boolean canConsoleUseCommand() { return true; } @Override public String getCommandPerm() { return "ForgeEssentials.BasicCommands." + getCommandName(); } @Override public List<?> addTabCompletionOptions(ICommandSender sender, String[] args) { ArrayList<String> completes = new ArrayList<String>(); // type if (args.length == 1) { completes.add("type"); completes.add("point"); completes.add("help"); } // target type else if (args.length == 2) { completes.add("player"); completes.add("group"); completes.add("zone"); } // target else if (args.length == 3) { if (args[1].equalsIgnoreCase("player")) { completes.add("_ME_"); for (String name : FMLCommonHandler.instance().getMinecraftServerInstance().getAllUsernames()) completes.add(name); } else if (args[1].equalsIgnoreCase("group")) { List<Group> groups = PermissionsAPI.getGroupsInZone(ZoneManager.getGLOBAL().getZoneName()); for (Group g : groups) completes.add(g.name); } else if (args[1].equalsIgnoreCase("zone")) { for (Zone z : ZoneManager.getZoneList()) { completes.add(z.getZoneName()); } } } // value else if (args.length == 4) { if (args[0].equalsIgnoreCase("type")) { completes.add("none"); completes.add("bed"); completes.add("point"); } else if (args[0].equalsIgnoreCase("point")) { completes.add("here"); } } // zone after 1 arg of vals else if (args.length == 5) { if (args[0].equalsIgnoreCase("type") || (args[0].equalsIgnoreCase("point") && args[4].equalsIgnoreCase("here"))) { for (Zone z : ZoneManager.getZoneList()) { completes.add(z.getZoneName()); } } } // zone after coords else if (args.length == 7) { if (args[0].equalsIgnoreCase("point")) { for (Zone z : ZoneManager.getZoneList()) { completes.add(z.getZoneName()); } } } return getListOfStringsMatchingLastWord(args, completes.toArray(new String[completes.size()])); } @Override public RegGroup getReggroup() { return RegGroup.OWNERS; } }
true
true
public void processCommandPlayer(EntityPlayer sender, String[] args) { if (args.length <= 1) { error(sender); return; } if (args.length == 1) { if (args[0].equalsIgnoreCase("help")) { OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.1")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.2")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.3")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.4")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.5")); return; } else error(sender); } else if (args.length < 4 || args.length > 7) { error(sender); return; } // check point or type. String permProp = null; String prop = null; String output = ""; if (args[0].equalsIgnoreCase("point")) { permProp = SPAWN_PROP; int dim = 0, x = 0, y = 0, z = 0; if (args.length >= 6) { dim = sender.worldObj.provider.dimensionId; x = parseInt(sender, args[3], sender.posX); y = parseInt(sender, args[4], sender.posY); z = parseInt(sender, args[5], sender.posZ); } else if (args.length >= 4) { if (args[3].equalsIgnoreCase("here")) { WorldPoint p = new WorldPoint(sender); x = p.x; y = p.y; z = p.z; dim = p.dim; } else error(sender); } else error(sender); prop = dim + ";" + x + ";" + y + ";" + z; output = Localization.format("command.setspawn.setPoint", x, y, z); } else if (args[0].equalsIgnoreCase("type")) { permProp = SPAWN_TYPE_PROP; if (args[3].equalsIgnoreCase("none")) { prop = "none"; } else if (args[3].equalsIgnoreCase("none")) { prop = "bed"; } else if (args[3].equalsIgnoreCase("none")) { prop = "point"; } else error(sender); output = Localization.format("command.setspawn.setType", prop); } else { error(sender); } // calc zone. Zone zone = ZoneManager.getGLOBAL(); if (args.length == 5) { if (ZoneManager.doesZoneExist(args[4])) { zone = ZoneManager.getZone(args[4]); } else if (args[4].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[5])); return; } } else if(args.length == 7) { if (ZoneManager.doesZoneExist(args[6])) { zone = ZoneManager.getZone(args[6]); } else if (args[6].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[7])); return; } } if (args[1].equalsIgnoreCase("user")) { String name = args[1]; if (args[2].equalsIgnoreCase("_ME_")) { name = sender.username; } else { EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]); if (player == null) { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); OutputHandler.chatConfirmation(sender, args[0] + " will be used, but may be inaccurate."); } else { name = player.username; } } PermissionsAPI.setPlayerPermissionProp(name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("group")) { if (PermissionsAPI.getGroupForName(args[2]) == null) { OutputHandler.chatError(sender, args[2] + " does not exist as a group!"); return; } PermissionsAPI.setGroupPermissionProp(args[2], permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("zone")) { if (ZoneManager.doesZoneExist(args[2])) { zone = ZoneManager.getZone(args[2]); } else if (args[5].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[2])); return; } PermissionsAPI.setGroupPermissionProp(PermissionsAPI.getDEFAULT().name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else error(sender); }
public void processCommandPlayer(EntityPlayer sender, String[] args) { if (args.length <= 0) { error(sender); return; } if (args.length == 1) { if (args[0].equalsIgnoreCase("help")) { OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.1")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.2")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.3")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.4")); OutputHandler.chatConfirmation(sender, Localization.get("command.setspawn.help.5")); return; } else error(sender); } else if (args.length < 4 || args.length > 7) { error(sender); return; } // check point or type. String permProp = null; String prop = null; String output = ""; if (args[0].equalsIgnoreCase("point")) { permProp = SPAWN_PROP; int dim = 0, x = 0, y = 0, z = 0; if (args.length >= 6) { dim = sender.worldObj.provider.dimensionId; x = parseInt(sender, args[3], sender.posX); y = parseInt(sender, args[4], sender.posY); z = parseInt(sender, args[5], sender.posZ); } else if (args.length >= 4) { if (args[3].equalsIgnoreCase("here")) { WorldPoint p = new WorldPoint(sender); x = p.x; y = p.y; z = p.z; dim = p.dim; } else error(sender); } else error(sender); prop = dim + ";" + x + ";" + y + ";" + z; output = Localization.format("command.setspawn.setPoint", x, y, z); } else if (args[0].equalsIgnoreCase("type")) { permProp = SPAWN_TYPE_PROP; if (args[3].equalsIgnoreCase("none")) { prop = "none"; } else if (args[3].equalsIgnoreCase("none")) { prop = "bed"; } else if (args[3].equalsIgnoreCase("none")) { prop = "point"; } else error(sender); output = Localization.format("command.setspawn.setType", prop); } else { error(sender); } // calc zone. Zone zone = ZoneManager.getGLOBAL(); if (args.length == 5) { if (ZoneManager.doesZoneExist(args[4])) { zone = ZoneManager.getZone(args[4]); } else if (args[4].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[5])); return; } } else if(args.length == 7) { if (ZoneManager.doesZoneExist(args[6])) { zone = ZoneManager.getZone(args[6]); } else if (args[6].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[7])); return; } } if (args[1].equalsIgnoreCase("user")) { String name = args[1]; if (args[2].equalsIgnoreCase("_ME_")) { name = sender.username; } else { EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]); if (player == null) { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); OutputHandler.chatConfirmation(sender, args[0] + " will be used, but may be inaccurate."); } else { name = player.username; } } PermissionsAPI.setPlayerPermissionProp(name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("group")) { if (PermissionsAPI.getGroupForName(args[2]) == null) { OutputHandler.chatError(sender, args[2] + " does not exist as a group!"); return; } PermissionsAPI.setGroupPermissionProp(args[2], permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else if (args[1].equalsIgnoreCase("zone")) { if (ZoneManager.doesZoneExist(args[2])) { zone = ZoneManager.getZone(args[2]); } else if (args[5].equalsIgnoreCase("here")) { zone = ZoneManager.getWhichZoneIn(new WorldPoint(sender)); } else { OutputHandler.chatError(sender, Localization.format(Localization.ERROR_ZONE_NOZONE, args[2])); return; } PermissionsAPI.setGroupPermissionProp(PermissionsAPI.getDEFAULT().name, permProp, prop, zone.getZoneName()); OutputHandler.chatConfirmation(sender, output); } else error(sender); }
diff --git a/src/MeetingImpl.java b/src/MeetingImpl.java index ea93366..7139d27 100644 --- a/src/MeetingImpl.java +++ b/src/MeetingImpl.java @@ -1,144 +1,144 @@ import java.util.*; public class MeetingImpl implements Meeting, Comparator<Meeting> { private int meetingId; private Set<Contact> contactsAtMeeting = new HashSet<Contact>(); private Calendar meetingCal; private boolean past = false; private boolean future = false; public MeetingImpl(Set<Contact> set, Calendar date) { this.meetingId = (set.size() + 1); this.contactsAtMeeting.addAll(set); this.meetingCal = date; Calendar currentDate = GregorianCalendar.getInstance(); if (currentDate.after(date)) // i.e if meeting date is in the past { this.past = true; } else if (currentDate.before(date)) // i.e. if meeting date is in the future { this.future = true; } } public MeetingImpl() { // no args constructor for comparator } public int getId() { return this.meetingId; } public Calendar getDate() { return this.meetingCal; } public Set<Contact> getContacts() { return this.contactsAtMeeting; } public String getSetInfo() { String setInfo = ""; for (Iterator<Contact> itr = this.contactsAtMeeting.iterator(); itr.hasNext();) { ContactImpl tmp = (ContactImpl) itr.next(); setInfo += tmp.getInfo(); } return setInfo; } public String getMeetingInfo() { String id = "Meeting Id: " + this.meetingId; String contacts = "Contacts at Meeting: " + this.getSetInfo(); String date = "Date of Meeting: " + this.meetingCal.get(GregorianCalendar.DAY_OF_MONTH) + "/" + (this.meetingCal.get(GregorianCalendar.MONTH) + 1) + "/" + this.meetingCal.get(GregorianCalendar.YEAR); String info = (id + "\n" + contacts + "\n" + date); return info; } public String getFormattedDate() { String datestr = "Date of Meeting: " + this.meetingCal.get(GregorianCalendar.DAY_OF_MONTH) + "/" + (this.meetingCal.get(GregorianCalendar.MONTH) + 1) + "/" + this.meetingCal.get(GregorianCalendar.YEAR); return datestr; } public boolean inPast() { return past; } public boolean inFuture() { return future; } @Override public int compare(Meeting m1, Meeting m2) { Calendar cal1 = m1.getDate(); // the calendar for the first meeting Calendar cal2 = m2.getDate(); // the calendar for the second meeting int cal1Time = (int) cal1.getTimeInMillis() ; // cast the long return type of method getTimeInMillis to an int for the comparator int cal2Time = (int) cal2.getTimeInMillis(); /** @return a number which will unambiguously place each calendar in order (using milliseconds) */ return (cal1Time - cal2Time); } /** @param whatKindOfMeeting - flag passed from ContactManager so we know * whether getFutureMeeting(), getPastMeeting() or getMeeting() has been called */ - public Meeting returnMeeting(Set<Meeting> meetingSet, int id, char whatKindOfMeeting) + protected Meeting returnMeeting(Set<Meeting> meetingSet, int id, char whatKindOfMeeting) { for (Iterator<Meeting> itr = meetingSet.iterator(); itr.hasNext();) { if (itr.next().getId() == id && whatKindOfMeeting == 'f') // i.e. this needs to be a FUTURE meeting { if (((MeetingImpl)itr.next()).inFuture() == true) // use boolean getter to confirm this is a FUTURE meeting { /** if this condition true we have found id AND confirmed the meeting to be FUTURE; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inPast() == true) // i.e. if this is a PAST meeting [error] { /** if this condition true we have found id BUT the meeting is PAST; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID happened on " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'p') // i.e. this needs to be a PAST meeting { if (((MeetingImpl)itr.next()).inPast() == true) // use boolean getter to confirm this is a PAST meeting { /** if this condition true we have found id AND confirmed the meeting to be PAST; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inFuture() == true) // i.e. if this is a FUTURE meeting [error] { /** if this condition true we have found id BUT the meeting is FUTURE; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID will not happen until " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'm') // i.e. this needs to be just a MEETING [getMeeting] { /** can just return; no need to check if meeting past or future as it can be both to satisfy getMeeting() */ return itr.next(); } else // if the id is never found at all { System.err.println("No meeting found with id " + id); return null; } } System.err.println("Unable to read list of meetings. Please ensure it has readable permissions and/or has been created"); return null; } }
true
true
public Meeting returnMeeting(Set<Meeting> meetingSet, int id, char whatKindOfMeeting) { for (Iterator<Meeting> itr = meetingSet.iterator(); itr.hasNext();) { if (itr.next().getId() == id && whatKindOfMeeting == 'f') // i.e. this needs to be a FUTURE meeting { if (((MeetingImpl)itr.next()).inFuture() == true) // use boolean getter to confirm this is a FUTURE meeting { /** if this condition true we have found id AND confirmed the meeting to be FUTURE; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inPast() == true) // i.e. if this is a PAST meeting [error] { /** if this condition true we have found id BUT the meeting is PAST; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID happened on " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'p') // i.e. this needs to be a PAST meeting { if (((MeetingImpl)itr.next()).inPast() == true) // use boolean getter to confirm this is a PAST meeting { /** if this condition true we have found id AND confirmed the meeting to be PAST; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inFuture() == true) // i.e. if this is a FUTURE meeting [error] { /** if this condition true we have found id BUT the meeting is FUTURE; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID will not happen until " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'm') // i.e. this needs to be just a MEETING [getMeeting] { /** can just return; no need to check if meeting past or future as it can be both to satisfy getMeeting() */ return itr.next(); } else // if the id is never found at all { System.err.println("No meeting found with id " + id); return null; } } System.err.println("Unable to read list of meetings. Please ensure it has readable permissions and/or has been created"); return null; }
protected Meeting returnMeeting(Set<Meeting> meetingSet, int id, char whatKindOfMeeting) { for (Iterator<Meeting> itr = meetingSet.iterator(); itr.hasNext();) { if (itr.next().getId() == id && whatKindOfMeeting == 'f') // i.e. this needs to be a FUTURE meeting { if (((MeetingImpl)itr.next()).inFuture() == true) // use boolean getter to confirm this is a FUTURE meeting { /** if this condition true we have found id AND confirmed the meeting to be FUTURE; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inPast() == true) // i.e. if this is a PAST meeting [error] { /** if this condition true we have found id BUT the meeting is PAST; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID happened on " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'p') // i.e. this needs to be a PAST meeting { if (((MeetingImpl)itr.next()).inPast() == true) // use boolean getter to confirm this is a PAST meeting { /** if this condition true we have found id AND confirmed the meeting to be PAST; @return itr.next */ return itr.next(); } else if (((MeetingImpl)itr.next()).inFuture() == true) // i.e. if this is a FUTURE meeting [error] { /** if this condition true we have found id BUT the meeting is FUTURE; @throws IllegalArgsException */ throw new IllegalArgumentException("Meeting with specified ID will not happen until " + ((MeetingImpl)itr.next()).getFormattedDate()); } } else if (itr.next().getId() == id && whatKindOfMeeting == 'm') // i.e. this needs to be just a MEETING [getMeeting] { /** can just return; no need to check if meeting past or future as it can be both to satisfy getMeeting() */ return itr.next(); } else // if the id is never found at all { System.err.println("No meeting found with id " + id); return null; } } System.err.println("Unable to read list of meetings. Please ensure it has readable permissions and/or has been created"); return null; }
diff --git a/tests/tests/widget/src/android/widget/cts/ListViewTest.java b/tests/tests/widget/src/android/widget/cts/ListViewTest.java index f21b721a..f283681e 100644 --- a/tests/tests/widget/src/android/widget/cts/ListViewTest.java +++ b/tests/tests/widget/src/android/widget/cts/ListViewTest.java @@ -1,1071 +1,1070 @@ /* * Copyright (C) 2008 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 android.widget.cts; import java.util.List; import junit.framework.Assert; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.app.Instrumentation; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.suitebuilder.annotation.MediumTest; import android.util.AttributeSet; import android.util.SparseBooleanArray; import android.util.Xml; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LayoutAnimationController; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import com.android.cts.stub.R; import com.google.android.collect.Lists; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; import dalvik.annotation.ToBeFixed; @TestTargetClass(ListView.class) public class ListViewTest extends ActivityInstrumentationTestCase2<ListViewStubActivity> { private final String[] mCountryList = new String[] { "Argentina", "Australia", "China", "France", "Germany", "Italy", "Japan", "United States" }; private final String[] mNameList = new String[] { "Jacky", "David", "Kevin", "Michael", "Andy" }; private ListView mListView; private Activity mActivity; private Instrumentation mInstrumentation; private AttributeSet mAttributeSet; private ArrayAdapter<String> mAdapter_countries; private ArrayAdapter<String> mAdapter_names; public ListViewTest() { super("com.android.cts.stub", ListViewStubActivity.class); } protected void setUp() throws Exception { super.setUp(); mActivity = getActivity(); mInstrumentation = getInstrumentation(); XmlPullParser parser = mActivity.getResources().getXml(R.layout.listview_layout); mAttributeSet = Xml.asAttributeSet(parser); mAdapter_countries = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, mCountryList); mAdapter_names = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, mNameList); mListView = (ListView) mActivity.findViewById(R.id.listview_default); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "ListView", args = {android.content.Context.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "ListView", args = {android.content.Context.class, android.util.AttributeSet.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "ListView", args = {android.content.Context.class, android.util.AttributeSet.class, int.class} ) }) @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete") public void testConstructor() { new ListView(mActivity); new ListView(mActivity, mAttributeSet); new ListView(mActivity, mAttributeSet, 0); try { new ListView(null); fail("There should be a NullPointerException thrown out. "); } catch (NullPointerException e) { // expected, test success. } try { new ListView(null, null); fail("There should be a NullPointerException thrown out. "); } catch (NullPointerException e) { // expected, test success. } try { new ListView(null, null, -1); fail("There should be a NullPointerException thrown out. "); } catch (NullPointerException e) { // expected, test success. } } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setAdapter", args = {android.widget.ListAdapter.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getMaxScrollAmount", args = {} ) }) public void testGetMaxScrollAmount() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); int amount1 = mListView.getMaxScrollAmount(); assertTrue(amount1 > 0); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_names); } }); mInstrumentation.waitForIdleSync(); int amount2 = mListView.getMaxScrollAmount(); assertTrue(amount2 > 0); assertTrue(amount2 < amount1); // because NAMES list is shorter than COUNTRIES list } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setDividerHeight", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getDividerHeight", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getDivider", args = {} ) }) public void testAccessDividerHeight() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); Drawable d = mListView.getDivider(); Rect r = d.getBounds(); assertTrue(r.bottom - r.top > 0); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setDividerHeight(20); } }); mInstrumentation.waitForIdleSync(); assertEquals(20, mListView.getDividerHeight()); assertEquals(20, r.bottom - r.top); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setDividerHeight(10); } }); mInstrumentation.waitForIdleSync(); assertEquals(10, mListView.getDividerHeight()); assertEquals(10, r.bottom - r.top); } @TestTargets({ @TestTargetNew( level = TestLevel.PARTIAL, method = "setItemsCanFocus", args = {boolean.class} ), @TestTargetNew( level = TestLevel.PARTIAL, method = "getItemsCanFocus", args = {} ) }) public void testAccessItemsCanFocus() { mListView.setItemsCanFocus(true); assertTrue(mListView.getItemsCanFocus()); mListView.setItemsCanFocus(false); assertFalse(mListView.getItemsCanFocus()); // TODO: how to check? } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setAdapter", args = {android.widget.ListAdapter.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getAdapter", args = {} ) }) public void testAccessAdapter() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); assertSame(mAdapter_countries, mListView.getAdapter()); assertEquals(mCountryList.length, mListView.getCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_names); } }); mInstrumentation.waitForIdleSync(); assertSame(mAdapter_names, mListView.getAdapter()); assertEquals(mNameList.length, mListView.getCount()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setItemChecked", args = {int.class, boolean.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setChoiceMode", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getChoiceMode", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getCheckedItemPosition", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "isItemChecked", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getCheckedItemPositions", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "clearChoices", args = {} ) }) @UiThreadTest @ToBeFixed(bug="2031502", explanation="setItemChecked(i,false) always unchecks all items") public void testAccessItemChecked() { // NONE mode mListView.setChoiceMode(ListView.CHOICE_MODE_NONE); assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(1)); // SINGLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode()); mListView.setItemChecked(2, true); assertEquals(2, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(2)); mListView.setItemChecked(3, true); assertEquals(3, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); // test attempt to uncheck a item that wasn't checked to begin with mListView.setItemChecked(4, false); - // item three should still be checked, but current ListView behavior unchecks all items - assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); + // item three should still be checked + assertEquals(3, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); - // should be assertTrue - assertFalse(mListView.isItemChecked(3)); + assertTrue(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(4, true); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); // MULTIPLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); SparseBooleanArray array = mListView.getCheckedItemPositions(); assertTrue(array.get(1)); assertFalse(array.get(2)); assertTrue(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(2, true); mListView.setItemChecked(3, false); mListView.setItemChecked(4, true); assertTrue(array.get(1)); assertTrue(array.get(2)); assertFalse(array.get(3)); assertTrue(array.get(4)); assertTrue(mListView.isItemChecked(1)); assertTrue(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertFalse(array.get(1)); assertFalse(array.get(2)); assertFalse(array.get(3)); assertFalse(array.get(4)); assertFalse(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(4)); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setFooterDividersEnabled", args = {boolean.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addFooterView", args = {android.view.View.class, java.lang.Object.class, boolean.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addFooterView", args = {android.view.View.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getFooterViewsCount", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "removeFooterView", args = {android.view.View.class} ) }) public void testAccessFooterView() { final TextView footerView1 = new TextView(mActivity); footerView1.setText("footerview1"); final TextView footerView2 = new TextView(mActivity); footerView2.setText("footerview2"); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setFooterDividersEnabled(true); } }); mInstrumentation.waitForIdleSync(); assertEquals(0, mListView.getFooterViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.addFooterView(footerView1, null, true); } }); mInstrumentation.waitForIdleSync(); assertEquals(1, mListView.getFooterViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.addFooterView(footerView2); } }); mInstrumentation.waitForIdleSync(); assertEquals(2, mListView.getFooterViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.removeFooterView(footerView1); } }); mInstrumentation.waitForIdleSync(); assertEquals(1, mListView.getFooterViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.removeFooterView(footerView2); } }); mInstrumentation.waitForIdleSync(); assertEquals(0, mListView.getFooterViewsCount()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setHeaderDividersEnabled", args = {boolean.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addHeaderView", args = {android.view.View.class, java.lang.Object.class, boolean.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addHeaderView", args = {android.view.View.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getHeaderViewsCount", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "removeHeaderView", args = {android.view.View.class} ) }) @ToBeFixed(bug = "", explanation = "After add two header views, the setAdapter will fail, " + "and throws out an java.lang.ClassCastException.") public void testAccessHeaderView() { final TextView headerView1 = (TextView) mActivity.findViewById(R.id.headerview1); final TextView headerView2 = (TextView) mActivity.findViewById(R.id.headerview2); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setHeaderDividersEnabled(true); } }); mInstrumentation.waitForIdleSync(); assertEquals(0, mListView.getHeaderViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.addHeaderView(headerView2, null, true); } }); mInstrumentation.waitForIdleSync(); assertEquals(1, mListView.getHeaderViewsCount()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.addHeaderView(headerView1); } }); mInstrumentation.waitForIdleSync(); assertEquals(2, mListView.getHeaderViewsCount()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setDivider", args = {android.graphics.drawable.Drawable.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getDivider", args = {} ) }) public void testAccessDivider() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); Drawable defaultDrawable = mListView.getDivider(); Rect r = defaultDrawable.getBounds(); assertTrue(r.bottom - r.top > 0); final Drawable d = mActivity.getResources().getDrawable(R.drawable.scenery); r = d.getBounds(); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setDivider(d); } }); mInstrumentation.waitForIdleSync(); assertSame(d, mListView.getDivider()); assertEquals(r.bottom - r.top, mListView.getDividerHeight()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setDividerHeight(10); } }); mInstrumentation.waitForIdleSync(); assertEquals(10, mListView.getDividerHeight()); assertEquals(10, r.bottom - r.top); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setSelection", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setSelectionFromTop", args = {int.class, int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setSelectionAfterHeaderView", args = {} ) }) public void testSetSelection() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setSelection(1); } }); mInstrumentation.waitForIdleSync(); String item = (String) mListView.getSelectedItem(); assertEquals(mCountryList[1], item); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setSelectionFromTop(5, 0); } }); mInstrumentation.waitForIdleSync(); item = (String) mListView.getSelectedItem(); assertEquals(mCountryList[5], item); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setSelectionAfterHeaderView(); } }); mInstrumentation.waitForIdleSync(); item = (String) mListView.getSelectedItem(); assertEquals(mCountryList[0], item); } @TestTargets({ @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onKeyDown", args = {int.class, android.view.KeyEvent.class} ), @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onKeyUp", args = {int.class, android.view.KeyEvent.class} ), @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onKeyMultiple", args = {int.class, int.class, android.view.KeyEvent.class} ) }) public void testOnKeyUpDown() { // implementation details, do NOT test } @TestTargetNew( level = TestLevel.COMPLETE, method = "performItemClick", args = {android.view.View.class, int.class, long.class} ) public void testPerformItemClick() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setSelection(2); } }); mInstrumentation.waitForIdleSync(); final TextView child = (TextView) mAdapter_countries.getView(2, null, mListView); assertNotNull(child); assertEquals(mCountryList[2], child.getText().toString()); final long itemID = mAdapter_countries.getItemId(2); assertEquals(2, itemID); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.performItemClick(child, 2, itemID); } }); mInstrumentation.waitForIdleSync(); MockOnItemClickListener onClickListener = new MockOnItemClickListener(); mListView.setOnItemClickListener(onClickListener); assertNull(onClickListener.getView()); assertEquals(0, onClickListener.getPosition()); assertEquals(0, onClickListener.getID()); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.performItemClick(child, 2, itemID); } }); mInstrumentation.waitForIdleSync(); assertSame(child, onClickListener.getView()); assertEquals(2, onClickListener.getPosition()); assertEquals(2, onClickListener.getID()); } @TestTargets({ @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onRestoreInstanceState", args = {android.os.Parcelable.class} ), @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onSaveInstanceState", args = {} ) }) public void testSaveAndRestoreInstanceState() { // implementation details, do NOT test } @TestTargetNew( level = TestLevel.COMPLETE, method = "dispatchKeyEvent", args = {android.view.KeyEvent.class} ) public void testDispatchKeyEvent() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setSelection(1); } }); mInstrumentation.waitForIdleSync(); String item = (String) mListView.getSelectedItem(); assertEquals(mCountryList[1], item); mInstrumentation.runOnMainSync(new Runnable() { public void run() { KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A); mListView.dispatchKeyEvent(keyEvent); } }); mInstrumentation.waitForIdleSync(); mInstrumentation.runOnMainSync(new Runnable() { public void run() { KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN); mListView.dispatchKeyEvent(keyEvent); mListView.dispatchKeyEvent(keyEvent); mListView.dispatchKeyEvent(keyEvent); } }); mInstrumentation.waitForIdleSync(); item = (String)mListView.getSelectedItem(); assertEquals(mCountryList[4], item); } @TestTargetNew( level = TestLevel.PARTIAL, method = "requestChildRectangleOnScreen", args = {android.view.View.class, android.graphics.Rect.class, boolean.class} ) public void testRequestChildRectangleOnScreen() { mInstrumentation.runOnMainSync(new Runnable() { public void run() { mListView.setAdapter(mAdapter_countries); } }); mInstrumentation.waitForIdleSync(); TextView child = (TextView) mAdapter_countries.getView(0, null, mListView); assertNotNull(child); assertEquals(mCountryList[0], child.getText().toString()); Rect rect = new Rect(0, 0, 10, 10); assertFalse(mListView.requestChildRectangleOnScreen(child, rect, false)); // TODO: how to check? } @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onTouchEvent", args = {android.view.MotionEvent.class} ) public void testOnTouchEvent() { // implementation details, do NOT test } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "canAnimate", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setAdapter", args = {android.widget.ListAdapter.class} ) }) @UiThreadTest public void testCanAnimate() { MyListView listView = new MyListView(mActivity, mAttributeSet); assertFalse(listView.canAnimate()); listView.setAdapter(mAdapter_countries); assertFalse(listView.canAnimate()); LayoutAnimationController controller = new LayoutAnimationController( mActivity, mAttributeSet); listView.setLayoutAnimation(controller); assertTrue(listView.canAnimate()); } @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "dispatchDraw", args = {android.graphics.Canvas.class} ) @UiThreadTest public void testDispatchDraw() { // implementation details, do NOT test } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "findViewTraversal", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addHeaderView", args = {android.view.View.class} ) }) @UiThreadTest public void testFindViewTraversal() { MyListView listView = new MyListView(mActivity, mAttributeSet); TextView headerView = (TextView) mActivity.findViewById(R.id.headerview1); assertNull(listView.findViewTraversal(R.id.headerview1)); listView.addHeaderView(headerView); assertNotNull(listView.findViewTraversal(R.id.headerview1)); assertSame(headerView, listView.findViewTraversal(R.id.headerview1)); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "findViewWithTagTraversal", args = {java.lang.Object.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "addHeaderView", args = {android.view.View.class} ) }) @UiThreadTest public void testFindViewWithTagTraversal() { MyListView listView = new MyListView(mActivity, mAttributeSet); TextView headerView = (TextView) mActivity.findViewById(R.id.headerview1); assertNull(listView.findViewWithTagTraversal("header")); headerView.setTag("header"); listView.addHeaderView(headerView); assertNotNull(listView.findViewWithTagTraversal("header")); assertSame(headerView, listView.findViewWithTagTraversal("header")); } @TestTargetNew( level = TestLevel.TODO, method = "layoutChildren", args = {} ) @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete") public void testLayoutChildren() { // TODO: how to test? } @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onFinishInflate", args = {} ) public void testOnFinishInflate() { // implementation details, do NOT test } @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onFocusChanged", args = {boolean.class, int.class, android.graphics.Rect.class} ) public void testOnFocusChanged() { // implementation details, do NOT test } @TestTargetNew( level = TestLevel.NOT_NECESSARY, method = "onMeasure", args = {int.class, int.class} ) public void testOnMeasure() { // implementation details, do NOT test } /** * MyListView for test */ private static class MyListView extends ListView { public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected boolean canAnimate() { return super.canAnimate(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); } @Override protected View findViewTraversal(int id) { return super.findViewTraversal(id); } @Override protected View findViewWithTagTraversal(Object tag) { return super.findViewWithTagTraversal(tag); } @Override protected void layoutChildren() { super.layoutChildren(); } } private static class MockOnItemClickListener implements OnItemClickListener { private View mView; private int mPosition; private long mID; public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mView = view; mPosition = position; mID = id; } public View getView() { return mView; } public int getPosition() { return mPosition; } public long getID() { return mID; } } /** * The following functions are merged from frameworktest. */ @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "layoutChildren", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setAdapter", args = {android.widget.ListAdapter.class} ) }) @MediumTest public void testRequestLayout() throws Exception { ListView listView = new ListView(mActivity); List<String> items = Lists.newArrayList("hello"); Adapter<String> adapter = new Adapter<String>(mActivity, 0, items); listView.setAdapter(adapter); int measureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); adapter.notifyDataSetChanged(); listView.measure(measureSpec, measureSpec); listView.layout(0, 0, 100, 100); MockView childView = (MockView) listView.getChildAt(0); childView.requestLayout(); childView.onMeasureCalled = false; listView.measure(measureSpec, measureSpec); listView.layout(0, 0, 100, 100); Assert.assertTrue(childView.onMeasureCalled); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setSelection", args = {int.class} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "setAdapter", args = {android.widget.ListAdapter.class} ) }) @MediumTest public void testNoSelectableItems() throws Exception { ListView listView = new ListView(mActivity); // We use a header as the unselectable item to remain after the selectable one is removed. listView.addHeaderView(new View(mActivity), null, false); List<String> items = Lists.newArrayList("hello"); Adapter<String> adapter = new Adapter<String>(mActivity, 0, items); listView.setAdapter(adapter); listView.setSelection(1); int measureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); adapter.notifyDataSetChanged(); listView.measure(measureSpec, measureSpec); listView.layout(0, 0, 100, 100); items.remove(0); adapter.notifyDataSetChanged(); listView.measure(measureSpec, measureSpec); listView.layout(0, 0, 100, 100); } private class MockView extends View { public boolean onMeasureCalled = false; public MockView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); onMeasureCalled = true; } } private class Adapter<T> extends ArrayAdapter<T> { public Adapter(Context context, int resource, List<T> objects) { super(context, resource, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { return new MockView(getContext()); } } }
false
true
public void testAccessItemChecked() { // NONE mode mListView.setChoiceMode(ListView.CHOICE_MODE_NONE); assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(1)); // SINGLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode()); mListView.setItemChecked(2, true); assertEquals(2, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(2)); mListView.setItemChecked(3, true); assertEquals(3, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); // test attempt to uncheck a item that wasn't checked to begin with mListView.setItemChecked(4, false); // item three should still be checked, but current ListView behavior unchecks all items assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); // should be assertTrue assertFalse(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(4, true); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); // MULTIPLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); SparseBooleanArray array = mListView.getCheckedItemPositions(); assertTrue(array.get(1)); assertFalse(array.get(2)); assertTrue(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(2, true); mListView.setItemChecked(3, false); mListView.setItemChecked(4, true); assertTrue(array.get(1)); assertTrue(array.get(2)); assertFalse(array.get(3)); assertTrue(array.get(4)); assertTrue(mListView.isItemChecked(1)); assertTrue(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertFalse(array.get(1)); assertFalse(array.get(2)); assertFalse(array.get(3)); assertFalse(array.get(4)); assertFalse(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(4)); }
public void testAccessItemChecked() { // NONE mode mListView.setChoiceMode(ListView.CHOICE_MODE_NONE); assertEquals(ListView.CHOICE_MODE_NONE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(1)); // SINGLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); assertEquals(ListView.CHOICE_MODE_SINGLE, mListView.getChoiceMode()); mListView.setItemChecked(2, true); assertEquals(2, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(2)); mListView.setItemChecked(3, true); assertEquals(3, mListView.getCheckedItemPosition()); assertTrue(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); // test attempt to uncheck a item that wasn't checked to begin with mListView.setItemChecked(4, false); // item three should still be checked assertEquals(3, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); assertTrue(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(4, true); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); assertFalse(mListView.isItemChecked(4)); // MULTIPLE mode mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); assertEquals(ListView.CHOICE_MODE_MULTIPLE, mListView.getChoiceMode()); mListView.setItemChecked(1, true); assertEquals(ListView.INVALID_POSITION, mListView.getCheckedItemPosition()); SparseBooleanArray array = mListView.getCheckedItemPositions(); assertTrue(array.get(1)); assertFalse(array.get(2)); assertTrue(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); mListView.setItemChecked(2, true); mListView.setItemChecked(3, false); mListView.setItemChecked(4, true); assertTrue(array.get(1)); assertTrue(array.get(2)); assertFalse(array.get(3)); assertTrue(array.get(4)); assertTrue(mListView.isItemChecked(1)); assertTrue(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertTrue(mListView.isItemChecked(4)); mListView.clearChoices(); assertFalse(array.get(1)); assertFalse(array.get(2)); assertFalse(array.get(3)); assertFalse(array.get(4)); assertFalse(mListView.isItemChecked(1)); assertFalse(mListView.isItemChecked(2)); assertFalse(mListView.isItemChecked(3)); assertFalse(mListView.isItemChecked(4)); }
diff --git a/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java b/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java index 7362bf686..455587d2c 100644 --- a/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java +++ b/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java @@ -1,52 +1,52 @@ /* * Copyright 2009-2011 Collaborative Research Centre SFB 632 * * 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 annis.sqlgen; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import annis.model.Annotation; import static annis.sqlgen.SqlConstraints.sqlString; public class ListDocumentsAnnotationsSqlHelper implements ParameterizedRowMapper<Annotation> { public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + - "ON docs.pre=meta.corpus_ref \n" + + "ON docs.id=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; } @Override public Annotation mapRow(ResultSet rs, int rowNum) throws SQLException { String namespace = rs.getString("namespace"); String name = rs.getString("name"); String value = rs.getString("value"); return new Annotation(namespace, name, value); } }
true
true
public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + "ON docs.pre=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; }
public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + "ON docs.id=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; }
diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java index 667b4dcc0..a1eb906b0 100755 --- a/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java @@ -1,162 +1,162 @@ /** * 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.transport.discovery; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.jms.DeliveryMode; import junit.framework.Test; import org.apache.activemq.broker.StubConnection; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.SessionInfo; import org.apache.activemq.network.NetworkTestSupport; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportFactory; import org.apache.activemq.transport.failover.FailoverTransport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DiscoveryTransportBrokerTest extends NetworkTestSupport { private static final Log LOG = LogFactory.getLog(DiscoveryTransportBrokerTest.class); String groupName; public void setUp() throws Exception { super.setAutoFail(true); super.setUp(); } public void testPublisherFailsOver() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); int deliveryMode = DeliveryMode.NON_PERSISTENT; // Start a normal consumer on the local broker StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.request(consumerInfo1); // Start a normal consumer on a remote broker StubConnection connection2 = createRemoteConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); // Start a failover publisher. StubConnection connection3 = createFailoverConnection(); ConnectionInfo connectionInfo3 = createConnectionInfo(); SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); connection3.send(connectionInfo3); connection3.send(sessionInfo3); connection3.send(producerInfo3); // Send the message using the fail over publisher. connection3.request(createMessage(producerInfo3, destination, deliveryMode)); // The message will be sent to one of the brokers. FailoverTransport ft = (FailoverTransport)connection3.getTransport().narrow(FailoverTransport.class); // See which broker we were connected to. StubConnection connectionA; StubConnection connectionB; TransportConnector serverA; - if (connector.getServer().getConnectURI().equals(ft.getConnectedTransportURI())) { + if (connector.getServer().getConnectURI().getPort() == ft.getConnectedTransportURI().getPort()) { connectionA = connection1; connectionB = connection2; serverA = connector; } else { connectionA = connection2; connectionB = connection1; serverA = remoteConnector; } assertNotNull(receiveMessage(connectionA)); assertNoMessagesLeft(connectionB); // Dispose the server so that it fails over to the other server. LOG.info("Disconnecting active server"); serverA.stop(); LOG.info("Sending request that should failover"); connection3.request(createMessage(producerInfo3, destination, deliveryMode)); assertNotNull(receiveMessage(connectionB)); assertNoMessagesLeft(connectionA); } protected String getLocalURI() { return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; } protected String getRemoteURI() { return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; } protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { TransportConnector x = super.createConnector(); x.setDiscoveryUri(new URI(getDiscoveryUri())); return x; } protected String getDiscoveryUri() { if ( groupName == null ) { groupName = "group-"+System.currentTimeMillis(); } return "multicast://default?group="+groupName; } protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { TransportConnector x = super.createRemoteConnector(); x.setDiscoveryUri(new URI(getDiscoveryUri())); return x; } protected StubConnection createFailoverConnection() throws Exception { URI failoverURI = new URI("discovery:" + getDiscoveryUri()); Transport transport = TransportFactory.connect(failoverURI); StubConnection connection = new StubConnection(transport); connections.add(connection); return connection; } public static Test suite() { return suite(DiscoveryTransportBrokerTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
true
true
public void testPublisherFailsOver() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); int deliveryMode = DeliveryMode.NON_PERSISTENT; // Start a normal consumer on the local broker StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.request(consumerInfo1); // Start a normal consumer on a remote broker StubConnection connection2 = createRemoteConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); // Start a failover publisher. StubConnection connection3 = createFailoverConnection(); ConnectionInfo connectionInfo3 = createConnectionInfo(); SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); connection3.send(connectionInfo3); connection3.send(sessionInfo3); connection3.send(producerInfo3); // Send the message using the fail over publisher. connection3.request(createMessage(producerInfo3, destination, deliveryMode)); // The message will be sent to one of the brokers. FailoverTransport ft = (FailoverTransport)connection3.getTransport().narrow(FailoverTransport.class); // See which broker we were connected to. StubConnection connectionA; StubConnection connectionB; TransportConnector serverA; if (connector.getServer().getConnectURI().equals(ft.getConnectedTransportURI())) { connectionA = connection1; connectionB = connection2; serverA = connector; } else { connectionA = connection2; connectionB = connection1; serverA = remoteConnector; } assertNotNull(receiveMessage(connectionA)); assertNoMessagesLeft(connectionB); // Dispose the server so that it fails over to the other server. LOG.info("Disconnecting active server"); serverA.stop(); LOG.info("Sending request that should failover"); connection3.request(createMessage(producerInfo3, destination, deliveryMode)); assertNotNull(receiveMessage(connectionB)); assertNoMessagesLeft(connectionA); }
public void testPublisherFailsOver() throws Exception { ActiveMQDestination destination = new ActiveMQQueue("TEST"); int deliveryMode = DeliveryMode.NON_PERSISTENT; // Start a normal consumer on the local broker StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); connection1.send(connectionInfo1); connection1.send(sessionInfo1); connection1.request(consumerInfo1); // Start a normal consumer on a remote broker StubConnection connection2 = createRemoteConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); connection2.send(connectionInfo2); connection2.send(sessionInfo2); connection2.request(consumerInfo2); // Start a failover publisher. StubConnection connection3 = createFailoverConnection(); ConnectionInfo connectionInfo3 = createConnectionInfo(); SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); connection3.send(connectionInfo3); connection3.send(sessionInfo3); connection3.send(producerInfo3); // Send the message using the fail over publisher. connection3.request(createMessage(producerInfo3, destination, deliveryMode)); // The message will be sent to one of the brokers. FailoverTransport ft = (FailoverTransport)connection3.getTransport().narrow(FailoverTransport.class); // See which broker we were connected to. StubConnection connectionA; StubConnection connectionB; TransportConnector serverA; if (connector.getServer().getConnectURI().getPort() == ft.getConnectedTransportURI().getPort()) { connectionA = connection1; connectionB = connection2; serverA = connector; } else { connectionA = connection2; connectionB = connection1; serverA = remoteConnector; } assertNotNull(receiveMessage(connectionA)); assertNoMessagesLeft(connectionB); // Dispose the server so that it fails over to the other server. LOG.info("Disconnecting active server"); serverA.stop(); LOG.info("Sending request that should failover"); connection3.request(createMessage(producerInfo3, destination, deliveryMode)); assertNotNull(receiveMessage(connectionB)); assertNoMessagesLeft(connectionA); }
diff --git a/gcov/org.eclipse.linuxtools.gcov/src/org/eclipse/linuxtools/gcov/dialog/OpenGCDialog.java b/gcov/org.eclipse.linuxtools.gcov/src/org/eclipse/linuxtools/gcov/dialog/OpenGCDialog.java index 1d8b3ceb9..5b69b71a3 100644 --- a/gcov/org.eclipse.linuxtools.gcov/src/org/eclipse/linuxtools/gcov/dialog/OpenGCDialog.java +++ b/gcov/org.eclipse.linuxtools.gcov/src/org/eclipse/linuxtools/gcov/dialog/OpenGCDialog.java @@ -1,303 +1,303 @@ /******************************************************************************* * Copyright (c) 2009 STMicroelectronics. * 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: * Xavier Raynaud <xavier.raynaud@st.com> - initial API and implementation *******************************************************************************/ package org.eclipse.linuxtools.gcov.dialog; import java.io.File; import org.eclipse.cdt.core.IBinaryParser.IBinaryObject; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.linuxtools.binutils.utils.STSymbolManager; import org.eclipse.linuxtools.gcov.Activator; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.ui.views.navigator.ResourceComparator; /** * This dialog box is opened when user clicks on a gcno/gcda file. * it allows the user to choose the binary file who produced the gcno/gcda file. * @author Xavier Raynaud <xavier.raynaud@st.com> * */ public class OpenGCDialog extends Dialog { /* Inputs */ private Text binText; private String binValue; private Button openThisFileOnlyButton; private Button openCoverageSummaryButton; private boolean openCoverageSummary = true; /* buttons */ private Button binBrowseWorkspaceButton; private Button binBrowseFileSystemButton; /* error label */ private Label errorLabel; /* validation boolean */ private boolean binaryValid; /* internal listener */ private final BinaryModifyListener binModifyListener = new BinaryModifyListener(); private final String defaultValue; private final IPath gcFile; /** * Constructor * @param parentShell * @param binPath the path to a binary file. */ public OpenGCDialog(Shell parentShell, String binPath, IPath gcFile) { super(parentShell); this.gcFile = gcFile; setShellStyle(getShellStyle() | SWT.RESIZE); this.defaultValue = binPath; } /** * Gets the Binary file selected by the user * @return a path to a binary file */ public String getBinaryFile() { return binValue; } /** * Gets whether the user wants a complete coverage result, or a result specific file to the given gcFile. */ public boolean isCompleteCoverageResultWanted() { return openCoverageSummary; } protected Control createContents(Composite parent) { Control composite = super.createContents(parent); validateBinary(); return composite; } protected Control createDialogArea(Composite parent) { this.getShell().setText("Gcov - Open coverage results..."); Composite composite = (Composite) super.createDialogArea(parent); /* first line */ Group c = new Group(composite, SWT.NONE); c.setText("Binary File"); - c.setToolTipText("Please enter here the binary file who produced this gcov trace."); + c.setToolTipText("Please enter here the binary file which produced the coverage data."); GridLayout layout = new GridLayout(2,false); c.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); c.setLayoutData(data); Label binLabel = new Label(c,SWT.NONE); - binLabel.setText("Please enter here the binary file who produced gcov trace"); + binLabel.setText("Please enter here the binary file which produced the coverage data."); data = new GridData(); data.horizontalSpan = 2; binLabel.setLayoutData(data); binText = new Text(c,SWT.BORDER); binText.setText(this.defaultValue); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; binText.setLayoutData(data); binText.addModifyListener(binModifyListener); Composite cbBin = new Composite(c,SWT.NONE); data = new GridData(GridData.HORIZONTAL_ALIGN_END); cbBin.setLayoutData(data); cbBin.setLayout(new GridLayout(2, true)); binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH); binBrowseWorkspaceButton.setText("&Workspace..."); binBrowseWorkspaceButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowseWorkspace("Open Binary file...", binText); } } ); binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH); binBrowseFileSystemButton.setText("&File System..."); binBrowseFileSystemButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowse("Open Binary file...", binText); } } ); Group covMode = new Group(composite, SWT.NONE); covMode.setText("Coverage result"); covMode.setToolTipText("Please choose the result scope."); GridData covModeData = new GridData(GridData.FILL_BOTH); covMode.setLayoutData(covModeData); covMode.setLayout(new GridLayout()); openThisFileOnlyButton = new Button(covMode, SWT.RADIO); openThisFileOnlyButton.setLayoutData(new GridData()); openCoverageSummaryButton = new Button(covMode, SWT.RADIO); openCoverageSummaryButton.setLayoutData(new GridData()); String cFile = gcFile.removeFileExtension().lastSegment() + ".c"; openThisFileOnlyButton.setText("Show coverage details for \"" + cFile + "\" only."); openCoverageSummaryButton.setText("Show coverage for the whole selected binary file"); openCoverageSummaryButton.setSelection(true); SelectionAdapter sa = new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { openCoverageSummary = openCoverageSummaryButton.getSelection(); } }; openCoverageSummaryButton.addSelectionListener(sa); openThisFileOnlyButton.addSelectionListener(sa); /* 2sd line */ errorLabel = new Label(composite,SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 3; errorLabel.setLayoutData(data); errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED)); c.layout(); return composite; } private void validateBinary() { binValue = binText.getText(); IStringVariableManager mgr = VariablesPlugin.getDefault().getStringVariableManager(); try { binValue = mgr.performStringSubstitution(binValue, false); } catch (CoreException _) { // do nothing: never occurs } File f = new File(binValue); if (f.exists()) { IBinaryObject binary = STSymbolManager.sharedInstance.getBinaryObject(new Path(binValue)); if (binary == null) { MessageDialog.openError( PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Invalid binary file", binText.getText() + " is not a valid binary file."); return; } binaryValid = true; getButton(IDialogConstants.OK_ID).setEnabled(binaryValid); errorLabel.setText(""); } else { binaryValid = false; getButton(IDialogConstants.OK_ID).setEnabled(false); if (!binValue.equals("")) { errorLabel.setText("\"" + binText.getText() + "\" doesn't exist"); } else { errorLabel.setText("Please enter a binary file"); } return; } } private class BinaryModifyListener implements ModifyListener { public void modifyText(ModifyEvent e) { validateBinary(); } } protected void handleBrowseWorkspace(String msg, Text text) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setTitle(msg); dialog.setMessage(msg); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setComparator(new ResourceComparator(ResourceComparator.NAME)); dialog.setAllowMultiple(false); IContainer c = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(this.gcFile); if (c != null) dialog.setInitialSelection(c.getProject()); dialog.setValidator(new ISelectionStatusValidator() { public IStatus validate(Object[] selection) { if (selection.length != 1) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ } if (!(selection[0] instanceof IFile)) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ } return new Status(IStatus.OK, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ } }); if (dialog.open() == IDialogConstants.OK_ID) { IResource resource = (IResource) dialog.getFirstResult(); text.setText("${resource_loc:" + resource.getFullPath() + "}"); } } protected void handleBrowse(String msg, Text text) { FileDialog dialog = new FileDialog(this.getShell(),SWT.OPEN); dialog.setText(msg); String t = text.getText(); IStringVariableManager mgr = VariablesPlugin.getDefault().getStringVariableManager(); try { t = mgr.performStringSubstitution(t, false); } catch (CoreException _) { // do nothing: never occurs } File f = new File(t); t = f.getParent(); if (t == null || t.length() == 0) { t = this.gcFile.removeLastSegments(1).toOSString(); } dialog.setFilterPath(t); String s = dialog.open(); if (s != null) text.setText(s); } }
false
true
protected Control createDialogArea(Composite parent) { this.getShell().setText("Gcov - Open coverage results..."); Composite composite = (Composite) super.createDialogArea(parent); /* first line */ Group c = new Group(composite, SWT.NONE); c.setText("Binary File"); c.setToolTipText("Please enter here the binary file who produced this gcov trace."); GridLayout layout = new GridLayout(2,false); c.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); c.setLayoutData(data); Label binLabel = new Label(c,SWT.NONE); binLabel.setText("Please enter here the binary file who produced gcov trace"); data = new GridData(); data.horizontalSpan = 2; binLabel.setLayoutData(data); binText = new Text(c,SWT.BORDER); binText.setText(this.defaultValue); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; binText.setLayoutData(data); binText.addModifyListener(binModifyListener); Composite cbBin = new Composite(c,SWT.NONE); data = new GridData(GridData.HORIZONTAL_ALIGN_END); cbBin.setLayoutData(data); cbBin.setLayout(new GridLayout(2, true)); binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH); binBrowseWorkspaceButton.setText("&Workspace..."); binBrowseWorkspaceButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowseWorkspace("Open Binary file...", binText); } } ); binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH); binBrowseFileSystemButton.setText("&File System..."); binBrowseFileSystemButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowse("Open Binary file...", binText); } } ); Group covMode = new Group(composite, SWT.NONE); covMode.setText("Coverage result"); covMode.setToolTipText("Please choose the result scope."); GridData covModeData = new GridData(GridData.FILL_BOTH); covMode.setLayoutData(covModeData); covMode.setLayout(new GridLayout()); openThisFileOnlyButton = new Button(covMode, SWT.RADIO); openThisFileOnlyButton.setLayoutData(new GridData()); openCoverageSummaryButton = new Button(covMode, SWT.RADIO); openCoverageSummaryButton.setLayoutData(new GridData()); String cFile = gcFile.removeFileExtension().lastSegment() + ".c"; openThisFileOnlyButton.setText("Show coverage details for \"" + cFile + "\" only."); openCoverageSummaryButton.setText("Show coverage for the whole selected binary file"); openCoverageSummaryButton.setSelection(true); SelectionAdapter sa = new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { openCoverageSummary = openCoverageSummaryButton.getSelection(); } }; openCoverageSummaryButton.addSelectionListener(sa); openThisFileOnlyButton.addSelectionListener(sa); /* 2sd line */ errorLabel = new Label(composite,SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 3; errorLabel.setLayoutData(data); errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED)); c.layout(); return composite; }
protected Control createDialogArea(Composite parent) { this.getShell().setText("Gcov - Open coverage results..."); Composite composite = (Composite) super.createDialogArea(parent); /* first line */ Group c = new Group(composite, SWT.NONE); c.setText("Binary File"); c.setToolTipText("Please enter here the binary file which produced the coverage data."); GridLayout layout = new GridLayout(2,false); c.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); c.setLayoutData(data); Label binLabel = new Label(c,SWT.NONE); binLabel.setText("Please enter here the binary file which produced the coverage data."); data = new GridData(); data.horizontalSpan = 2; binLabel.setLayoutData(data); binText = new Text(c,SWT.BORDER); binText.setText(this.defaultValue); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; binText.setLayoutData(data); binText.addModifyListener(binModifyListener); Composite cbBin = new Composite(c,SWT.NONE); data = new GridData(GridData.HORIZONTAL_ALIGN_END); cbBin.setLayoutData(data); cbBin.setLayout(new GridLayout(2, true)); binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH); binBrowseWorkspaceButton.setText("&Workspace..."); binBrowseWorkspaceButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowseWorkspace("Open Binary file...", binText); } } ); binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH); binBrowseFileSystemButton.setText("&File System..."); binBrowseFileSystemButton.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { handleBrowse("Open Binary file...", binText); } } ); Group covMode = new Group(composite, SWT.NONE); covMode.setText("Coverage result"); covMode.setToolTipText("Please choose the result scope."); GridData covModeData = new GridData(GridData.FILL_BOTH); covMode.setLayoutData(covModeData); covMode.setLayout(new GridLayout()); openThisFileOnlyButton = new Button(covMode, SWT.RADIO); openThisFileOnlyButton.setLayoutData(new GridData()); openCoverageSummaryButton = new Button(covMode, SWT.RADIO); openCoverageSummaryButton.setLayoutData(new GridData()); String cFile = gcFile.removeFileExtension().lastSegment() + ".c"; openThisFileOnlyButton.setText("Show coverage details for \"" + cFile + "\" only."); openCoverageSummaryButton.setText("Show coverage for the whole selected binary file"); openCoverageSummaryButton.setSelection(true); SelectionAdapter sa = new SelectionAdapter() { public void widgetSelected(SelectionEvent sev) { openCoverageSummary = openCoverageSummaryButton.getSelection(); } }; openCoverageSummaryButton.addSelectionListener(sa); openThisFileOnlyButton.addSelectionListener(sa); /* 2sd line */ errorLabel = new Label(composite,SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalSpan = 3; errorLabel.setLayoutData(data); errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED)); c.layout(); return composite; }
diff --git a/MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java b/MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java index e9d4319..0bff43d 100644 --- a/MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java +++ b/MachinaFactory/src/me/lyneira/ItemRelay/DispenserRelay.java @@ -1,56 +1,56 @@ package me.lyneira.ItemRelay; import me.lyneira.MachinaCore.BlockLocation; import me.lyneira.MachinaCore.BlockRotation; import me.lyneira.MachinaFactory.ComponentActivateException; import me.lyneira.MachinaFactory.ComponentDetectException; import me.lyneira.util.InventoryTransaction; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; /** * Item Relay with a dispenser as container. Will also suck in items near it on * each tick. * * @author Lyneira */ public class DispenserRelay extends ItemRelay { private static final double suctionDistance = 3; DispenserRelay(Blueprint blueprint, BlockLocation anchor, BlockRotation yaw, Player player) throws ComponentActivateException, ComponentDetectException { super(blueprint, blueprint.blueprintDispenser, anchor, yaw, player); } /** * Sucks items within a certain distance into the dispenser. */ @Override protected void relayActions() { BlockLocation container = container(); Location location = container.getLocation(); for (Entity i : container.getWorld().getEntitiesByClass(Item.class)) { - if (i.getLocation().distance(location) < suctionDistance) { + if (! i.isDead() && i.getLocation().distance(location) < suctionDistance) { ItemStack item = ((Item) i).getItemStack(); Inventory myInventory = (((InventoryHolder) container().getBlock().getState()).getInventory()); InventoryTransaction transaction = new InventoryTransaction(myInventory); transaction.add(item); if (transaction.execute()) { age = 0; i.remove(); } } } } @Override protected BlockLocation container() { return anchor.getRelative(blueprint.dispenser.vector(yaw)); } }
true
true
protected void relayActions() { BlockLocation container = container(); Location location = container.getLocation(); for (Entity i : container.getWorld().getEntitiesByClass(Item.class)) { if (i.getLocation().distance(location) < suctionDistance) { ItemStack item = ((Item) i).getItemStack(); Inventory myInventory = (((InventoryHolder) container().getBlock().getState()).getInventory()); InventoryTransaction transaction = new InventoryTransaction(myInventory); transaction.add(item); if (transaction.execute()) { age = 0; i.remove(); } } } }
protected void relayActions() { BlockLocation container = container(); Location location = container.getLocation(); for (Entity i : container.getWorld().getEntitiesByClass(Item.class)) { if (! i.isDead() && i.getLocation().distance(location) < suctionDistance) { ItemStack item = ((Item) i).getItemStack(); Inventory myInventory = (((InventoryHolder) container().getBlock().getState()).getInventory()); InventoryTransaction transaction = new InventoryTransaction(myInventory); transaction.add(item); if (transaction.execute()) { age = 0; i.remove(); } } } }
diff --git a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/ASMExecEnv.java b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/ASMExecEnv.java index a539c362..db034bf7 100644 --- a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/ASMExecEnv.java +++ b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/ASMExecEnv.java @@ -1,311 +1,311 @@ package org.eclipse.m2m.atl.engine.vm; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMBoolean; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMEnumLiteral; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMInteger; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModule; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclType; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclUndefined; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMReal; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMString; import org.eclipse.m2m.atl.engine.vm.nativelib.ASMTupleType; /** * An ASMExecEnv is an execution environment for ATL Stack Machine programs. * It holds: * * the only call Stack of the machine (no multi-thread support required), * * the Map of models used by the program, * * the Map of program-specific operations and attribute helpers. * This permits several transformations to be launched in sequence without altering one another. * @author Fr�d�ric Jouault */ public class ASMExecEnv extends ExecEnv { public ASMExecEnv(ASMModule asm, Debugger debugger) { this(asm, debugger, true); } public ASMExecEnv(ASMModule asm, Debugger debugger, boolean cacheAttributeHelperResults) { super(debugger); this.asm = asm; globalVariables.put(asm.getName(), asm); typeOperations = new HashMap(); attributeInitializers = new HashMap(); helperValuesByElement = new HashMap(); vmTypeOperations = ASMOclType.getVMOperations(); this.cacheAttributeHelperResults = cacheAttributeHelperResults; } public ASMModule getASMModule() { return asm; } public void registerOperations(ASM asm) { for(Iterator i = asm.getOperations().iterator() ; i.hasNext() ; ) { ASMOperation op = (ASMOperation)i.next(); String signature = op.getContextSignature(); if(signature.matches("^(Q|G|C|E|O|N).*$")) { // Sequence, Bag, Collection, Set, OrderedSet, Native type System.out.println("Unsupported registration: " + signature); // } else if(signature.startsWith("T")) { // System.out.println("Unsupported registration: " + signature); } else { try { ASMOclType type = parseType(new StringCharacterIterator(signature)); //System.out.println("registering " + op + " on " + type); registerOperation(type, op); op.setContextType(type); } catch(SignatureParsingException spe) { spe.printStackTrace(System.out); } } } } // read until c, including c // returns everything read before c private String readUntil(CharacterIterator ci, char c) throws SignatureParsingException { StringBuffer ret = new StringBuffer(); while(ci.current() != c) { ret.append(ci.current()); ci.next(); } read(ci, c); return ret.toString(); } private void read(CharacterIterator ci, char c) throws SignatureParsingException { if(ci.current() != c) throw new SignatureParsingException("Expected \'" + c + "\', found \'" + ci.current() + "\' at position " + ci.getIndex() + "."); ci.next(); } private ASMOclType parseType(CharacterIterator ci) throws SignatureParsingException { ASMOclType ret = parseTypeInternal(ci); if(ci.next() != CharacterIterator.DONE) { throw new SignatureParsingException("End of type signature expected at position " + ci.getIndex() + "."); } return ret; } private ASMOclType parseTypeInternal(CharacterIterator ci) throws SignatureParsingException { ASMOclType ret = null; switch(ci.current()) { case 'Q': case 'G': case 'C': // Sequence, Bag, Collection, case 'E': case 'O': case 'N': // Set, OrderedSet, Native type ci.next(); - //ASMOclType elementType = parseTypeInternal(ci); - read(ci, ';'); + ASMOclType elementType = parseTypeInternal(ci); + //read(ci, ';'); break; case 'T': // Tuple ci.next(); Map attrs = new HashMap(); while(ci.current() != ';') { ASMOclType attrType = parseTypeInternal(ci); String attrName = readUntil(ci, ';'); //attrs.put(attrName, attrType); // TODO: correct type attrs.put(attrName, ASMOclAny.myType); } ret = new ASMTupleType(attrs); break; case 'M': // Metamodel Class ci.next(); String mname = readUntil(ci, '!'); String name = readUntil(ci, ';'); ASMModel model = getModel(mname); if(model != null) { ASMModelElement ame = model.findModelElement(name); if(ame == null) throw new SignatureParsingException("ERROR: could not find model element " + name + " from " + mname); ret = ame; } else { System.out.println("WARNING: could not find model " + mname + "."); } break; // Primitive types, VM Types case 'A': // Module ret = ASMModule.myType; ci.next(); break; case 'J': // Object => OclAny ? ret = ASMOclAny.myType; ci.next(); break; case 'V': // Void ret = ASMOclUndefined.myType; ci.next(); break; case 'I': // Integer ret = ASMInteger.myType; ci.next(); break; case 'B': // Boolean ret = ASMBoolean.myType; ci.next(); break; case 'S': // String ret = ASMString.myType; ci.next(); break; case 'Z': // String ret = ASMEnumLiteral.myType; ci.next(); break; case 'D': // Real ret = ASMReal.myType; ci.next(); break; case 'L': // Model ret = ASMModel.myType; ci.next(); break; case CharacterIterator.DONE: throw new SignatureParsingException("End of type signature unexpected at position " + ci.getIndex() + "."); default: throw new SignatureParsingException("Unknown type code : " + ci + "."); } return ret; } private class SignatureParsingException extends Exception { public SignatureParsingException(String msg) { super(msg); } } private void registerOperation(ASMOclType type, Operation oper) { getOperations(type, true).put(oper.getName(), oper); } private Map getOperations(ASMOclType type, boolean createIfMissing) { Map ret = (Map)typeOperations.get(type); if(ret == null) { Map vmops = getVMOperations(type); if(createIfMissing || ((vmops != null) && !vmops.isEmpty())) { ret = new HashMap(); typeOperations.put(type, ret); if(vmops != null) ret.putAll(vmops); } } return ret; } private Map getVMOperations(ASMOclType type) { return (Map)vmTypeOperations.get(type); } public Collection getOperations(ASMOclType type) { Collection ret = null; ret = getOperations(type, true).values(); return ret; } public Operation getOperation(ASMOclType type, String name) { final boolean debug = false; Operation ret = null; Map map = getOperations(type, false); if(map != null) ret = (Operation)map.get(name); if(debug) System.out.println(this + "@" + this.hashCode() + ".getOperation(" + name + ")"); if(ret == null) { if(debug) System.out.println("looking in super of this for operation " + name); for(Iterator i = type.getSupertypes().iterator() ; i.hasNext() && (ret == null) ; ) { ASMOclType st = (ASMOclType)i.next(); ret = getOperation(st, name); } } return ret; } public void registerAttributeHelper(ASMOclType type, String name, Operation oper) { getAttributeInitializers(type, true).put(name, oper); } public Operation getAttributeInitializer(ASMOclType type, String name) { Operation ret = null; Map map = getAttributeInitializers(type, false); if(map != null) ret = (Operation)map.get(name); if(ret == null) { for(Iterator i = type.getSupertypes().iterator() ; i.hasNext() && (ret == null) ; ) { ASMOclType st = (ASMOclType)i.next(); ret = getAttributeInitializer(st, name); } } return ret; } private Map getAttributeInitializers(ASMOclType type, boolean createIfMissing) { Map ret = (Map)attributeInitializers.get(type); if(createIfMissing && (ret == null)) { ret = new HashMap(); attributeInitializers.put(type, ret); } return ret; } private Map getHelperValues(ASMOclAny element) { Map ret = (Map)helperValuesByElement.get(element); if(ret == null) { ret = new HashMap(); helperValuesByElement.put(element, ret); } return ret; } public ASMOclAny getHelperValue(StackFrame frame, ASMOclAny element, String name) { Map helperValues = getHelperValues(element); ASMOclAny ret = (ASMOclAny)helperValues.get(name); if(ret == null) { ASMOperation o = (ASMOperation)getAttributeInitializer(element.getType(), name); List args = new ArrayList(); args.add(element); ret = o.exec(frame.enterFrame(o, args)); if(cacheAttributeHelperResults) helperValues.put(name, ret); } return ret; } private boolean cacheAttributeHelperResults; private ASMModule asm; private Map typeOperations; private Map vmTypeOperations; private Map attributeInitializers; private Map helperValuesByElement; }
true
true
private ASMOclType parseTypeInternal(CharacterIterator ci) throws SignatureParsingException { ASMOclType ret = null; switch(ci.current()) { case 'Q': case 'G': case 'C': // Sequence, Bag, Collection, case 'E': case 'O': case 'N': // Set, OrderedSet, Native type ci.next(); //ASMOclType elementType = parseTypeInternal(ci); read(ci, ';'); break; case 'T': // Tuple ci.next(); Map attrs = new HashMap(); while(ci.current() != ';') { ASMOclType attrType = parseTypeInternal(ci); String attrName = readUntil(ci, ';'); //attrs.put(attrName, attrType); // TODO: correct type attrs.put(attrName, ASMOclAny.myType); } ret = new ASMTupleType(attrs); break; case 'M': // Metamodel Class ci.next(); String mname = readUntil(ci, '!'); String name = readUntil(ci, ';'); ASMModel model = getModel(mname); if(model != null) { ASMModelElement ame = model.findModelElement(name); if(ame == null) throw new SignatureParsingException("ERROR: could not find model element " + name + " from " + mname); ret = ame; } else { System.out.println("WARNING: could not find model " + mname + "."); } break; // Primitive types, VM Types case 'A': // Module ret = ASMModule.myType; ci.next(); break; case 'J': // Object => OclAny ? ret = ASMOclAny.myType; ci.next(); break; case 'V': // Void ret = ASMOclUndefined.myType; ci.next(); break; case 'I': // Integer ret = ASMInteger.myType; ci.next(); break; case 'B': // Boolean ret = ASMBoolean.myType; ci.next(); break; case 'S': // String ret = ASMString.myType; ci.next(); break; case 'Z': // String ret = ASMEnumLiteral.myType; ci.next(); break; case 'D': // Real ret = ASMReal.myType; ci.next(); break; case 'L': // Model ret = ASMModel.myType; ci.next(); break; case CharacterIterator.DONE: throw new SignatureParsingException("End of type signature unexpected at position " + ci.getIndex() + "."); default: throw new SignatureParsingException("Unknown type code : " + ci + "."); } return ret; }
private ASMOclType parseTypeInternal(CharacterIterator ci) throws SignatureParsingException { ASMOclType ret = null; switch(ci.current()) { case 'Q': case 'G': case 'C': // Sequence, Bag, Collection, case 'E': case 'O': case 'N': // Set, OrderedSet, Native type ci.next(); ASMOclType elementType = parseTypeInternal(ci); //read(ci, ';'); break; case 'T': // Tuple ci.next(); Map attrs = new HashMap(); while(ci.current() != ';') { ASMOclType attrType = parseTypeInternal(ci); String attrName = readUntil(ci, ';'); //attrs.put(attrName, attrType); // TODO: correct type attrs.put(attrName, ASMOclAny.myType); } ret = new ASMTupleType(attrs); break; case 'M': // Metamodel Class ci.next(); String mname = readUntil(ci, '!'); String name = readUntil(ci, ';'); ASMModel model = getModel(mname); if(model != null) { ASMModelElement ame = model.findModelElement(name); if(ame == null) throw new SignatureParsingException("ERROR: could not find model element " + name + " from " + mname); ret = ame; } else { System.out.println("WARNING: could not find model " + mname + "."); } break; // Primitive types, VM Types case 'A': // Module ret = ASMModule.myType; ci.next(); break; case 'J': // Object => OclAny ? ret = ASMOclAny.myType; ci.next(); break; case 'V': // Void ret = ASMOclUndefined.myType; ci.next(); break; case 'I': // Integer ret = ASMInteger.myType; ci.next(); break; case 'B': // Boolean ret = ASMBoolean.myType; ci.next(); break; case 'S': // String ret = ASMString.myType; ci.next(); break; case 'Z': // String ret = ASMEnumLiteral.myType; ci.next(); break; case 'D': // Real ret = ASMReal.myType; ci.next(); break; case 'L': // Model ret = ASMModel.myType; ci.next(); break; case CharacterIterator.DONE: throw new SignatureParsingException("End of type signature unexpected at position " + ci.getIndex() + "."); default: throw new SignatureParsingException("Unknown type code : " + ci + "."); } return ret; }
diff --git a/eclipse/workspace/paf/src/ontology/HTMLTagger.java b/eclipse/workspace/paf/src/ontology/HTMLTagger.java index 3da07df..918f02c 100644 --- a/eclipse/workspace/paf/src/ontology/HTMLTagger.java +++ b/eclipse/workspace/paf/src/ontology/HTMLTagger.java @@ -1,103 +1,104 @@ package ontology; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import analyse.MyDocument; public class HTMLTagger { public static void tagHTML(HashMap<MyDocument, LinkedDocument> docs) { for (LinkedDocument doc : docs.values()){ String line; ArrayList<String> lignes = new ArrayList<String>(); InputStream file = null; String repoSaved="docTxt/docSaved/"; String repoTagged="docTxt/docTagged/"; try { file = new FileInputStream(repoSaved+doc.getHTMLfile()); } catch (FileNotFoundException e) {} BufferedReader br = new BufferedReader(new InputStreamReader(file)); try { while((line = br.readLine()) !=null){ lignes.add(line); } br.close(); file.close(); } catch (IOException e) {e.printStackTrace();} for(int n =0;n<lignes.size();n++){ ArrayList<String> newline = new ArrayList<String>(); String s = lignes.get(n); int i=0,j=0; while(i<s.length()){ char c = s.charAt(i); if (c=='<' || c=='>' || c==' ' || c=='\''||c==8217 || c==';' || c=='.' || c==',' || c=='(' || c==')'){ // System.out.println("caractère stop : "+c+" i="+i+" j="+j); // System.out.println((int)s.charAt(j+1)); newline.add(testMot(s.substring(j,i),doc)); j=i+1; + if(c=='<') while(i<s.length() && s.charAt(j)!='>') j++; newline.add(s.substring(i,j)); } - i++; + i=Math.max(j,i+1); } newline.add(s.substring(j,s.length())); lignes.set(n, append(newline)); } try { FileWriter fw = new FileWriter(repoTagged+doc.HTMLfile); BufferedWriter bw = new BufferedWriter(fw); for(String s: lignes){ // System.out.println(s); bw.write(s+"\n"); } bw.close(); fw.close(); } catch (IOException e) {e.printStackTrace();} lignes.clear(); } } private static String append(ArrayList<String> newline) { String result = ""; for (String s : newline) result = result+s; return result; } private static String testMot(String mot, LinkedDocument doc) { if (doc.getWordsToEnhance().contains(mot.toLowerCase())) //return ("<span class=\"verbeOnto\">"+mot+"</span>"); return ("<span style=\"color:red;\">"+mot+"</span>"); else if (doc.getWordsToSuggest().contains(mot.toLowerCase())) //return ("<span class=\"verbePasOnto\">"+mot+"</span>"); return ("<span style=\"color:blue;\">"+mot+"</span>"); else if (doc.getMotsPropres().contains(mot.toLowerCase())) //return ("<span class=\"nomsPropres;\">"+mot+"</span>"); return ("<span style=\"color:green;\">"+mot+"</span>"); else if (doc.getHighTfidfWords().containsKey(mot.toLowerCase())){ float tfidf = doc.getHighTfidfWords().get(mot.toLowerCase()); //return ("<span class=\"highTfidf;\">"+mot+"</span>"); return ("<span style=\"color:#2c3e50;\" tfidf=\""+tfidf+ "\" title=\"tfidf: "+tfidf+"\" >"+mot+"</span>"); } else return mot; } }
false
true
public static void tagHTML(HashMap<MyDocument, LinkedDocument> docs) { for (LinkedDocument doc : docs.values()){ String line; ArrayList<String> lignes = new ArrayList<String>(); InputStream file = null; String repoSaved="docTxt/docSaved/"; String repoTagged="docTxt/docTagged/"; try { file = new FileInputStream(repoSaved+doc.getHTMLfile()); } catch (FileNotFoundException e) {} BufferedReader br = new BufferedReader(new InputStreamReader(file)); try { while((line = br.readLine()) !=null){ lignes.add(line); } br.close(); file.close(); } catch (IOException e) {e.printStackTrace();} for(int n =0;n<lignes.size();n++){ ArrayList<String> newline = new ArrayList<String>(); String s = lignes.get(n); int i=0,j=0; while(i<s.length()){ char c = s.charAt(i); if (c=='<' || c=='>' || c==' ' || c=='\''||c==8217 || c==';' || c=='.' || c==',' || c=='(' || c==')'){ // System.out.println("caractère stop : "+c+" i="+i+" j="+j); // System.out.println((int)s.charAt(j+1)); newline.add(testMot(s.substring(j,i),doc)); j=i+1; newline.add(s.substring(i,j)); } i++; } newline.add(s.substring(j,s.length())); lignes.set(n, append(newline)); } try { FileWriter fw = new FileWriter(repoTagged+doc.HTMLfile); BufferedWriter bw = new BufferedWriter(fw); for(String s: lignes){ // System.out.println(s); bw.write(s+"\n"); } bw.close(); fw.close(); } catch (IOException e) {e.printStackTrace();} lignes.clear(); } }
public static void tagHTML(HashMap<MyDocument, LinkedDocument> docs) { for (LinkedDocument doc : docs.values()){ String line; ArrayList<String> lignes = new ArrayList<String>(); InputStream file = null; String repoSaved="docTxt/docSaved/"; String repoTagged="docTxt/docTagged/"; try { file = new FileInputStream(repoSaved+doc.getHTMLfile()); } catch (FileNotFoundException e) {} BufferedReader br = new BufferedReader(new InputStreamReader(file)); try { while((line = br.readLine()) !=null){ lignes.add(line); } br.close(); file.close(); } catch (IOException e) {e.printStackTrace();} for(int n =0;n<lignes.size();n++){ ArrayList<String> newline = new ArrayList<String>(); String s = lignes.get(n); int i=0,j=0; while(i<s.length()){ char c = s.charAt(i); if (c=='<' || c=='>' || c==' ' || c=='\''||c==8217 || c==';' || c=='.' || c==',' || c=='(' || c==')'){ // System.out.println("caractère stop : "+c+" i="+i+" j="+j); // System.out.println((int)s.charAt(j+1)); newline.add(testMot(s.substring(j,i),doc)); j=i+1; if(c=='<') while(i<s.length() && s.charAt(j)!='>') j++; newline.add(s.substring(i,j)); } i=Math.max(j,i+1); } newline.add(s.substring(j,s.length())); lignes.set(n, append(newline)); } try { FileWriter fw = new FileWriter(repoTagged+doc.HTMLfile); BufferedWriter bw = new BufferedWriter(fw); for(String s: lignes){ // System.out.println(s); bw.write(s+"\n"); } bw.close(); fw.close(); } catch (IOException e) {e.printStackTrace();} lignes.clear(); } }
diff --git a/src/imo/GraphGen.java b/src/imo/GraphGen.java index 9e5351a..de737ec 100644 --- a/src/imo/GraphGen.java +++ b/src/imo/GraphGen.java @@ -1,173 +1,173 @@ package imo; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; import java.util.Scanner; import java.util.Set; import org.apache.commons.collections15.Factory; import edu.uci.ics.jung.algorithms.generators.random.MixedRandomGraphGenerator; import edu.uci.ics.jung.graph.DirectedSparseGraph; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseGraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.graph.util.Pair; /** * A class for generating Graphs, either randomly or from a file. * */ public final class GraphGen { private GraphGen() { //Cannot instantiate } /** * Randomly generates a Graph within specified parameters. * @param numV Number of vertices. * @param minW Minimum edge weight, inclusive. * @param maxW Maximum edge weight, exclusive. * @return A random Graph with numV vertices and numE edges. */ public static Graph<Vertex, Edge> getGraph( final int numV, final int minW, final int maxW) { return getGraph( numV, minW, maxW, System.currentTimeMillis()); } /** * Randomly generates a Graph within specified parameters. * @param numV Number of vertices. * @param minW Minimum edge weight, inclusive. * @Param maxW Maximum edge weight, exclusive. * @param seed Seed for pseudo-random generation. * @return A random Graph with numV vertices and numE edges. */ public static Graph<Vertex, Edge> getGraph( final int numV, final int minW, final int maxW, final long seed) { final Random r = new Random(seed); Factory<Graph<Vertex,Edge>> gFact = new Factory<Graph<Vertex,Edge>>() { @Override public Graph<Vertex, Edge> create() { return new SparseGraph<Vertex, Edge>(); } }; ArrayList<Vertex> verts = GraphGen.genVerts( numV); final Iterator<Vertex> vIter = verts.iterator(); Factory<Vertex> vFact = new Factory<Vertex>() { @Override public Vertex create() { return vIter.next(); } }; Factory<Edge> eFact = new Factory<Edge>() { @Override public Edge create() { return new Edge( r.nextInt(maxW - minW) + minW); } }; Set<Vertex> vSeed = new HashSet(verts); Graph<Vertex, Edge> g = MixedRandomGraphGenerator.<Vertex,Edge>generateMixedRandomGraph(gFact, vFact, eFact, new HashMap<Edge,Number>(), numV, false, vSeed); for(Edge e : g.getEdges()) { Pair<Vertex> pair = g.getEndpoints(e); g.removeEdge(e); g.addEdge(e, pair,EdgeType.DIRECTED); } return g; } /** * Loads a Graph from a .csv file representing an adjacency matrix with no labels. * @param file Relative filepath of the input Graph. * @return The Graph represented in the file. * @throws FileNotFoundException File Not Found */ public static Graph<Vertex, Edge> getGraph( String file) throws FileNotFoundException { - Scanner scan = new Scanner(new FileReader(file)).useDelimiter("\\s"); + Scanner scan = new Scanner(new FileReader(file)).useDelimiter("\\n"); String first = scan.next().trim(); String[] fArray = first.split(","); int numV = fArray.length; int[][] mat = new int[numV][numV]; for(int j = 0; j < numV; j++) { mat[0][j] = Integer.parseInt(fArray[j]); } for(int i = 1; i < numV; i++) { String[] raw = null; try{ raw = scan.next().trim().split(","); } catch( NoSuchElementException e) { System.out.println("File \"" + file + "\" malformed: row/column length mismatch"); return null; } for(int j = 0; j < numV; j++) { try{ mat[i][j] = Integer.parseInt(raw[j]); } catch( NumberFormatException e) { mat[i][j] = -1; //just ignore an invalid edge } } } ArrayList<Vertex> verts = genVerts(numV); Graph<Vertex, Edge> g = new DirectedSparseGraph<Vertex, Edge>(); for(Vertex v : verts) { g.addVertex(v); } for(int i = 0; i < numV; i++) { for(int j = 0; j < numV; j++) { int weight = mat[i][j]; if( weight > 0 && i != j) //no costless, negative cost, or loop edges { g.addEdge(new Edge(weight), verts.get(i), verts.get(j)); } } } return g; } private static ArrayList<Vertex> genVerts( int numV) { ArrayList<Vertex> ret = new ArrayList<Vertex>(numV); for(int i = 0; i < numV; i++) { String name = ""; for(int repeat = 0; repeat <= i / 26; repeat++) { name += String.valueOf((char) ((i % 26) + 97)); } ret.add(new Vertex(name)); } return ret; } }
true
true
public static Graph<Vertex, Edge> getGraph( String file) throws FileNotFoundException { Scanner scan = new Scanner(new FileReader(file)).useDelimiter("\\s"); String first = scan.next().trim(); String[] fArray = first.split(","); int numV = fArray.length; int[][] mat = new int[numV][numV]; for(int j = 0; j < numV; j++) { mat[0][j] = Integer.parseInt(fArray[j]); } for(int i = 1; i < numV; i++) { String[] raw = null; try{ raw = scan.next().trim().split(","); } catch( NoSuchElementException e) { System.out.println("File \"" + file + "\" malformed: row/column length mismatch"); return null; } for(int j = 0; j < numV; j++) { try{ mat[i][j] = Integer.parseInt(raw[j]); } catch( NumberFormatException e) { mat[i][j] = -1; //just ignore an invalid edge } } } ArrayList<Vertex> verts = genVerts(numV); Graph<Vertex, Edge> g = new DirectedSparseGraph<Vertex, Edge>(); for(Vertex v : verts) { g.addVertex(v); } for(int i = 0; i < numV; i++) { for(int j = 0; j < numV; j++) { int weight = mat[i][j]; if( weight > 0 && i != j) //no costless, negative cost, or loop edges { g.addEdge(new Edge(weight), verts.get(i), verts.get(j)); } } } return g; }
public static Graph<Vertex, Edge> getGraph( String file) throws FileNotFoundException { Scanner scan = new Scanner(new FileReader(file)).useDelimiter("\\n"); String first = scan.next().trim(); String[] fArray = first.split(","); int numV = fArray.length; int[][] mat = new int[numV][numV]; for(int j = 0; j < numV; j++) { mat[0][j] = Integer.parseInt(fArray[j]); } for(int i = 1; i < numV; i++) { String[] raw = null; try{ raw = scan.next().trim().split(","); } catch( NoSuchElementException e) { System.out.println("File \"" + file + "\" malformed: row/column length mismatch"); return null; } for(int j = 0; j < numV; j++) { try{ mat[i][j] = Integer.parseInt(raw[j]); } catch( NumberFormatException e) { mat[i][j] = -1; //just ignore an invalid edge } } } ArrayList<Vertex> verts = genVerts(numV); Graph<Vertex, Edge> g = new DirectedSparseGraph<Vertex, Edge>(); for(Vertex v : verts) { g.addVertex(v); } for(int i = 0; i < numV; i++) { for(int j = 0; j < numV; j++) { int weight = mat[i][j]; if( weight > 0 && i != j) //no costless, negative cost, or loop edges { g.addEdge(new Edge(weight), verts.get(i), verts.get(j)); } } } return g; }
diff --git a/shared/root/java/result_pane/com/deepsky/view/query_pane/grid/EditableGrid.java b/shared/root/java/result_pane/com/deepsky/view/query_pane/grid/EditableGrid.java index 287be23..3ef91cd 100644 --- a/shared/root/java/result_pane/com/deepsky/view/query_pane/grid/EditableGrid.java +++ b/shared/root/java/result_pane/com/deepsky/view/query_pane/grid/EditableGrid.java @@ -1,530 +1,534 @@ /* * Copyright (c) 2009,2010 Serhiy Kulyk * 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. * * SQL CODE ASSISTANT PLUG-IN FOR INTELLIJ IDEA IS PROVIDED BY SERHIY KULYK * "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 SERHIY KULYK 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.deepsky.view.query_pane.grid; import com.deepsky.database.DBException; import com.deepsky.database.exec.UpdatableRecordCache; import com.deepsky.database.ora.types.LONGRAWType; import com.deepsky.database.ora.types.RAWType; import com.deepsky.lang.common.PluginKeys; import com.deepsky.settings.SqlCodeAssistantSettings; import com.deepsky.view.query_pane.*; import com.deepsky.view.query_pane.converters.ConversionUtil; import com.deepsky.view.query_pane.converters.RAWType_Convertor; import com.deepsky.view.query_pane.grid.editors.*; import com.deepsky.view.query_pane.grid.renders.*; import com.deepsky.view.query_pane.ui.BinaryEditorDialog; import com.deepsky.view.query_pane.ui.TextEditorDialog; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import oracle.sql.*; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import java.awt.*; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.sql.SQLException; import java.sql.Timestamp; public class EditableGrid extends AbstractDataGrid { UpdatableRecordCache rowset; int lastEditRow = -1; public EditableGrid(final Project project, TableModel model, final UpdatableRecordCache rowset) { super(project, model, rowset); this.rowset = rowset; getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (lastEditRow != -1 && lastEditRow != EditableGrid.this.getSelectedRow()) { // commit changes try { int cnt = rowset.getColumnCount(); for (int i = 0; i < cnt; i++) { Object o = rowset.getValueAt(lastEditRow, i + 1); if (o == null && rowset.isColumnNotNull(i + 1) && rowset.isColumnEditable(i + 1)) { // final int columnIndex = i + 1; SwingUtilities.invokeLater(new Runnable() { final Object k = new Object(); public void run() { try { synchronized (k) { k.wait(400); } EditableGrid.this.setRowSelectionInterval(lastEditRow, lastEditRow); EditableGrid.this.editCellAt(lastEditRow, columnIndex); } catch (InterruptedException e) { e.printStackTrace(); } } }); // skip row saving return; } } //todo -- experimental rowset.completeUpdate(); } catch (DBException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } }); SqlCodeAssistantSettings settings = PluginKeys.PLUGIN_SETTINGS.getData(project); Font font = settings.getGridFont(); // create column renderers setDefaultRenderer(Color.class, new ColumnNumberRenderer(true)); setDefaultRenderer(BigDecimal.class, new NumberRenderer(font)); setDefaultRenderer(String.class, new TextRenderer(font)); setDefaultRenderer(ROWID.class, new ROWIDRenderer(font)); // _table.setDefaultRenderer(java.sql.Time.class, new DateRenderer()); setDefaultRenderer(RAWType.class, new RAWTypeRenderer(font)); setDefaultRenderer(LONGRAWType.class, new LONGRAWTypeRenderer(font)); setDefaultRenderer(CLOB.class, new CLOBTypeRenderer()); setDefaultRenderer(BLOB.class, new BLOBTypeRenderer()); setDefaultRenderer(BFILE.class, new BFILETypeRenderer()); setDefaultRenderer(TIMESTAMP.class, new TimestampRenderer(font, PluginKeys.TS_CONVERTOR.getData(project))); setDefaultRenderer(TIMESTAMPLTZ.class, new TimestampRenderer(font, PluginKeys.TS_CONVERTOR.getData(project))); setDefaultRenderer(TIMESTAMPTZ.class, new TimestampRenderer(font, PluginKeys.TSTZ_CONVERTOR.getData(project))); DateRenderer dateRenderer = new DateRenderer(font) { public String getFormat() { return getDateTimeFormat(); } }; setDefaultRenderer(java.util.Date.class, dateRenderer); setDefaultRenderer(java.sql.Date.class, dateRenderer); setDefaultRenderer(Timestamp.class, dateRenderer); // create column editors TextCellEditor textEditor = new TextCellEditor(font); textEditor.addActionListener(new TextCellEditorListener() { public void invokeExternalEditor(DataAccessor accessor) { openColumnValueEditor(accessor); } }); RawCellEditor rawEditor = new RawCellEditor<RAWType>(font, new RAWType_Convertor()); rawEditor.addActionListener(new TextCellEditorListener() { public void invokeExternalEditor(DataAccessor accessor) { openColumnValueEditor(accessor); } }); setDefaultEditor(BigDecimal.class, new NumberCellEditor(font)); setDefaultEditor(String.class, textEditor); setDefaultEditor(RAWType.class, rawEditor); setDefaultEditor(LONGRAWType.class, rawEditor); setDefaultEditor(java.sql.Timestamp.class, new TimestampCellEditor(settings)); setDefaultEditor(java.sql.Date.class, new DateCellEditor(settings)); setDefaultEditor(TIMESTAMP.class, new OracleTimestampCellEditor(font, PluginKeys.TS_CONVERTOR.getData(project))); setDefaultEditor(TIMESTAMPTZ.class, new OracleTimestampCellEditor(font, PluginKeys.TSTZ_CONVERTOR.getData(project))); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setRowSelectionAllowed(true); setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); setSurrendersFocusOnKeystroke(true); } public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { // double click, open Editor dialog if column is BLOB/CLOB/BFILE int columnIndex = getSelectedColumn(); int rowIndex = getSelectedRow(); Class columnClazz = getModel().getColumnClass(columnIndex); if(columnClazz.isAssignableFrom(BLOB.class)){ DataAccessor accessor = createAccessor(columnIndex, rowIndex); openColumnValueEditor(accessor); } else if(columnClazz.isAssignableFrom(CLOB.class)){ DataAccessor accessor = createAccessor(columnIndex, rowIndex); openColumnValueEditor(accessor); } else if(columnClazz.isAssignableFrom(BFILE.class)){ openColumnValueViewer(columnClazz, columnIndex); } else { // open for other cases if the cell is readOnly if(!getModel().isCellEditable(rowIndex, columnIndex)){ openColumnValueViewer(columnClazz, columnIndex); } } } } private DataAccessor createAccessor(final int columnIndex, final int rowIndex){ Class columnClazz = getModel().getColumnClass(columnIndex); boolean isEditable = getModel().isCellEditable(rowIndex, columnIndex); Object value = getValueAt(rowIndex, columnIndex); if(columnClazz.isAssignableFrom(BFILE.class)){ // BFILE is read only return DataAccessorFactory.createReadOnly(project, columnClazz, value); } else if(isEditable){ // editable column value DataAccessor accessor = DataAccessorFactory.createReadOnly(project, columnClazz, value); if(columnClazz.isAssignableFrom(BLOB.class)){ return new DataAccessorWrapper<BLOB>(accessor){ public void loadFromString(String text) throws ConversionException { BLOB blob = getValue(); try { if(blob == null || !blob.isTemporary()){ blob = BLOB.createTemporary(rowset.getConnection(), true, BLOB.DURATION_SESSION); } OutputStream out = blob.setBinaryStream(1); byte[] array = ConversionUtil.convertHEXString2ByteArray(text); out.write(array); out.close(); setValueAt(blob, rowIndex, columnIndex); } catch (SQLException e) { // todo -- do appropriate handling e.printStackTrace(); } catch (IOException e) { // todo -- do appropriate handling e.printStackTrace(); } } public boolean isReadOnly(){ return false; } }; } else if(columnClazz.isAssignableFrom(CLOB.class)){ return new DataAccessorWrapper<CLOB>(accessor){ public void loadFromString(String text) throws ConversionException { CLOB clob = getValue(); try { if(clob == null || !clob.isTemporary()){ clob = CLOB.createTemporary(rowset.getConnection(), true, CLOB.DURATION_SESSION); } OutputStream out = clob.setAsciiStream(1); out.write(text.getBytes()); out.close(); setValueAt(clob, rowIndex, columnIndex); } catch (SQLException e) { // todo -- do appropriate handling e.printStackTrace(); } catch (IOException e) { // todo -- do appropriate handling e.printStackTrace(); } } public boolean isReadOnly(){ return false; } }; } else { // todo -- make accessor ReadWrite return accessor; } } else { // read only column value return DataAccessorFactory.createReadOnly(project, columnClazz, value); } } private class DataAccessorWrapper<E> extends DataAccessor<E> { protected DataAccessor<E> delegate; public DataAccessorWrapper(DataAccessor<E> delegate){ this.delegate = delegate; } public long size() throws SQLException{ return delegate.size(); } public String convertToString() throws SQLException{ return delegate.convertToString(); } public void loadFromString(String text) throws ConversionException { delegate.loadFromString(text); } public void saveValueTo(File file) throws IOException { delegate.saveValueTo(file); } public boolean isReadOnly(){ return delegate.isReadOnly(); } public E getValue(){ return delegate.getValue(); } } private void openColumnValueViewer(Class columnClazz, int columnIndex) { int rowIndex = getSelectedRow(); Object value = getValueAt(rowIndex, columnIndex); DataAccessor accessor = DataAccessorFactory.createReadOnly(project, columnClazz, value); if(accessor != null){ String columnName = getColumnName(columnIndex); try { DialogWrapper dialog = buildDialog(project, columnClazz, columnName, accessor); dialog.show(); } catch (ColumnReadException e) { // todo - log exception } } } private void openColumnValueEditor(DataAccessor accessor){ int columnIndex = getSelectedColumn(); String columnName = getColumnName(columnIndex); Class columnClazz = getModel().getColumnClass(columnIndex); try { DialogWrapper dialog = buildDialog(project, columnClazz, columnName, accessor); dialog.show(); } catch (ColumnReadException e) { // todo - log exception } finally { Component eComponent = getEditorComponent(); if(eComponent != null){ TableCellEditor editor = getDefaultEditor(columnClazz); if(editor != null){ editor.stopCellEditing(); } } } } private void updateModel(TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: { try { final int firstRow = e.getFirstRow(); rowset.deleteRows(firstRow, e.getLastRow()); if (rowset.getFetchedRowCount() > 0) {//= firstRow) { SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow - 1; if (EditableGrid.this.getModel().getRowCount() <= position) { position--; } EditableGrid.this.setRowSelectionInterval(position, position); } }); } } catch (DBException e1) { e1.printStackTrace(); } break; } case TableModelEvent.INSERT: { final int firstRow = e.getFirstRow(); try { rowset.addRow(firstRow); lastEditRow = firstRow; SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow;// - 1; EditableGrid.this.setRowSelectionInterval(position, position); } }); } catch (DBException e1) { - e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + e1.printStackTrace(); } break; } case TableModelEvent.UPDATE: { int _1st = e.getFirstRow(); int _last = e.getLastRow(); lastEditRow = _1st; } } } /** * Submit row editing if any */ public void submitUpdate() throws DBException { final int lastEditRow1 = EditableGrid.this.getSelectedRow(); TableCellEditor cellEditor = EditableGrid.this.getCellEditor(); if(cellEditor != null){ - cellEditor.stopCellEditing(); + if(cellEditor.stopCellEditing()!=true){ + // cell editor failed, abort submitting changes + Messages.showWarningDialog(" Entered value is not valid ", "Cannot save changes"); + return; + } } // check cells on NOT NULL constraints int cnt = rowset.getColumnCount(); for (int i = 0; i < cnt; i++) { final int columnIndex = i + 1; Object o = rowset.getValueAt(lastEditRow1, columnIndex); if (o == null && rowset.isColumnNotNull(columnIndex) && rowset.isColumnEditable(columnIndex)) { // SwingUtilities.invokeLater(new Runnable() { final Object k = new Object(); public void run() { try { synchronized (k) { k.wait(400); } EditableGrid.this.setRowSelectionInterval(lastEditRow1, lastEditRow1); EditableGrid.this.editCellAt(lastEditRow1, columnIndex); } catch (InterruptedException e) { e.printStackTrace(); } } }); // skip row saving return; } } rowset.completeUpdate(); fireTableRowsUpdated1(lastEditRow1, lastEditRow1); // todo -- is lastEditRow really needed? lastEditRow = -1; } @Override public boolean changesNotPosted() { return rowset.changesNotPosted(); } @Override public boolean isFirst() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isLast() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void prev() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void next() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void first() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void last() { //To change body of implemented methods use File | Settings | File Templates. } /** * Insert new row before selected row */ public void insertRow() { int selectedRow = EditableGrid.this.getSelectedRow(); selectedRow = (selectedRow!=-1)? selectedRow: 0; fireTableRowsInserted1(selectedRow, selectedRow); } /** * Delete currently selected row */ public void deleteRow() { int[] selectedRows = EditableGrid.this.getSelectedRows(); if(selectedRows.length == 0){ Messages.showWarningDialog(" Rows being deleted are not selected ", "Cannot delete records"); return; } fireTableRowsDeleted1(selectedRows[0] + 1, selectedRows[selectedRows.length - 1] + 1); } private void fireTableRowsUpdated1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE); this.tableChanged(e); updateModel(e); } private void fireTableRowsDeleted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE); this.tableChanged(e); updateModel(e); } private void fireTableRowsInserted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT); this.tableChanged(e); updateModel(e); } public static DialogWrapper buildDialog( @NotNull Project project, @NotNull Class columnClazz, String columnName, DataAccessor accessor) throws ColumnReadException { try { if(columnClazz.isAssignableFrom(RAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(LONGRAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(BLOB.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else { return new TextEditorDialog(project, columnName, accessor); } } catch (SQLException e) { // todo -- save in the log e.printStackTrace(); } throw new ColumnReadException("Editor for class " + columnClazz + " not found"); } }
false
true
private void updateModel(TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: { try { final int firstRow = e.getFirstRow(); rowset.deleteRows(firstRow, e.getLastRow()); if (rowset.getFetchedRowCount() > 0) {//= firstRow) { SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow - 1; if (EditableGrid.this.getModel().getRowCount() <= position) { position--; } EditableGrid.this.setRowSelectionInterval(position, position); } }); } } catch (DBException e1) { e1.printStackTrace(); } break; } case TableModelEvent.INSERT: { final int firstRow = e.getFirstRow(); try { rowset.addRow(firstRow); lastEditRow = firstRow; SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow;// - 1; EditableGrid.this.setRowSelectionInterval(position, position); } }); } catch (DBException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } break; } case TableModelEvent.UPDATE: { int _1st = e.getFirstRow(); int _last = e.getLastRow(); lastEditRow = _1st; } } } /** * Submit row editing if any */ public void submitUpdate() throws DBException { final int lastEditRow1 = EditableGrid.this.getSelectedRow(); TableCellEditor cellEditor = EditableGrid.this.getCellEditor(); if(cellEditor != null){ cellEditor.stopCellEditing(); } // check cells on NOT NULL constraints int cnt = rowset.getColumnCount(); for (int i = 0; i < cnt; i++) { final int columnIndex = i + 1; Object o = rowset.getValueAt(lastEditRow1, columnIndex); if (o == null && rowset.isColumnNotNull(columnIndex) && rowset.isColumnEditable(columnIndex)) { // SwingUtilities.invokeLater(new Runnable() { final Object k = new Object(); public void run() { try { synchronized (k) { k.wait(400); } EditableGrid.this.setRowSelectionInterval(lastEditRow1, lastEditRow1); EditableGrid.this.editCellAt(lastEditRow1, columnIndex); } catch (InterruptedException e) { e.printStackTrace(); } } }); // skip row saving return; } } rowset.completeUpdate(); fireTableRowsUpdated1(lastEditRow1, lastEditRow1); // todo -- is lastEditRow really needed? lastEditRow = -1; } @Override public boolean changesNotPosted() { return rowset.changesNotPosted(); } @Override public boolean isFirst() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isLast() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void prev() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void next() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void first() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void last() { //To change body of implemented methods use File | Settings | File Templates. } /** * Insert new row before selected row */ public void insertRow() { int selectedRow = EditableGrid.this.getSelectedRow(); selectedRow = (selectedRow!=-1)? selectedRow: 0; fireTableRowsInserted1(selectedRow, selectedRow); } /** * Delete currently selected row */ public void deleteRow() { int[] selectedRows = EditableGrid.this.getSelectedRows(); if(selectedRows.length == 0){ Messages.showWarningDialog(" Rows being deleted are not selected ", "Cannot delete records"); return; } fireTableRowsDeleted1(selectedRows[0] + 1, selectedRows[selectedRows.length - 1] + 1); } private void fireTableRowsUpdated1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE); this.tableChanged(e); updateModel(e); } private void fireTableRowsDeleted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE); this.tableChanged(e); updateModel(e); } private void fireTableRowsInserted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT); this.tableChanged(e); updateModel(e); } public static DialogWrapper buildDialog( @NotNull Project project, @NotNull Class columnClazz, String columnName, DataAccessor accessor) throws ColumnReadException { try { if(columnClazz.isAssignableFrom(RAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(LONGRAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(BLOB.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else { return new TextEditorDialog(project, columnName, accessor); } } catch (SQLException e) { // todo -- save in the log e.printStackTrace(); } throw new ColumnReadException("Editor for class " + columnClazz + " not found"); } }
private void updateModel(TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: { try { final int firstRow = e.getFirstRow(); rowset.deleteRows(firstRow, e.getLastRow()); if (rowset.getFetchedRowCount() > 0) {//= firstRow) { SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow - 1; if (EditableGrid.this.getModel().getRowCount() <= position) { position--; } EditableGrid.this.setRowSelectionInterval(position, position); } }); } } catch (DBException e1) { e1.printStackTrace(); } break; } case TableModelEvent.INSERT: { final int firstRow = e.getFirstRow(); try { rowset.addRow(firstRow); lastEditRow = firstRow; SwingUtilities.invokeLater(new Runnable() { public void run() { int position = firstRow;// - 1; EditableGrid.this.setRowSelectionInterval(position, position); } }); } catch (DBException e1) { e1.printStackTrace(); } break; } case TableModelEvent.UPDATE: { int _1st = e.getFirstRow(); int _last = e.getLastRow(); lastEditRow = _1st; } } } /** * Submit row editing if any */ public void submitUpdate() throws DBException { final int lastEditRow1 = EditableGrid.this.getSelectedRow(); TableCellEditor cellEditor = EditableGrid.this.getCellEditor(); if(cellEditor != null){ if(cellEditor.stopCellEditing()!=true){ // cell editor failed, abort submitting changes Messages.showWarningDialog(" Entered value is not valid ", "Cannot save changes"); return; } } // check cells on NOT NULL constraints int cnt = rowset.getColumnCount(); for (int i = 0; i < cnt; i++) { final int columnIndex = i + 1; Object o = rowset.getValueAt(lastEditRow1, columnIndex); if (o == null && rowset.isColumnNotNull(columnIndex) && rowset.isColumnEditable(columnIndex)) { // SwingUtilities.invokeLater(new Runnable() { final Object k = new Object(); public void run() { try { synchronized (k) { k.wait(400); } EditableGrid.this.setRowSelectionInterval(lastEditRow1, lastEditRow1); EditableGrid.this.editCellAt(lastEditRow1, columnIndex); } catch (InterruptedException e) { e.printStackTrace(); } } }); // skip row saving return; } } rowset.completeUpdate(); fireTableRowsUpdated1(lastEditRow1, lastEditRow1); // todo -- is lastEditRow really needed? lastEditRow = -1; } @Override public boolean changesNotPosted() { return rowset.changesNotPosted(); } @Override public boolean isFirst() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isLast() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void prev() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void next() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void first() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void last() { //To change body of implemented methods use File | Settings | File Templates. } /** * Insert new row before selected row */ public void insertRow() { int selectedRow = EditableGrid.this.getSelectedRow(); selectedRow = (selectedRow!=-1)? selectedRow: 0; fireTableRowsInserted1(selectedRow, selectedRow); } /** * Delete currently selected row */ public void deleteRow() { int[] selectedRows = EditableGrid.this.getSelectedRows(); if(selectedRows.length == 0){ Messages.showWarningDialog(" Rows being deleted are not selected ", "Cannot delete records"); return; } fireTableRowsDeleted1(selectedRows[0] + 1, selectedRows[selectedRows.length - 1] + 1); } private void fireTableRowsUpdated1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE); this.tableChanged(e); updateModel(e); } private void fireTableRowsDeleted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE); this.tableChanged(e); updateModel(e); } private void fireTableRowsInserted1(int firstRow, int lastRow) { TableModel tableModel = EditableGrid.this.getModel(); TableModelEvent e = new TableModelEvent(tableModel, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT); this.tableChanged(e); updateModel(e); } public static DialogWrapper buildDialog( @NotNull Project project, @NotNull Class columnClazz, String columnName, DataAccessor accessor) throws ColumnReadException { try { if(columnClazz.isAssignableFrom(RAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(LONGRAWType.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else if(columnClazz.isAssignableFrom(BLOB.class)){ return new BinaryEditorDialog(project, columnName, accessor); } else { return new TextEditorDialog(project, columnName, accessor); } } catch (SQLException e) { // todo -- save in the log e.printStackTrace(); } throw new ColumnReadException("Editor for class " + columnClazz + " not found"); } }
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java index d9cc126f..8719298a 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java @@ -1,4068 +1,4068 @@ package com.redhat.ceylon.compiler.js; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisWarning; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.ImportableScope; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.InterfaceAlias; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.Specification; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.*; import com.redhat.ceylon.compiler.typechecker.tree.Tree.*; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Stack<Continuation> continues = new Stack<Continuation>(); private final EnclosingFunctionVisitor encloser = new EnclosingFunctionVisitor(); private final JsIdentifierNames names; private final Set<Declaration> directAccess = new HashSet<Declaration>(); private final RetainedVars retainedVars = new RetainedVars(); final ConditionGenerator conds; private final InvocationGenerator invoker; private final List<CommonToken> tokens; private int dynblock; private final class SuperVisitor extends Visitor { private final List<Declaration> decs; private SuperVisitor(List<Declaration> decs) { this.decs = decs; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { Term primary = eliminateParensAndWidening(qe.getPrimary()); if (primary instanceof Super) { decs.add(qe.getDeclaration()); } super.visit(qe); } @Override public void visit(QualifiedType that) { if (that.getOuterType() instanceof SuperType) { decs.add(that.getDeclarationModel()); } super.visit(that); } public void visit(Tree.ClassOrInterface qe) { //don't recurse if (qe instanceof ClassDefinition) { ExtendedType extType = ((ClassDefinition) qe).getExtendedType(); if (extType != null) { super.visit(extType); } } } } private final class OuterVisitor extends Visitor { boolean found = false; private Declaration dec; private OuterVisitor(Declaration dec) { this.dec = dec; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { if (qe.getPrimary() instanceof Outer || qe.getPrimary() instanceof This) { if ( qe.getDeclaration().equals(dec) ) { found = true; } } super.visit(qe); } } private List<? extends Statement> currentStatements = null; private final TypeUtils types; private Writer out; private final Writer originalOut; final Options opts; private CompilationUnit root; private static String clAlias=""; private static final String function="function "; private boolean needIndent = true; private int indentLevel = 0; Package getCurrentPackage() { return root.getUnit().getPackage(); } private static void setCLAlias(String alias) { clAlias = alias + "."; } /** Returns the module name for the language module. */ static String getClAlias() { return clAlias; } @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } private final JsOutput jsout; public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names, List<CommonToken> tokens, TypeUtils typeUtils) throws IOException { this.jsout = out; this.opts = options; this.out = out.getWriter(); originalOut = out.getWriter(); this.names = names; conds = new ConditionGenerator(this, names, directAccess); this.tokens = tokens; types = typeUtils; invoker = new InvocationGenerator(this, names, retainedVars); } TypeUtils getTypeUtils() { return types; } InvocationGenerator getInvoker() { return invoker; } /** Returns the helper component to handle naming. */ JsIdentifierNames getNames() { return names; } private static interface GenerateCallback { public void generateValue(); } /** Print generated code to the Writer specified at creation time. * Automatically prints indentation first if necessary. * @param code The main code * @param codez Optional additional strings to print after the main code. */ void out(String code, String... codez) { try { if (opts.isIndent() && needIndent) { for (int i=0;i<indentLevel;i++) { out.write(" "); } } needIndent = false; out.write(code); for (String s : codez) { out.write(s); } if (opts.isVerbose() && out == originalOut) { //Print code to console (when printing to REAL output) System.out.print(code); for (String s : codez) { System.out.print(s); } } } catch (IOException ioe) { throw new RuntimeException("Generating JS code", ioe); } } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. */ void endLine() { endLine(false); } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. * @param semicolon if <code>true</code> then a semicolon is printed at the end * of the previous line*/ void endLine(boolean semicolon) { if (semicolon) { out(";"); } out("\n"); needIndent = true; } /** Calls {@link #endLine()} if the current position is not already the beginning * of a line. */ void beginNewLine() { if (!needIndent) { endLine(); } } /** Increases indentation level, prints opening brace and newline. Indentation will * automatically be printed by {@link #out(String, String...)} when the next line is started. */ void beginBlock() { indentLevel++; out("{"); endLine(); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. */ void endBlockNewLine() { endBlock(false, true); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. * @param semicolon if <code>true</code> then prints a semicolon after the brace*/ void endBlockNewLine(boolean semicolon) { endBlock(semicolon, true); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). */ void endBlock() { endBlock(false, false); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). * @param semicolon if <code>true</code> then prints a semicolon after the brace * @param newline if <code>true</code> then additionally calls {@link #endLine()} */ void endBlock(boolean semicolon, boolean newline) { indentLevel--; beginNewLine(); out(semicolon ? "};" : "}"); if (newline) { endLine(); } } /** Prints source code location in the form "at [filename] ([location])" */ void location(Node node) { out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")"); } private String generateToString(final GenerateCallback callback) { final Writer oldWriter = out; out = new StringWriter(); callback.generateValue(); final String str = out.toString(); out = oldWriter; return str; } @Override public void visit(CompilationUnit that) { root = that; Module clm = that.getUnit().getPackage().getModule() .getLanguageModule(); if (!JsCompiler.compilingLanguageModule) { require(clm); setCLAlias(names.moduleAlias(clm)); } for (CompilerAnnotation ca: that.getCompilerAnnotations()) { ca.visit(this); } if (that.getImportList() != null) { that.getImportList().visit(this); } visitStatements(that.getDeclarations()); } public void visit(Import that) { ImportableScope scope = that.getImportMemberOrTypeList().getImportList().getImportedScope(); if (scope instanceof Package) { require(((Package) scope).getModule()); } } private void require(Module mod) { final String path = scriptPath(mod); final String modAlias = names.moduleAlias(mod); if (jsout.requires.put(path, modAlias) == null) { out("var ", modAlias, "=require('", path, "');"); endLine(); } } private String scriptPath(Module mod) { StringBuilder path = new StringBuilder(mod.getNameAsString().replace('.', '/')).append('/'); if (!mod.isDefault()) { path.append(mod.getVersion()).append('/'); } path.append(mod.getNameAsString()); if (!mod.isDefault()) { path.append('-').append(mod.getVersion()); } return path.toString(); } @Override public void visit(Parameter that) { out(names.name(that.getDeclarationModel())); } @Override public void visit(ParameterList that) { out("("); boolean first=true; boolean ptypes = false; //Check if this is the first parameter list if (that.getScope() instanceof Method && that.getModel().isFirst()) { ptypes = ((Method)that.getScope()).getTypeParameters() != null && !((Method)that.getScope()).getTypeParameters().isEmpty(); } for (Parameter param: that.getParameters()) { if (!first) out(","); out(names.name(param.getDeclarationModel())); first = false; } if (ptypes) { if (!first) out(","); out("$$$mptypes"); } out(")"); } private void visitStatements(List<? extends Statement> statements) { List<String> oldRetainedVars = retainedVars.reset(null); final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; for (int i=0; i<statements.size(); i++) { Statement s = statements.get(i); s.visit(this); beginNewLine(); retainedVars.emitRetainedVars(this); } retainedVars.reset(oldRetainedVars); currentStatements = prevStatements; } @Override public void visit(Body that) { visitStatements(that.getStatements()); } @Override public void visit(Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); } else { beginBlock(); initSelf(that); visitStatements(stmnts); endBlock(); } } private void initSelf(Block block) { initSelf(block.getScope()); } private void initSelf(Scope scope) { if ((prototypeOwner != null) && ((scope instanceof MethodOrValue) || (scope instanceof TypeDeclaration) || (scope instanceof Specification))) { out("var "); self(prototypeOwner); out("=this;"); endLine(); } } private void comment(Tree.Declaration that) { if (!opts.isComment()) return; endLine(); out("//", that.getNodeType(), " ", that.getDeclarationModel().getName()); location(that); endLine(); } private void var(Declaration d) { out("var ", names.name(d), "="); } private boolean share(Declaration d) { return share(d, true); } private boolean share(Declaration d, boolean excludeProtoMembers) { boolean shared = false; if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember()) && isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.name(d), "=", names.name(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(ClassDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) { //But warnings are ok for (Message err : that.getErrors()) { if (!(err instanceof AnalysisWarning)) { return; } } } Class d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; comment(that); Tree.ClassSpecifier ext = that.getClassSpecifier(); out(function, names.name(d), "("); //Generate each parameter because we need to append one at the end for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } TypeArgumentList targs = ext.getType().getTypeArgumentList(); if (targs != null && !targs.getTypes().isEmpty()) { out("$$targs$$,"); } self(d); out(")"); TypeDeclaration aliased = ext.getType().getDeclarationModel(); out("{return "); qualify(ext.getType(), aliased); out(names.name(aliased), "("); if (ext.getInvocationExpression().getPositionalArgumentList() != null) { ext.getInvocationExpression().getPositionalArgumentList().visit(this); if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) { out(","); } } else { out("/*PENDIENTE NAMED ARG CLASS DECL */"); } if (targs != null && !targs.getTypes().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( aliased.getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(that, invargs, this); } else { out("/*TARGS != TPARAMS!!!! WTF?????*/"); } out(","); } self(d); out(");}"); endLine(); out(names.name(d), ".$$="); qualify(ext, aliased); out(names.name(aliased), ".$$;"); endLine(); share(d); } private void addClassDeclarationToPrototype(TypeDeclaration outer, ClassDeclaration that) { comment(that); TypeDeclaration dec = that.getClassSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } @Override public void visit(InterfaceDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Interface d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; //It's pointless declaring interface aliases outside of classes/interfaces Scope scope = that.getScope(); if (scope instanceof InterfaceAlias) { scope = scope.getContainer(); if (!(scope instanceof ClassOrInterface)) return; } comment(that); var(d); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel() .getDeclaration(); qualify(that,dec); out(names.name(dec), ";"); endLine(); share(d); } private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, InterfaceDeclaration that) { comment(that); TypeDeclaration dec = that.getTypeSpecifier().getType().getTypeModel().getDeclaration(); String path = qualifiedPath(that, dec, true); if (path.length() > 0) { path += '.'; } out(names.self(outer), ".", names.name(that.getDeclarationModel()), "=", path, names.name(dec), ";"); endLine(); } private void addInterfaceToPrototype(ClassOrInterface type, InterfaceDefinition interfaceDef) { interfaceDefinition(interfaceDef); Interface d = interfaceDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(InterfaceDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { interfaceDefinition(that); } } private void interfaceDefinition(InterfaceDefinition that) { Interface d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); self(d); out(")"); beginBlock(); //declareSelf(d); referenceOuter(d); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getInterfaceBody()); } callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); that.getInterfaceBody().visit(this); //returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void addClassToPrototype(ClassOrInterface type, ClassDefinition classDef) { classDefinition(classDef); Class d = classDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d), ";"); endLine(); } @Override public void visit(ClassDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { classDefinition(that); } } private void classDefinition(ClassDefinition that) { Class d = that.getDeclarationModel(); comment(that); out(function, names.name(d), "("); for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } boolean withTargs = that.getTypeParameterList() != null && !that.getTypeParameterList().getTypeParameterDeclarations().isEmpty(); if (withTargs) { out("$$targs$$,"); } self(d); out(")"); beginBlock(); //This takes care of top-level attributes defined before the class definition out("$init$", names.name(d), "();"); endLine(); declareSelf(d); if (withTargs) { out(clAlias, "set_type_args("); self(d); out(",$$targs$$);"); endLine(); } else { //Check if any of the satisfied types have type arguments if (that.getSatisfiedTypes() != null) { for(Tree.StaticType sat : that.getSatisfiedTypes().getTypes()) { boolean first = true; Map<TypeParameter,ProducedType> targs = sat.getTypeModel().getTypeArguments(); if (targs != null && !targs.isEmpty()) { if (first) { self(d); out(".$$targs$$="); TypeUtils.printTypeArguments(that, targs, this); endLine(true); } else { out("/*TODO: more type arguments*/"); endLine(); } } } } } referenceOuter(d); initParameters(that.getParameterList(), d); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(that.getExtendedType(), d, that, superDecs); callInterfaces(that.getSatisfiedTypes(), d, that, superDecs); that.getClassBody().visit(this); returnSelf(d); endBlockNewLine(); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); share(d); typeInitialization(that); } private void referenceOuter(TypeDeclaration d) { if (d.isClassOrInterfaceMember()) { self(d); out("."); out("$$outer"); //outerSelf(d); out("=this;"); endLine(); } } private void copySuperMembers(TypeDeclaration typeDecl, final List<Declaration> decs, ClassOrInterface d) { if (!opts.isOptimize()) { for (Declaration dec: decs) { if (!typeDecl.isMember(dec)) { continue; } String suffix = names.scopeSuffix(dec.getContainer()); if (dec instanceof Value && ((Value)dec).isTransient()) { superGetterRef(dec,d,suffix); if (((Value) dec).isVariable()) { superSetterRef(dec,d,suffix); } } else { superRef(dec,d,suffix); } } } } private void callSuperclass(ExtendedType extendedType, Class d, Node that, final List<Declaration> superDecs) { if (extendedType!=null) { PositionalArgumentList argList = extendedType.getInvocationExpression() .getPositionalArgumentList(); TypeDeclaration typeDecl = extendedType.getType().getDeclarationModel(); out(memberAccessBase(extendedType.getType(), typeDecl, false, qualifiedPath(that, typeDecl)), (opts.isOptimize() && (getSuperMemberScope(extendedType.getType()) != null)) ? ".call(this," : "("); invoker.generatePositionalArguments(argList, argList.getPositionalArguments(), false, false); if (argList.getPositionalArguments().size() > 0) { out(","); } //There may be defaulted args we must pass as undefined if (d.getExtendedTypeDeclaration().getParameterList().getParameters().size() > argList.getPositionalArguments().size()) { List<com.redhat.ceylon.compiler.typechecker.model.Parameter> superParams = d.getExtendedTypeDeclaration().getParameterList().getParameters(); for (int i = argList.getPositionalArguments().size(); i < superParams.size(); i++) { com.redhat.ceylon.compiler.typechecker.model.Parameter p = superParams.get(i); if (p.isSequenced()) { out(clAlias, "getEmpty(),"); } else { out("undefined,"); } } } //If the supertype has type arguments, add them to the call if (typeDecl.getTypeParameters() != null && !typeDecl.getTypeParameters().isEmpty()) { extendedType.getType().getTypeArgumentList().getTypeModels(); TypeUtils.printTypeArguments(that, TypeUtils.matchTypeParametersWithArguments(typeDecl.getTypeParameters(), extendedType.getType().getTypeArgumentList().getTypeModels()), this); out(","); } self(d); out(");"); endLine(); copySuperMembers(typeDecl, superDecs, d); } } private void callInterfaces(SatisfiedTypes satisfiedTypes, ClassOrInterface d, Node that, final List<Declaration> superDecs) { if (satisfiedTypes!=null) { for (StaticType st: satisfiedTypes.getTypes()) { TypeDeclaration typeDecl = st.getTypeModel().getDeclaration(); if (typeDecl.isAlias()) { typeDecl = typeDecl.getExtendedTypeDeclaration(); } qualify(that, typeDecl); out(names.name((ClassOrInterface)typeDecl), "("); self(d); out(");"); endLine(); //Set the reified types from interfaces Map<TypeParameter, ProducedType> reifs = st.getTypeModel().getTypeArguments(); if (reifs != null && !reifs.isEmpty()) { for (Map.Entry<TypeParameter, ProducedType> e : reifs.entrySet()) { if (e.getValue().getDeclaration() instanceof ClassOrInterface) { out(clAlias, "add_type_arg("); self(d); out(",'", e.getKey().getName(), "',"); TypeUtils.typeNameOrList(that, e.getValue(), this, true); out(");"); endLine(); } } } copySuperMembers(typeDecl, superDecs, d); } } } /** Generates a function to initialize the specified type. */ private void typeInitialization(final Tree.Declaration type) { ExtendedType extendedType = null; SatisfiedTypes satisfiedTypes = null; boolean isInterface = false; ClassOrInterface decl = null; if (type instanceof ClassDefinition) { ClassDefinition classDef = (ClassDefinition) type; extendedType = classDef.getExtendedType(); satisfiedTypes = classDef.getSatisfiedTypes(); decl = classDef.getDeclarationModel(); } else if (type instanceof InterfaceDefinition) { satisfiedTypes = ((InterfaceDefinition) type).getSatisfiedTypes(); isInterface = true; decl = ((InterfaceDefinition) type).getDeclarationModel(); } else if (type instanceof ObjectDefinition) { ObjectDefinition objectDef = (ObjectDefinition) type; extendedType = objectDef.getExtendedType(); satisfiedTypes = objectDef.getSatisfiedTypes(); decl = (ClassOrInterface)objectDef.getDeclarationModel().getTypeDeclaration(); } final PrototypeInitCallback callback = new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { if (type instanceof ClassDefinition) { addToPrototype(((ClassDefinition)type).getDeclarationModel(), ((ClassDefinition)type).getClassBody().getStatements()); } else if (type instanceof InterfaceDefinition) { addToPrototype(((InterfaceDefinition)type).getDeclarationModel(), ((InterfaceDefinition)type).getInterfaceBody().getStatements()); } } }; typeInitialization(extendedType, satisfiedTypes, isInterface, decl, callback); } /** This is now the main method to generate the type initialization code. * @param extendedType The type that is being extended. * @param satisfiedTypes The types satisfied by the type being initialized. * @param isInterface Tells whether the type being initialized is an interface * @param d The declaration for the type being initialized * @param callback A callback to add something more to the type initializer in prototype style. */ private void typeInitialization(ExtendedType extendedType, SatisfiedTypes satisfiedTypes, boolean isInterface, final ClassOrInterface d, PrototypeInitCallback callback) { //Let's always use initTypeProto to avoid #113 String initFuncName = "initTypeProto"; out("function $init$", names.name(d), "()"); beginBlock(); out("if (", names.name(d), ".$$===undefined)"); beginBlock(); String qns = d.getQualifiedNameString(); if (JsCompiler.compilingLanguageModule && qns.indexOf("::") < 0) { //Language module files get compiled in default module //so they need to have this added to their qualified name qns = "ceylon.language::" + qns; } out(clAlias, initFuncName, "(", names.name(d), ",'", qns, "'"); if (extendedType != null) { String fname = typeFunctionName(extendedType.getType(), false); out(",", fname); } else if (!isInterface) { out(",", clAlias, "Basic"); } if (satisfiedTypes != null) { for (StaticType satType : satisfiedTypes.getTypes()) { TypeDeclaration tdec = satType.getTypeModel().getDeclaration(); if (tdec.isAlias()) { tdec = tdec.getExtendedTypeDeclaration(); } String fname = typeFunctionName(satType, true); //Actually it could be "if not in same module" if (!JsCompiler.compilingLanguageModule && declaredInCL(tdec)) { out(",", fname); } else { int idx = fname.lastIndexOf('.'); if (idx > 0) { fname = fname.substring(0, idx+1) + "$init$" + fname.substring(idx+1); } else { fname = "$init$" + fname; } out(",", fname, "()"); } } } out(");"); //Add ref to outer type if (d.isMember()) { StringBuilder containers = new StringBuilder(); Scope _d2 = d; while (_d2 instanceof ClassOrInterface) { if (containers.length() > 0) { containers.insert(0, '.'); } containers.insert(0, names.name((Declaration)_d2)); _d2 = _d2.getScope(); } endLine(); out(containers.toString(), "=", names.name(d), ";"); } //The class definition needs to be inside the init function if we want forwards decls to work in prototype style if (opts.isOptimize()) { endLine(); callback.addToPrototypeCallback(); } endBlockNewLine(); out("return ", names.name(d), ";"); endBlockNewLine(); //If it's nested, share the init function if (outerSelf(d)) { out(".$init$", names.name(d), "=$init$", names.name(d), ";"); endLine(); } out("$init$", names.name(d), "();"); endLine(); } private String typeFunctionName(StaticType type, boolean removeAlias) { TypeDeclaration d = type.getTypeModel().getDeclaration(); if (removeAlias && d.isAlias()) { d = d.getExtendedTypeDeclaration(); } boolean inProto = opts.isOptimize() && (type.getScope().getContainer() instanceof TypeDeclaration); return memberAccessBase(type, d, false, qualifiedPath(type, d, inProto)); } private void addToPrototype(ClassOrInterface d, List<Statement> statements) { if (opts.isOptimize() && !statements.isEmpty()) { final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; out("(function(", names.self(d), ")"); beginBlock(); for (Statement s: statements) { addToPrototype(d, s); } endBlock(); out(")(", names.name(d), ".$$.prototype);"); endLine(); currentStatements = prevStatements; } } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, Statement s) { ClassOrInterface oldPrototypeOwner = prototypeOwner; prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } else if (s instanceof MethodDeclaration) { methodDeclaration(d, (MethodDeclaration) s); } else if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } else if (s instanceof AttributeDeclaration) { addGetterAndSetterToPrototype(d, (AttributeDeclaration) s); } else if (s instanceof ClassDefinition) { addClassToPrototype(d, (ClassDefinition) s); } else if (s instanceof InterfaceDefinition) { addInterfaceToPrototype(d, (InterfaceDefinition) s); } else if (s instanceof ObjectDefinition) { addObjectToPrototype(d, (ObjectDefinition) s); } else if (s instanceof ClassDeclaration) { addClassDeclarationToPrototype(d, (ClassDeclaration) s); } else if (s instanceof InterfaceDeclaration) { addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s); } else if (s instanceof SpecifierStatement) { addSpecifierToPrototype(d, (SpecifierStatement) s); } prototypeOwner = oldPrototypeOwner; } private void declareSelf(ClassOrInterface d) { out("if ("); self(d); out("===undefined)"); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); /*out("var "); self(d); out("="); self(); out(";"); endLine();*/ } private void instantiateSelf(ClassOrInterface d) { out("var "); self(d); out("=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this.", names.name(d), ".$$;"); } else { out(names.name(d), ".$$;"); } endLine(); } private void returnSelf(ClassOrInterface d) { out("return "); self(d); out(";"); } private void addObjectToPrototype(ClassOrInterface type, ObjectDefinition objDef) { objectDefinition(objDef); Value d = objDef.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); out(names.self(type), ".", names.name(c), "=", names.name(c), ";"); endLine(); } @Override public void visit(ObjectDefinition that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Value d = that.getDeclarationModel(); if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) { objectDefinition(that); } else { Class c = (Class) d.getTypeDeclaration(); comment(that); outerSelf(d); out(".", names.privateName(d), "="); outerSelf(d); out(".", names.name(c), "();"); endLine(); } } private void objectDefinition(ObjectDefinition that) { comment(that); Value d = that.getDeclarationModel(); boolean addToPrototype = opts.isOptimize() && d.isClassOrInterfaceMember(); Class c = (Class) d.getTypeDeclaration(); out(function, names.name(c)); Map<TypeParameter, ProducedType> targs=new HashMap<TypeParameter, ProducedType>(); if (that.getSatisfiedTypes() != null) { for (StaticType st : that.getSatisfiedTypes().getTypes()) { Map<TypeParameter, ProducedType> stargs = st.getTypeModel().getTypeArguments(); if (stargs != null && !stargs.isEmpty()) { targs.putAll(stargs); } } } out(targs.isEmpty()?"()":"($$targs$$)"); beginBlock(); instantiateSelf(c); referenceOuter(c); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } if (!targs.isEmpty()) { self(c); out(".$$targs$$=$$targs$$;"); endLine(); } callSuperclass(that.getExtendedType(), c, that, superDecs); callInterfaces(that.getSatisfiedTypes(), c, that, superDecs); that.getClassBody().visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); typeInitialization(that); addToPrototype(c, that.getClassBody().getStatements()); if (!addToPrototype) { out("var ", names.name(d), "=", names.name(c), "("); if (!targs.isEmpty()) { TypeUtils.printTypeArguments(that, targs, this); } out(");"); endLine(); } if (!defineAsProperty(d)) { out("var ", names.getter(d), "=function()"); beginBlock(); out("return "); if (addToPrototype) { out("this."); } out(names.name(d), ";"); endBlockNewLine(); if (addToPrototype || d.isShared()) { outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); } } else { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); if (addToPrototype) { out("this.", names.privateName(d)); } else { out(names.name(d)); } out(";});"); endLine(); } } private void superRef(Declaration d, ClassOrInterface sub, String parentSuffix) { //if (d.isActual()) { self(sub); out(".", names.name(d), parentSuffix, "="); self(sub); out(".", names.name(d), ";"); endLine(); //} } private void superGetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (defineAsProperty(d)) { out(clAlias, "copySuperAttr(", names.self(sub), ",'", names.name(d), "','", parentSuffix, "');"); } else { self(sub); out(".", names.getter(d), parentSuffix, "="); self(sub); out(".", names.getter(d), ";"); } endLine(); } private void superSetterRef(Declaration d, ClassOrInterface sub, String parentSuffix) { if (!defineAsProperty(d)) { self(sub); out(".", names.setter(d), parentSuffix, "="); self(sub); out(".", names.setter(d), ";"); endLine(); } } @Override public void visit(MethodDeclaration that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; methodDeclaration(null, that); } private void methodDeclaration(TypeDeclaration outer, MethodDeclaration that) { Method m = that.getDeclarationModel(); if (that.getSpecifierExpression() != null) { // method(params) => expr if (outer == null) { // Not in a prototype definition. Null to do here if it's a // member in prototype style. if (opts.isOptimize() && m.isMember()) { return; } comment(that); out("var "); } else { // prototype definition comment(that); out(names.self(outer), "."); } out(names.name(m), "="); singleExprFunction(that.getParameterLists(), that.getSpecifierExpression().getExpression(), that.getScope()); endLine(true); if (outer != null) { out(names.self(outer), "."); } out(names.name(m), ".$$metamodel$$="); TypeUtils.encodeForRuntime(m, that.getAnnotationList(), this); endLine(true); share(m); } else if (outer == null) { // don't do the following in a prototype definition //Check for refinement of simple param declaration if (m == that.getScope()) { if (m.getContainer() instanceof Class && m.isClassOrInterfaceMember()) { //Declare the method just by pointing to the param function final String name = names.name(((Class)m.getContainer()).getParameter(m.getName())); if (name != null) { self((Class)m.getContainer()); out(".", names.name(m), "=", name, ";"); endLine(); } } else if (m.getContainer() instanceof Method) { //Declare the function just by forcing the name we used in the param list final String name = names.name(((Method)m.getContainer()).getParameter(m.getName())); if (names != null) { names.forceName(m, name); } } } } } @Override public void visit(MethodDefinition that) { Method d = that.getDeclarationModel(); //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; if (!((opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) || isNative(d))) { comment(that); methodDefinition(that); //Add reference to metamodel out(names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(";//", names.name(d), ".$$targs$$="); Map<TypeParameter, ProducedType> _parms = new HashMap<>(); for (TypeParameter ctp : types.callable.getTypeParameters()) { if ("Return".equals(ctp.getName())) { _parms.put(ctp, d.getType()); } else if ("Arguments".equals(ctp.getName())) { try { com.redhat.ceylon.compiler.typechecker.model.ParameterList plist = d.getParameterLists().get(0); _parms.put(ctp, types.tupleFromParameters(plist.getParameters())); } catch (Exception ex) { System.err.println("WTF????? This should never happen! JS compiler is seriously broken..."); ex.printStackTrace(); } } } TypeUtils.printTypeArguments(that, _parms, this); endLine(true); } } private void methodDefinition(MethodDefinition that) { Method d = that.getDeclarationModel(); if (that.getParameterLists().size() == 1) { out(function, names.name(d)); ParameterList paramList = that.getParameterLists().get(0); paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, null); visitStatements(that.getBlock().getStatements()); endBlock(); } else { int count=0; for (ParameterList paramList : that.getParameterLists()) { if (count==0) { out(function, names.name(d)); } else { out("return function"); } paramList.visit(this); beginBlock(); initSelf(that.getBlock()); initParameters(paramList, null); count++; } visitStatements(that.getBlock().getStatements()); for (int i=0; i < count; i++) { endBlock(); } } if (!share(d)) { out(";"); } } private void initParameters(ParameterList params, TypeDeclaration typeDecl) { for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getDeclarationModel(); /*if (param instanceof ValueParameterDeclaration && ((ValueParameterDeclaration)param).getDeclarationModel().isHidden()) { //TODO support new syntax for class and method parameters //the declaration is actually different from the one we usually use out("//HIDDEN! ", pd.getName(), "(", names.name(pd), ")"); endLine(); }*/ String paramName = names.name(pd); if (param.getDefaultArgument() != null || pd.isSequenced()) { out("if(", paramName, "===undefined){", paramName, "="); if (param.getDefaultArgument() == null) { out(clAlias, "getEmpty()"); } else { final SpecifierExpression defaultExpr = param.getDefaultArgument().getSpecifierExpression(); if ((param instanceof FunctionalParameterDeclaration) && (defaultExpr instanceof LazySpecifierExpression)) { // function parameter defaulted using "=>" singleExprFunction( ((FunctionalParameterDeclaration) param).getParameterLists(), defaultExpr.getExpression(), null); } else { defaultExpr.visit(this); } } out(";}"); endLine(); } if ((typeDecl != null) && pd.isCaptured()) { self(typeDecl); out(".", paramName, "=", paramName, ";"); endLine(); } } } private void addMethodToPrototype(TypeDeclaration outer, MethodDefinition that) { Method d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); out(names.self(outer), ".", names.name(d), "="); methodDefinition(that); //Add reference to metamodel out(names.self(outer), ".", names.name(d), ".$$metamodel$$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out(";"); } @Override public void visit(AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return; comment(that); if (defineAsProperty(d)) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(");"); } else { out("var ", names.getter(d), "=function()"); super.visit(that); if (!shareGetter(d)) { out(";"); } } } private void addGetterToPrototype(TypeDeclaration outer, AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); super.visit(that); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } out(");"); } private AttributeSetterDefinition associatedSetterDefinition( Value valueDecl) { final Setter setter = valueDecl.getSetter(); if ((setter != null) && (currentStatements != null)) { for (Statement stmt : currentStatements) { if (stmt instanceof AttributeSetterDefinition) { final AttributeSetterDefinition setterDef = (AttributeSetterDefinition) stmt; if (setterDef.getDeclarationModel() == setter) { return setterDef; } } } } return null; } /** Exports a getter function; useful in non-prototype style. */ private boolean shareGetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.getter(d), "=", names.getter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return; comment(that); out("var ", names.setter(d.getGetter()), "=function(", names.name(d.getParameter()), ")"); if (that.getSpecifierExpression() == null) { that.getBlock().visit(this); } else { out("{return "); that.getSpecifierExpression().visit(this); out(";}"); } if (!shareSetter(d)) { out(";"); } } private boolean isCaptured(Declaration d) { if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures if (d.isShared() || d.isCaptured() ) { return true; } else { OuterVisitor ov = new OuterVisitor(d); ov.visit(root); return ov.found; } } else { return false; } } private boolean shareSetter(MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.setter(d), "=", names.setter(d), ";"); endLine(); shared = true; } return shared; } @Override public void visit(AttributeDeclaration that) { Value d = that.getDeclarationModel(); //Check if the attribute corresponds to a class parameter //This is because of the new initializer syntax String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } if (!d.isFormal()) { comment(that); final boolean isLate = d.isLate(); SpecifierOrInitializerExpression specInitExpr = that.getSpecifierOrInitializerExpression(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { if ((specInitExpr != null && !(specInitExpr instanceof LazySpecifierExpression)) || isLate) { outerSelf(d); out(".", names.privateName(d), "="); if (isLate) { out("undefined"); } else { super.visit(that); } endLine(true); } else if (classParam != null) { outerSelf(d); out(".", names.privateName(d), "=", classParam); endLine(true); } //TODO generate for => expr when no classParam is available } else if (specInitExpr instanceof LazySpecifierExpression) { final boolean property = defineAsProperty(d); if (property) { out(clAlias, "defineAttr("); outerSelf(d); out(",'", names.name(d), "',function(){return "); } else { out("var ", names.getter(d), "=function(){return "); } int boxType = boxStart(specInitExpr.getExpression().getTerm()); specInitExpr.getExpression().visit(this); if (boxType == 4) out("/*TODO: callable targs 1*/"); boxUnboxEnd(boxType); out(";}"); if (property) { if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } out(");"); endLine(); } else { endLine(true); shareGetter(d); } } else { if ((specInitExpr != null) || (classParam != null) || !d.isMember() || d.isVariable() || isLate) { generateAttributeGetter(d, specInitExpr, classParam); } if ((d.isVariable() || isLate) && !defineAsProperty(d)) { final String varName = names.name(d); String paramVarName = names.createTempVariable(d.getName()); out("var ", names.setter(d), "=function(", paramVarName, "){"); if (isLate) { generateImmutableAttributeReassignmentCheck(varName, names.name(d)); } out("return ", varName, "=", paramVarName, ";};"); endLine(); shareSetter(d); } } } } private void generateAttributeGetter(MethodOrValue decl, SpecifierOrInitializerExpression expr, String param) { final String varName = names.name(decl); out("var ", varName); if (expr != null) { out("="); int boxType = boxStart(expr.getExpression().getTerm()); if (dynblock > 0 && TypeUtils.isUnknown(expr.getExpression().getTypeModel()) && !TypeUtils.isUnknown(decl.getType())) { TypeUtils.generateDynamicCheck(expr.getExpression(), decl.getType(), this); } else { expr.visit(this); } if (boxType == 4) { //Pass Callable argument types out(","); if (decl instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)decl).getParameterLists().get(0), GenerateJsVisitor.this); } else { //Type of value must be Callable //And the Args Type Parameters is a Tuple types.encodeTupleAsParameterListForRuntime(decl.getType(), this); } out(","); TypeUtils.printTypeArguments(expr, expr.getExpression().getTypeModel().getTypeArguments(), this); } boxUnboxEnd(boxType); } else if (param != null) { out("=", param); } endLine(true); if (decl instanceof Method) { if (decl.isClassOrInterfaceMember() && isCaptured(decl)) { beginNewLine(); outerSelf(decl); out(".", names.name(decl), "=", names.name(decl), ";"); endLine(); } } else { if (isCaptured(decl)) { final boolean isLate = decl.isLate(); if (defineAsProperty(decl)) { out(clAlias, "defineAttr("); outerSelf(decl); out(",'", varName, "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck(varName, names.name(decl)); } out("return ", varName, ";}"); if (decl.isVariable() || isLate) { final String par = names.createTempVariable(decl.getName()); out(",function(", par, "){"); if (isLate && !decl.isVariable()) { generateImmutableAttributeReassignmentCheck(varName, names.name(decl)); } out("return ", varName, "=", par, ";}"); } out(");"); endLine(); } else { out("var ", names.getter(decl),"=function(){return ", varName, ";};"); endLine(); shareGetter(decl); } } else { directAccess.add(decl); } } } void generateUnitializedAttributeReadCheck(String privname, String pubname) { //TODO we can later optimize this, to replace this getter with the plain one //once the value has been defined out("if (", privname, "===undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to read unitialized attribute «", pubname, "»'));"); } void generateImmutableAttributeReassignmentCheck(String privname, String pubname) { out("if(", privname, "!==undefined)throw ", clAlias, "InitializationException("); if (JsCompiler.compilingLanguageModule) { out("String$('"); } else { out(clAlias, "String('"); } out("Attempt to reassign immutable attribute «", pubname, "»'));"); } private void addGetterAndSetterToPrototype(TypeDeclaration outer, AttributeDeclaration that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||d.isToplevel()) return; if (!d.isFormal()) { comment(that); String classParam = null; if (d.getContainer() instanceof Functional) { classParam = names.name(((Functional)d.getContainer()).getParameter(d.getName())); } final boolean isLate = d.isLate(); if ((that.getSpecifierOrInitializerExpression() != null) || d.isVariable() || classParam != null || isLate) { if (that.getSpecifierOrInitializerExpression() instanceof LazySpecifierExpression) { // attribute is defined by a lazy expression ("=>" syntax) out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function()"); beginBlock(); initSelf(that.getScope()); out("return "); Expression expr = that.getSpecifierOrInitializerExpression().getExpression(); int boxType = boxStart(expr.getTerm()); expr.visit(this); endLine(true); if (boxType == 4) out("/*TODO: callable targs 3*/"); boxUnboxEnd(boxType); endBlock(); if (d.isVariable()) { Tree.AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); if (setterDef.getSpecifierExpression() == null) { super.visit(setterDef); } else { out("{"); initSelf(that.getScope()); out("return "); setterDef.getSpecifierExpression().visit(this); out(";}"); } } } out(")"); endLine(true); } else { final String privname = names.privateName(d); out(clAlias, "defineAttr(", names.self(outer), ",'", names.name(d), "',function(){"); if (isLate) { generateUnitializedAttributeReadCheck("this."+privname, names.name(d)); } out("return this.", privname, ";}"); if (d.isVariable() || isLate) { final String param = names.createTempVariable(d.getName()); out(",function(", param, "){"); if (isLate && !d.isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(d)); } out("return this.", privname, "=", param, ";}"); } out(");"); endLine(); } } } } @Override public void visit(CharLiteral that) { out(clAlias, "Character("); out(String.valueOf(that.getText().codePointAt(1))); out(")"); } /** Escapes a StringLiteral (needs to be quoted). */ String escapeStringLiteral(String s) { StringBuilder text = new StringBuilder(s); //Escape special chars for (int i=0; i < text.length();i++) { switch(text.charAt(i)) { case 8:text.replace(i, i+1, "\\b"); i++; break; case 9:text.replace(i, i+1, "\\t"); i++; break; case 10:text.replace(i, i+1, "\\n"); i++; break; case 12:text.replace(i, i+1, "\\f"); i++; break; case 13:text.replace(i, i+1, "\\r"); i++; break; case 34:text.replace(i, i+1, "\\\""); i++; break; case 39:text.replace(i, i+1, "\\'"); i++; break; case 92:text.replace(i, i+1, "\\\\"); i++; break; case 0x2028:text.replace(i, i+1, "\\u2028"); i++; break; case 0x2029:text.replace(i, i+1, "\\u2029"); i++; break; } } return text.toString(); } @Override public void visit(StringLiteral that) { final int slen = that.getText().codePointCount(0, that.getText().length()); if (JsCompiler.compilingLanguageModule) { out("String$(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } else { out(clAlias, "String(\"", escapeStringLiteral(that.getText()), "\",", Integer.toString(slen), ")"); } } @Override public void visit(StringTemplate that) { List<StringLiteral> literals = that.getStringLiterals(); List<Expression> exprs = that.getExpressions(); out(clAlias, "StringBuilder().appendAll(["); boolean first = true; for (int i = 0; i < literals.size(); i++) { StringLiteral literal = literals.get(i); if (!literal.getText().isEmpty()) { if (!first) { out(","); } first = false; literal.visit(this); } if (i < exprs.size()) { if (!first) { out(","); } first = false; exprs.get(i).visit(this); out(".string"); } } out("]).string"); } @Override public void visit(FloatLiteral that) { out(clAlias, "Float(", that.getText(), ")"); } @Override public void visit(NaturalLiteral that) { char prefix = that.getText().charAt(0); if (prefix == '$' || prefix == '#') { int radix= prefix == '$' ? 2 : 16; try { out("(", new java.math.BigInteger(that.getText().substring(1), radix).toString(), ")"); } catch (NumberFormatException ex) { that.addError("Invalid numeric literal " + that.getText()); } } else { out("(", that.getText(), ")"); } } @Override public void visit(This that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Super that) { self(Util.getContainingClassOrInterface(that.getScope())); } @Override public void visit(Outer that) { boolean outer = false; if (opts.isOptimize()) { Scope scope = that.getScope(); while ((scope != null) && !(scope instanceof TypeDeclaration)) { scope = scope.getContainer(); } if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) { self((TypeDeclaration) scope); out("."); outer = true; } } if (outer) { out("$$outer"); } else { self(that.getTypeModel().getDeclaration()); } } @Override public void visit(BaseMemberExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) { //Don't even bother processing a node with errors return; } Declaration decl = that.getDeclaration(); if (decl != null) { String name = decl.getName(); String pkgName = decl.getUnit().getPackage().getQualifiedNameString(); // map Ceylon true/false/null directly to JS true/false/null if ("ceylon.language".equals(pkgName)) { if ("true".equals(name) || "false".equals(name) || "null".equals(name)) { out(name); return; } } } String exp = memberAccess(that, null); if (decl == null && isInDynamicBlock()) { out("(typeof ", exp, "==='undefined'||", exp, "===null?", clAlias, "throwexc('Undefined or null reference: ", exp, "'):", exp, ")"); } else { out(exp); } } private boolean accessDirectly(Declaration d) { return !accessThroughGetter(d) || directAccess.contains(d); } private boolean accessThroughGetter(Declaration d) { return (d instanceof MethodOrValue) && !(d instanceof Method) && !defineAsProperty(d); } private boolean defineAsProperty(Declaration d) { // for now, only define member attributes as properties, not toplevel attributes return d.isMember() && (d instanceof MethodOrValue) && !(d instanceof Method); } /** Returns true if the top-level declaration for the term is annotated "nativejs" */ private static boolean isNative(Term t) { if (t instanceof MemberOrTypeExpression) { return isNative(((MemberOrTypeExpression)t).getDeclaration()); } return false; } /** Returns true if the declaration is annotated "nativejs" */ private static boolean isNative(Declaration d) { return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d); } private static Declaration getToplevel(Declaration d) { while (d != null && !d.isToplevel()) { Scope s = d.getContainer(); // Skip any non-declaration elements while (s != null && !(s instanceof Declaration)) { s = s.getContainer(); } d = (Declaration) s; } return d; } private static boolean hasAnnotationByName(Declaration d, String name){ if (d != null) { for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){ if(annotation.getName().equals(name)) return true; } } return false; } private void generateSafeOp(QualifiedMemberOrTypeExpression that) { boolean isMethod = that.getDeclaration() instanceof Method; String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); super.visit(that); out(","); if (isMethod) { out(clAlias, "JsCallable(", lhsVar, ","); } out(lhsVar, "!==null?", memberAccess(that, lhsVar), ":null)"); if (isMethod) { out(")"); } } @Override public void visit(final QualifiedMemberExpression that) { //Big TODO: make sure the member is actually // refined by the current class! if (that.getMemberOperator() instanceof SafeMemberOp) { generateSafeOp(that); } else if (that.getMemberOperator() instanceof SpreadOp) { generateSpread(that); } else if (that.getDeclaration() instanceof Method && that.getSignature() == null) { //TODO right now this causes that all method invocations are done this way //we need to filter somehow to only use this pattern when the result is supposed to be a callable //looks like checking for signature is a good way (not THE way though; named arg calls don't have signature) generateCallable(that, null); } else if (that.getStaticMethodReference()) { out("function($O$) {return "); if (that.getDeclaration() instanceof Method) { out(clAlias, "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ");}"); } else { out("$O$.", names.name(that.getDeclaration()), ";}"); } } else { final String lhs = generateToString(new GenerateCallback() { @Override public void generateValue() { GenerateJsVisitor.super.visit(that); } }); out(memberAccess(that, lhs)); } } /** SpreadOp cannot be a simple function call because we need to reference the object methods directly, so it's a function */ private void generateSpread(QualifiedMemberOrTypeExpression that) { //Determine if it's a method or attribute boolean isMethod = that.getDeclaration() instanceof Method; //Define a function out("(function()"); beginBlock(); if (opts.isComment()) { out("//SpreadOp at ", that.getLocation()); endLine(); } //Declare an array to store the values/references String tmplist = names.createTempVariable("lst"); out("var ", tmplist, "=[];"); endLine(); //Get an iterator String iter = names.createTempVariable("it"); out("var ", iter, "="); super.visit(that); out(".iterator();"); endLine(); //Iterate String elem = names.createTempVariable("elem"); out("var ", elem, ";"); endLine(); out("while ((", elem, "=", iter, ".next())!==", clAlias, "getFinished())"); beginBlock(); //Add value or reference to the array out(tmplist, ".push("); if (isMethod) { out("{o:", elem, ", f:", memberAccess(that, elem), "}"); } else { out(memberAccess(that, elem)); } out(");"); endBlockNewLine(); //Gather arguments to pass to the callable //Return the array of values or a Callable with the arguments out("return ", clAlias); if (isMethod) { out("JsCallableList(", tmplist, ");"); } else { out("ArraySequence(", tmplist, ");"); } endBlock(); out("())"); } private void generateCallable(QualifiedMemberOrTypeExpression that, String name) { String primaryVar = createRetainedTempVar("opt"); out("(", primaryVar, "="); that.getPrimary().visit(this); out(",", clAlias, "JsCallable(", primaryVar, ",", primaryVar, "!==null?", (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name), ":null))"); } /** * Checks if the given node is a MemberOrTypeExpression or QualifiedType which * represents an access to a supertype member and returns the scope of that * member or null. */ Scope getSuperMemberScope(Node node) { Scope scope = null; if (node instanceof QualifiedMemberOrTypeExpression) { // Check for "super.member" QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node; final Term primary = eliminateParensAndWidening(qmte.getPrimary()); if (primary instanceof Super) { scope = qmte.getDeclaration().getContainer(); } } else if (node instanceof QualifiedType) { // Check for super.Membertype QualifiedType qtype = (QualifiedType) node; if (qtype.getOuterType() instanceof SuperType) { scope = qtype.getDeclarationModel().getContainer(); } } return scope; } private String memberAccessBase(Node node, Declaration decl, boolean setter, String lhs) { StringBuilder sb = new StringBuilder(); if (lhs != null) { if (lhs.length() > 0) { sb.append(lhs).append("."); } } else if (node instanceof BaseMemberOrTypeExpression) { BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node; String path = qualifiedPath(node, bmte.getDeclaration()); if (path.length() > 0) { sb.append(path); sb.append("."); } } Scope scope = getSuperMemberScope(node); if (opts.isOptimize() && (scope != null)) { sb.append("getT$all()['"); sb.append(scope.getQualifiedNameString()); sb.append("']"); if (defineAsProperty(decl)) { return clAlias + (setter ? "attrSetter(" : "attrGetter(") + sb.toString() + ",'" + names.name(decl) + "')"; } sb.append(".$$.prototype."); } final String member = (accessThroughGetter(decl) && !accessDirectly(decl)) ? (setter ? names.setter(decl) : names.getter(decl)) : names.name(decl); sb.append(member); if (!opts.isOptimize() && (scope != null)) { sb.append(names.scopeSuffix(scope)); } //When compiling the language module we need to modify certain base type names String rval = sb.toString(); if (TypeUtils.isReservedTypename(rval)) { rval = sb.append("$").toString(); } return rval; } /** * Returns a string representing a read access to a member, as represented by * the given expression. If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private String memberAccess(StaticMemberOrTypeExpression expr, String lhs) { Declaration decl = expr.getDeclaration(); String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { return ((lhs != null) && (lhs.length() > 0)) ? (lhs + "." + plainName) : plainName; } boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without getter return memberAccessBase(expr, decl, false, lhs); } // access through getter return memberAccessBase(expr, decl, false, lhs) + (protoCall ? ".call(this)" : "()"); } /** * Generates a write access to a member, as represented by the given expression. * The given callback is responsible for generating the assigned value. * If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ private void generateMemberAccess(StaticMemberOrTypeExpression expr, GenerateCallback callback, String lhs) { Declaration decl = expr.getDeclaration(); boolean paren = false; String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { if ((lhs != null) && (lhs.length() > 0)) { out(lhs, "."); } out(plainName, "="); } else { boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without setter out(memberAccessBase(expr, decl, true, lhs), "="); } else { // access through setter out(memberAccessBase(expr, decl, true, lhs), protoCall ? ".call(this," : "("); paren = true; } } callback.generateValue(); if (paren) { out(")"); } } private void generateMemberAccess(final StaticMemberOrTypeExpression expr, final String strValue, final String lhs) { generateMemberAccess(expr, new GenerateCallback() { @Override public void generateValue() { out(strValue); } }, lhs); } @Override public void visit(BaseTypeExpression that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; Declaration d = that.getDeclaration(); if (d == null && isInDynamicBlock()) { //It's a native js type but will be wrapped in dyntype() call String id = that.getIdentifier().getText(); out("(typeof ", id, "==='undefined'?", clAlias, "throwexc('Undefined type ", id, "'):", id, ")"); } else { qualify(that, d); out(names.name(d)); } } @Override public void visit(QualifiedTypeExpression that) { if (that.getMemberOperator() instanceof SafeMemberOp) { generateCallable(that, names.name(that.getDeclaration())); } else { super.visit(that); out(".", names.name(that.getDeclaration())); } } public void visit(Dynamic that) { //this is value{xxx} invoker.nativeObject(that.getNamedArgumentList()); } @Override public void visit(InvocationExpression that) { invoker.generateInvocation(that); } @Override public void visit(PositionalArgumentList that) { invoker.generatePositionalArguments(that, that.getPositionalArguments(), false, false); } /** Box a term, visit it, unbox it. */ private void box(Term term) { final int t = boxStart(term); term.visit(this); if (t == 4) out("/*TODO: callable targs 4*/"); boxUnboxEnd(t); } // Make sure fromTerm is compatible with toTerm by boxing it when necessary private int boxStart(Term fromTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = false; ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, Term toTerm) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toTerm); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } // Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary int boxUnboxStart(Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) { boolean fromNative = isNative(fromTerm); boolean toNative = isNative(toDecl); ProducedType fromType = fromTerm.getTypeModel(); return boxUnboxStart(fromNative, fromType, toNative); } int boxUnboxStart(boolean fromNative, ProducedType fromType, boolean toNative) { // Box the value final String fromTypeName = TypeUtils.isUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName(); if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) { if (fromNative) { // conversion from native value to Ceylon value if (fromTypeName.equals("ceylon.language::String")) { if (JsCompiler.compilingLanguageModule) { out("String$("); } else { out(clAlias, "String("); } } else if (fromTypeName.equals("ceylon.language::Integer")) { out("("); } else if (fromTypeName.equals("ceylon.language::Float")) { out(clAlias, "Float("); } else if (fromTypeName.equals("ceylon.language::Boolean")) { out("("); } else if (fromTypeName.equals("ceylon.language::Character")) { out(clAlias, "Character("); } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 0; } return 1; } else if ("ceylon.language::String".equals(fromTypeName) || "ceylon.language::Float".equals(fromTypeName)) { // conversion from Ceylon String or Float to native value return 2; } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(clAlias, "$JsCallable("); return 4; } else { return 3; } } return 0; } void boxUnboxEnd(int boxType) { switch (boxType) { case 1: out(")"); break; case 2: out(".valueOf()"); break; case 4: out(")"); break; default: //nothing } } @Override public void visit(ObjectArgument that) { //Don't even bother with nodes that have errors if (that.getErrors() != null && !that.getErrors().isEmpty()) return; final Class c = (Class)that.getDeclarationModel().getTypeDeclaration(); out("(function()"); beginBlock(); out("//ObjectArgument ", that.getIdentifier().getText()); location(that); endLine(); out(function, names.name(c), "()"); beginBlock(); instantiateSelf(c); referenceOuter(c); ExtendedType xt = that.getExtendedType(); final ClassBody body = that.getClassBody(); SatisfiedTypes sts = that.getSatisfiedTypes(); final List<Declaration> superDecs = new ArrayList<Declaration>(); if (!opts.isOptimize()) { new SuperVisitor(superDecs).visit(that.getClassBody()); } callSuperclass(xt, c, that, superDecs); callInterfaces(sts, c, that, superDecs); body.visit(this); returnSelf(c); indentLevel--; endLine(); out("}"); endLine(); //Add reference to metamodel out(names.name(c), ".$$metamodel$$="); TypeUtils.encodeForRuntime(c, null/*TODO check if an object arg can have annotations */, this); endLine(true); typeInitialization(xt, sts, false, c, new PrototypeInitCallback() { @Override public void addToPrototypeCallback() { addToPrototype(c, body.getStatements()); } }); out("return ", names.name(c), "(new ", names.name(c), ".$$);"); endBlock(); out("())"); } @Override public void visit(AttributeArgument that) { out("(function()"); beginBlock(); out("//AttributeArgument ", that.getParameter().getName()); location(that); endLine(); Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("return "); specExpr.getExpression().visit(this); out(";"); } else if (block != null) { visitStatements(block.getStatements()); } endBlock(); out("())"); } @Override public void visit(SequencedArgument that) { List<PositionalArgument> positionalArguments = that.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; if (!spread) { out("["); } boolean first=true; for (PositionalArgument arg: positionalArguments) { if (!first) out(","); if (arg instanceof Tree.ListedArgument) { ((Tree.ListedArgument) arg).getExpression().visit(this); } else if(arg instanceof Tree.SpreadArgument) ((Tree.SpreadArgument) arg).getExpression().visit(this); else // comprehension arg.visit(this); first = false; } if (!spread) { out("]"); } } @Override public void visit(SequenceEnumeration that) { SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); int lim = positionalArguments.size()-1; boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int count=0; ProducedType chainedType = null; if (lim>0 || !spread) { out("["); } for (PositionalArgument expr : positionalArguments) { if (count==lim && spread) { if (lim > 0) { ProducedType seqType = TypeUtils.findSupertype(types.iterable, that.getTypeModel()); closeSequenceWithReifiedType(that, seqType.getTypeArguments()); out(".chain("); chainedType = TypeUtils.findSupertype(types.iterable, expr.getTypeModel()); } count--; } else { if (count > 0) { out(","); } } if (dynblock > 0 && expr instanceof ListedArgument && TypeUtils.isUnknown(expr.getTypeModel())) { TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), types.anything.getType(), this); } else { expr.visit(this); } count++; } if (chainedType == null) { if (!spread) { closeSequenceWithReifiedType(that, that.getTypeModel().getTypeArguments()); } } else { out(","); TypeUtils.printTypeArguments(that, chainedType.getTypeArguments(), this); out(")"); } } } @Override public void visit(Comprehension that) { new ComprehensionGenerator(this, names, directAccess).generateComprehension(that); } @Override public void visit(final SpecifierStatement that) { // A lazy specifier expression in a class/interface should go into the // prototype in prototype style, so don't generate them here. if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression) && (that.getScope().getContainer() instanceof TypeDeclaration))) { specifierStatement(null, that); } } private void specifierStatement(final TypeDeclaration outer, final SpecifierStatement specStmt) { if (specStmt.getBaseMemberExpression() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) specStmt.getBaseMemberExpression(); Declaration bmeDecl = bme.getDeclaration(); if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) { // attr => expr; final boolean property = defineAsProperty(bmeDecl); if (property) { out(clAlias, "defineAttr(", qualifiedPath(specStmt, bmeDecl), ",'", names.name(bmeDecl), "',function()"); } else { if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out ("var "); } out(names.getter(bmeDecl), "=function()"); } beginBlock(); if (outer != null) { initSelf(specStmt.getScope()); } out ("return "); specStmt.getSpecifierExpression().visit(this); out(";"); endBlock(); if (property) { out(")"); } endLine(true); directAccess.remove(bmeDecl); } else if (outer != null) { // "attr = expr;" in a prototype definition if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) { out("delete ", names.self(outer), ".", names.name(bmeDecl)); endLine(true); } } else if (bmeDecl instanceof MethodOrValue) { // "attr = expr;" in an initializer or method final MethodOrValue moval = (MethodOrValue)bmeDecl; if (moval.isVariable()) { // simple assignment to a variable attribute generateMemberAccess(bme, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(specStmt.getSpecifierExpression().getExpression().getTerm(), moval); if (dynblock > 0 && !TypeUtils.isUnknown(moval.getType()) && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), moval.getType(), GenerateJsVisitor.this); } else { specStmt.getSpecifierExpression().getExpression().visit(GenerateJsVisitor.this); } if (boxType == 4) { out(","); if (moval instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this); out(","); } else { //TODO extract parameters from Value out("[/*VALUE Callable params", moval.getClass().getName(), "*/],"); } TypeUtils.printTypeArguments(specStmt.getSpecifierExpression().getExpression(), specStmt.getSpecifierExpression().getExpression().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); } boxUnboxEnd(boxType); } }, null); out(";"); } else if (moval.isMember()) { // Specifier for a member attribute. This actually defines the // member (e.g. in shortcut refinement syntax the attribute // declaration itself can be omitted), so generate the attribute. generateAttributeGetter(moval, specStmt.getSpecifierExpression(), null); } else { // Specifier for some other attribute, or for a method. if (opts.isOptimize() || (bmeDecl.isMember() && (bmeDecl instanceof Method))) { qualify(specStmt, bmeDecl); } out(names.name(bmeDecl), "="); if (dynblock > 0 && TypeUtils.isUnknown(specStmt.getSpecifierExpression().getExpression().getTypeModel())) { TypeUtils.generateDynamicCheck(specStmt.getSpecifierExpression().getExpression(), bme.getTypeModel(), this); } else { specStmt.getSpecifierExpression().visit(this); } out(";"); } } } else if ((specStmt.getBaseMemberExpression() instanceof ParameterizedExpression) && (specStmt.getSpecifierExpression() != null)) { final ParameterizedExpression paramExpr = (ParameterizedExpression) specStmt.getBaseMemberExpression(); if (paramExpr.getPrimary() instanceof BaseMemberExpression) { // func(params) => expr; BaseMemberExpression bme = (BaseMemberExpression) paramExpr.getPrimary(); Declaration bmeDecl = bme.getDeclaration(); if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out("var "); } out(names.name(bmeDecl), "="); singleExprFunction(paramExpr.getParameterLists(), specStmt.getSpecifierExpression().getExpression(), specStmt.getScope()); out(";"); } } } private void addSpecifierToPrototype(final TypeDeclaration outer, final SpecifierStatement specStmt) { specifierStatement(outer, specStmt); } @Override public void visit(final AssignOp that) { String returnValue = null; StaticMemberOrTypeExpression lhsExpr = null; if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { that.getLeftTerm().visit(this); out("="); int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); return; } out("("); if (that.getLeftTerm() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm(); lhsExpr = bme; Declaration bmeDecl = bme.getDeclaration(); boolean simpleSetter = hasSimpleGetterSetter(bmeDecl); if (!simpleSetter) { returnValue = memberAccess(bme, null); } } else if (that.getLeftTerm() instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm(); lhsExpr = qme; boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration()); String lhsVar = null; if (!simpleSetter) { lhsVar = createRetainedTempVar(); out(lhsVar, "="); super.visit(qme); out(",", lhsVar, "."); returnValue = memberAccess(qme, lhsVar); } else { super.visit(qme); out("."); } } generateMemberAccess(lhsExpr, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(GenerateJsVisitor.this); if (boxType == 4) out("/*TODO: callable targs 7*/"); boxUnboxEnd(boxType); } }, null); if (returnValue != null) { out(",", returnValue); } out(")"); } /** Outputs the module name for the specified declaration. Returns true if something was output. */ boolean qualify(Node that, Declaration d) { if (d.getUnit().getPackage().getModule().isDefault()) { return false; } String path = qualifiedPath(that, d); if (path.length() > 0) { out(path, "."); } return path.length() > 0; } private String qualifiedPath(Node that, Declaration d) { return qualifiedPath(that, d, false); } private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); super.visit(that); } @Override public void visit(AnnotationList that) { out("/*anotaciones:"); for (Annotation ann : that.getAnnotations()) { out(ann.getTypeModel().getProducedTypeQualifiedName(),","); } out("*/"); } void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".scale("); termgen.left(); out(")"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null || resources != null) { out("finally"); if (resources != null) { out("{"); for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){}"); } } if (that.getFinallyClause() != null) { encloseBlockInFunction(that.getFinallyClause().getBlock()); } if (resources != null) { out("}"); } } } @Override public void visit(Throw that) { out("throw "); if (that.getExpression() != null) { that.getExpression().visit(this); } else { out(clAlias, "Exception()"); } out(";"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase){ boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); out(expvar, "==="); //TODO equality? /*out(".equals(");*/ exp.visit(this); //out(")==="); clAlias(); out("getTrue()"); first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() != null) { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); initParameters(paramList, null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape custom = escapeStringLiteral(sb.toString()); out(") { throw ", clAlias, "AssertionException('", custom, "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$metamodel({Type:"); final StaticType type = that.getType(); - TypeUtils.metamodelTypeNameOrList(type.getUnit().getPackage(), - type.getTypeModel().resolveAliases(), this); + final ProducedType pt = type.getTypeModel().resolveAliases(); + TypeUtils.typeNameOrList(that, pt, this, true); out("})"); } }
true
true
private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); super.visit(that); } @Override public void visit(AnnotationList that) { out("/*anotaciones:"); for (Annotation ann : that.getAnnotations()) { out(ann.getTypeModel().getProducedTypeQualifiedName(),","); } out("*/"); } void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".scale("); termgen.left(); out(")"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null || resources != null) { out("finally"); if (resources != null) { out("{"); for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){}"); } } if (that.getFinallyClause() != null) { encloseBlockInFunction(that.getFinallyClause().getBlock()); } if (resources != null) { out("}"); } } } @Override public void visit(Throw that) { out("throw "); if (that.getExpression() != null) { that.getExpression().visit(this); } else { out(clAlias, "Exception()"); } out(";"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase){ boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); out(expvar, "==="); //TODO equality? /*out(".equals(");*/ exp.visit(this); //out(")==="); clAlias(); out("getTrue()"); first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() != null) { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); initParameters(paramList, null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape custom = escapeStringLiteral(sb.toString()); out(") { throw ", clAlias, "AssertionException('", custom, "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$metamodel({Type:"); final StaticType type = that.getType(); TypeUtils.metamodelTypeNameOrList(type.getUnit().getPackage(), type.getTypeModel().resolveAliases(), this); out("})"); } }
private String qualifiedPath(Node that, Declaration d, boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d instanceof com.redhat.ceylon.compiler.typechecker.model.Parameter && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } //else { //an inherited declaration that might be //inherited by an outer scope //} String path = ""; Scope scope = that.getScope(); // if (inProto) { // while ((scope != null) && (scope instanceof TypeDeclaration)) { // scope = scope.getContainer(); // } // } if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path += ".$$outer"; } else { path += names.self((TypeDeclaration) scope); } } else { path = ""; } if (scope == id) { break; } scope = scope.getContainer(); } return path; } } else if (d != null && (d.isShared() || inProto) && isMember) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); return !p1.equals(p2); } @Override public void visit(ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ private String createRetainedTempVar(String baseName) { String varName = names.createTempVariable(baseName); retainedVars.add(varName); return varName; } private String createRetainedTempVar() { return createRetainedTempVar("tmp"); } // @Override // public void visit(Expression that) { // if (that.getTerm() instanceof QualifiedMemberOrTypeExpression) { // QualifiedMemberOrTypeExpression term = (QualifiedMemberOrTypeExpression) that.getTerm(); // // References to methods of types from other packages always need // // special treatment, even if opts.isOptimize()==false, because they // // may have been generated in prototype style. In particular, // // ceylon.language is always in prototype style. // if ((term.getDeclaration() instanceof Functional) // && (opts.isOptimize() || !declaredInThisPackage(term.getDeclaration()))) { // if (term.getMemberOperator() instanceof SpreadOp) { // generateSpread(term); // } else { // generateCallable(term, names.name(term.getDeclaration())); // } // return; // } // } // super.visit(that); // } @Override public void visit(Return that) { out("return "); super.visit(that); } @Override public void visit(AnnotationList that) { out("/*anotaciones:"); for (Annotation ann : that.getAnnotations()) { out(ann.getTypeModel().getProducedTypeQualifiedName(),","); } out("*/"); } void self(TypeDeclaration d) { out(names.self(d)); } private boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("exports"); return true; } else if (d.isClassOrInterfaceMember()) { self((TypeDeclaration)d.getContainer()); return true; } return false; } private boolean declaredInCL(Declaration decl) { return decl.getUnit().getPackage().getQualifiedNameString() .startsWith("ceylon.language"); } @Override public void visit(SumOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".plus("); termgen.right(); out(")"); } }); } @Override public void visit(ScaleOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".scale("); termgen.left(); out(")"); } }); } @Override public void visit(DifferenceOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".minus("); termgen.right(); out(")"); } }); } @Override public void visit(ProductOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".times("); termgen.right(); out(")"); } }); } @Override public void visit(QuotientOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".divided("); termgen.right(); out(")"); } }); } @Override public void visit(RemainderOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".remainder("); termgen.right(); out(")"); } }); } @Override public void visit(PowerOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".power("); termgen.right(); out(")"); } }); } @Override public void visit(AddAssignOp that) { arithmeticAssignOp(that, "plus"); } @Override public void visit(SubtractAssignOp that) { arithmeticAssignOp(that, "minus"); } @Override public void visit(MultiplyAssignOp that) { arithmeticAssignOp(that, "times"); } @Override public void visit(DivideAssignOp that) { arithmeticAssignOp(that, "divided"); } @Override public void visit(RemainderAssignOp that) { arithmeticAssignOp(that, "remainder"); } private void arithmeticAssignOp(final ArithmeticAssignmentOp that, final String functionName) { Term lhs = that.getLeftTerm(); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, null); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) out("("); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); out("="); int boxType = boxStart(lhsQME); lhsQME.getPrimary().visit(this); out(".", lhsQME.getDeclaration().getName()); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); that.getRightTerm().visit(this); out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); that.getRightTerm().visit(GenerateJsVisitor.this); out(")"); } }, lhsPrimaryVar); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final NegativeOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer)) { out("(-"); termgen.term(); out(")"); //This is not really optimal yet, since it generates //stuff like Float(-Float((5.1))) /*} else if (d.inherits(types._float)) { out(clAlias, "Float(-"); termgen.term(); out(")");*/ } else { termgen.term(); out(".negativeValue"); } } }); } @Override public void visit(final PositiveOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); if (d.inherits(types._integer) || d.inherits(types._float)) { out("(+"); termgen.term(); out(")"); } else { termgen.term(); out(".positiveValue"); } } }); } @Override public void visit(EqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { leftEqualsRight(that); } } @Override public void visit(NotEqualOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { out("(!"); leftEqualsRight(that); out(")"); } } @Override public void visit(NotOp that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out("(!"); termgen.term(); out(")"); } }); } @Override public void visit(IdenticalOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("==="); termgen.right(); out(")"); } }); } @Override public void visit(CompareOp that) { leftCompareRight(that); } @Override public void visit(SmallerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getSmaller())"); } } @Override public void visit(LargerOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", clAlias, "getLarger()))||", ltmp, ">", rtmp, ")"); } else { leftCompareRight(that); out(".equals(", clAlias, "getLarger())"); } } @Override public void visit(SmallAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getLarger())||", ltmp, "<=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getLarger()"); out(")"); } } @Override public void visit(LargeAsOp that) { if (dynblock > 0 && TypeUtils.isUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", clAlias, "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { out("("); leftCompareRight(that); out("!==", clAlias, "getSmaller()"); out(")"); } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && TypeUtils.isUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", clAlias, "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", clAlias, "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getLarger()"); } else { out(")!==", clAlias, "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", clAlias, "getSmaller()"); } else { out(")!==", clAlias, "getLarger()"); } } out(")"); } /** Outputs the CL equivalent of 'a==b' in JS. */ private void leftEqualsRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".equals("); termgen.right(); out(")"); } }); } interface UnaryOpTermGenerator { void term(); } interface UnaryOpGenerator { void generate(UnaryOpTermGenerator termgen); } private void unaryOp(final UnaryOperatorExpression that, final UnaryOpGenerator gen) { final GenerateJsVisitor visitor = this; gen.generate(new UnaryOpTermGenerator() { @Override public void term() { int boxTypeLeft = boxStart(that.getTerm()); that.getTerm().visit(visitor); if (boxTypeLeft == 4) out("/*TODO: callable targs 9*/"); boxUnboxEnd(boxTypeLeft); } }); } interface BinaryOpTermGenerator { void left(); void right(); } interface BinaryOpGenerator { void generate(BinaryOpTermGenerator termgen); } private void binaryOp(final BinaryOperatorExpression that, final BinaryOpGenerator gen) { gen.generate(new BinaryOpTermGenerator() { @Override public void left() { box(that.getLeftTerm()); } @Override public void right() { box(that.getRightTerm()); } }); } /** Outputs the CL equivalent of 'a <=> b' in JS. */ private void leftCompareRight(BinaryOperatorExpression that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".compare("); termgen.right(); out(")"); } }); } @Override public void visit(AndOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("&&"); termgen.right(); out(")"); } }); } @Override public void visit(OrOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("||"); termgen.right(); out(")"); } }); } @Override public void visit(final EntryOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Entry("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Element that) { out(".get("); that.getExpression().visit(this); out(")"); } @Override public void visit(DefaultOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { String lhsVar = createRetainedTempVar("opt"); out("(", lhsVar, "="); termgen.left(); out(",", lhsVar, "!==null?", lhsVar, ":"); termgen.right(); out(")"); } }); } @Override public void visit(ThenOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out("("); termgen.left(); out("?"); termgen.right(); out(":null)"); } }); } @Override public void visit(IncrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(DecrementOp that) { prefixIncrementOrDecrement(that.getTerm(), "predecessor"); } private boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } private void prefixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; boolean simpleSetter = hasSimpleGetterSetter(bme.getDeclaration()); String getMember = memberAccess(bme, null); String applyFunc = String.format("%s.%s", getMember, functionName); out("("); generateMemberAccess(bme, applyFunc, null); if (!simpleSetter) { out(",", getMember); } out(")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; String primaryVar = createRetainedTempVar(); String getMember = memberAccess(qme, primaryVar); String applyFunc = String.format("%s.%s", getMember, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(","); generateMemberAccess(qme, applyFunc, primaryVar); if (!hasSimpleGetterSetter(qme.getDeclaration())) { out(",", getMember); } out(")"); } } @Override public void visit(PostfixIncrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "successor"); } @Override public void visit(PostfixDecrementOp that) { postfixIncrementOrDecrement(that.getTerm(), "predecessor"); } private void postfixIncrementOrDecrement(Term term, String functionName) { if (term instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) term; if (bme.getDeclaration() == null && dynblock > 0) { out(bme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String oldValueVar = createRetainedTempVar("old" + bme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", oldValueVar, "=", memberAccess(bme, null), ","); generateMemberAccess(bme, applyFunc, null); out(",", oldValueVar, ")"); } else if (term instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression) term; if (qme.getDeclaration() == null && dynblock > 0) { out(qme.getIdentifier().getText(), "successor".equals(functionName) ? "++" : "--"); return; } String primaryVar = createRetainedTempVar(); String oldValueVar = createRetainedTempVar("old" + qme.getDeclaration().getName()); String applyFunc = String.format("%s.%s", oldValueVar, functionName); out("(", primaryVar, "="); qme.getPrimary().visit(this); out(",", oldValueVar, "=", memberAccess(qme, primaryVar), ","); generateMemberAccess(qme, applyFunc, primaryVar); out(",", oldValueVar, ")"); } } @Override public void visit(final UnionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".union("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final IntersectionOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".intersection("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final XorOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".exclusiveUnion("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(final ComplementOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.left(); out(".complement("); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getRightTerm().getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(Exists that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "exists("); termgen.term(); out(")"); } }); } @Override public void visit(Nonempty that) { unaryOp(that, new UnaryOpGenerator() { @Override public void generate(UnaryOpTermGenerator termgen) { out(clAlias, "nonempty("); termgen.term(); out(")"); } }); } //Don't know if we'll ever see this... @Override public void visit(ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(IfStatement that) { conds.generateIf(that); } @Override public void visit(WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, Type type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(clAlias, "isOfType("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); TypeUtils.typeNameOrList(term, type.getTypeModel(), this, true); out(")"); } @Override public void visit(IsOp that) { generateIsOfType(that.getTerm(), null, that.getType(), null, false); } @Override public void visit(Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final RangeOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { out(clAlias, "Range("); termgen.left(); out(","); termgen.right(); out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); } }); } @Override public void visit(ForStatement that) { if (opts.isComment()) { out("//'for' statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); if (that.getExits()) out("//EXITS!"); endLine(); } ForIterator foriter = that.getForClause().getForIterator(); final String itemVar = generateForLoop(foriter); boolean hasElse = that.getElseClause() != null && !that.getElseClause().getBlock().getStatements().isEmpty(); visitStatements(that.getForClause().getBlock().getStatements()); //If there's an else block, check for normal termination endBlock(); if (hasElse) { endLine(); out("if (", clAlias, "getFinished() === ", itemVar, ")"); encloseBlockInFunction(that.getElseClause().getBlock()); } } /** Generates code for the beginning of a "for" loop, returning the name of the variable used for the item. */ private String generateForLoop(ForIterator that) { SpecifierExpression iterable = that.getSpecifierExpression(); final String iterVar = names.createTempVariable("it"); final String itemVar; if (that instanceof ValueIterator) { itemVar = names.name(((ValueIterator)that).getVariable().getDeclarationModel()); } else { itemVar = names.createTempVariable("item"); } out("var ", iterVar, " = "); iterable.visit(this); out(".iterator();"); endLine(); out("var ", itemVar, ";while ((", itemVar, "=", iterVar, ".next())!==", clAlias, "getFinished())"); beginBlock(); if (that instanceof ValueIterator) { directAccess.add(((ValueIterator)that).getVariable().getDeclarationModel()); } else if (that instanceof KeyValueIterator) { String keyvar = names.name(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); String valvar = names.name(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); out("var ", keyvar, "=", itemVar, ".key;"); endLine(); out("var ", valvar, "=", itemVar, ".item;"); directAccess.add(((KeyValueIterator)that).getKeyVariable().getDeclarationModel()); directAccess.add(((KeyValueIterator)that).getValueVariable().getDeclarationModel()); endLine(); } return itemVar; } public void visit(InOp that) { binaryOp(that, new BinaryOpGenerator() { @Override public void generate(BinaryOpTermGenerator termgen) { termgen.right(); out(".contains("); termgen.left(); out(")"); } }); } @Override public void visit(TryCatchStatement that) { if (that.getErrors() != null && !that.getErrors().isEmpty()) return; List<Resource> resources = that.getTryClause().getResourceList() == null ? null : that.getTryClause().getResourceList().getResources(); if (resources != null && resources.isEmpty()) { resources = null; } List<String> resourceVars = null; String excVar = null; if (resources != null) { resourceVars = new ArrayList<>(resources.size()); for (Resource res : resources) { final String resourceVar = names.createTempVariable(res.getVariable().getIdentifier().getText()); out("var ", resourceVar, "=null"); endLine(true); out("var ", resourceVar, "$cls=false"); endLine(true); resourceVars.add(resourceVar); } excVar = names.createTempVariable(); out("var ", excVar, "$exc=null"); endLine(true); } out("try"); if (resources != null) { int pos = 0; out("{"); for (String resourceVar : resourceVars) { out(resourceVar, "="); resources.get(pos++).visit(this); endLine(true); out(resourceVar, ".open()"); endLine(true); out(resourceVar, "$cls=true"); endLine(true); } } encloseBlockInFunction(that.getTryClause().getBlock()); if (resources != null) { for (String resourceVar : resourceVars) { out(resourceVar, "$cls=false"); endLine(true); out(resourceVar, ".close()"); endLine(true); } out("}"); } if (!that.getCatchClauses().isEmpty() || resources != null) { String catchVarName = names.createTempVariable("ex"); out("catch(", catchVarName, ")"); beginBlock(); //Check if it's native and if so, wrap it out("if (", catchVarName, ".getT$name === undefined) ", catchVarName, "=", clAlias, "NativeException(", catchVarName, ")"); endLine(true); if (excVar != null) { out(excVar, "$exc=", catchVarName); endLine(true); } boolean firstCatch = true; for (CatchClause catchClause : that.getCatchClauses()) { Variable variable = catchClause.getCatchVariable().getVariable(); if (!firstCatch) { out("else "); } firstCatch = false; out("if("); generateIsOfType(variable, catchVarName, variable.getType(), null, false); out(")"); if (catchClause.getBlock().getStatements().isEmpty()) { out("{}"); } else { beginBlock(); directAccess.add(variable.getDeclarationModel()); names.forceName(variable.getDeclarationModel(), catchVarName); visitStatements(catchClause.getBlock().getStatements()); endBlockNewLine(); } } if (!that.getCatchClauses().isEmpty()) { out("else{throw ", catchVarName, "}"); } endBlockNewLine(); } if (that.getFinallyClause() != null || resources != null) { out("finally"); if (resources != null) { out("{"); for (String resourceVar : resourceVars) { out("try{if(",resourceVar, "$cls)", resourceVar, ".close(", excVar, "$exc);}catch(",resourceVar,"$swallow){}"); } } if (that.getFinallyClause() != null) { encloseBlockInFunction(that.getFinallyClause().getBlock()); } if (resources != null) { out("}"); } } } @Override public void visit(Throw that) { out("throw "); if (that.getExpression() != null) { that.getExpression().visit(this); } else { out(clAlias, "Exception()"); } out(";"); } private void visitIndex(IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { if (TypeUtils.isUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); ((Element)eor).getExpression().visit(this); out("]"); } else { out(".get("); ((Element)eor).getExpression().visit(this); out(")"); } } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".segment("); } if (er.getLowerBound() != null) { er.getLowerBound().visit(this); if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { er.getUpperBound().visit(this); } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(IndexExpression that) { visitIndex(that); } /** Generates code for a case clause, as part of a switch statement. Each case * is rendered as an if. */ private void caseClause(CaseClause cc, String expvar, Term switchTerm) { out("if ("); final CaseItem item = cc.getCaseItem(); if (item instanceof IsCase) { IsCase isCaseItem = (IsCase) item; generateIsOfType(switchTerm, expvar, isCaseItem.getType(), null, false); Variable caseVar = isCaseItem.getVariable(); if (caseVar != null) { directAccess.add(caseVar.getDeclarationModel()); names.forceName(caseVar.getDeclarationModel(), expvar); } } else if (item instanceof SatisfiesCase) { item.addError("case(satisfies) not yet supported"); out("true"); } else if (item instanceof MatchCase){ boolean first = true; for (Expression exp : ((MatchCase)item).getExpressionList().getExpressions()) { if (!first) out(" || "); out(expvar, "==="); //TODO equality? /*out(".equals(");*/ exp.visit(this); //out(")==="); clAlias(); out("getTrue()"); first = false; } } else { cc.addUnexpectedError("support for case of type " + cc.getClass().getSimpleName() + " not yet implemented"); } out(") "); encloseBlockInFunction(cc.getBlock()); } @Override public void visit(SwitchStatement that) { if (opts.isComment()) out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); //Put the expression in a tmp var final String expvar = names.createTempVariable("case"); out("var ", expvar, "="); Expression expr = that.getSwitchClause().getExpression(); expr.visit(this); endLine(true); //For each case, do an if boolean first = true; for (CaseClause cc : that.getSwitchCaseList().getCaseClauses()) { if (!first) out("else "); caseClause(cc, expvar, expr.getTerm()); first = false; } if (that.getSwitchCaseList().getElseClause() != null) { out("else "); that.getSwitchCaseList().getElseClause().visit(this); } if (opts.isComment()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final FunctionArgument that) { if (that.getBlock() == null) { singleExprFunction(that.getParameterLists(), that.getExpression(), that.getScope()); } else { multiStmtFunction(that.getParameterLists(), that.getBlock(), that.getScope()); } } private void multiStmtFunction(final List<ParameterList> paramLists, final Block block, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); visitStatements(block.getStatements()); endBlock(); } }); } private void singleExprFunction(final List<ParameterList> paramLists, final Expression expr, final Scope scope) { generateParameterLists(paramLists, scope, new ParameterListCallback() { @Override public void completeFunction() { beginBlock(); if (paramLists.size() == 1) { initSelf(scope); } initParameters(paramLists.get(paramLists.size()-1), null); out("return "); expr.visit(GenerateJsVisitor.this); out(";"); endBlock(); } }); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final MethodArgument that) { generateParameterLists(that.getParameterLists(), that.getScope(), new ParameterListCallback() { @Override public void completeFunction() { Block block = that.getBlock(); SpecifierExpression specExpr = that.getSpecifierExpression(); if (specExpr != null) { out("{return "); specExpr.getExpression().visit(GenerateJsVisitor.this); out(";}"); } else if (block != null) { block.visit(GenerateJsVisitor.this); } } }); } @Override public void visit(SegmentOp that) { String rhs = names.createTempVariable(); out("(function(){var ", rhs, "="); that.getRightTerm().visit(this); endLine(true); out("if (", rhs, ">0){"); endLine(); String lhs = names.createTempVariable(); String end = names.createTempVariable(); out("var ", lhs, "="); that.getLeftTerm().visit(this); endLine(true); out("var ", end, "=", lhs); endLine(true); out("for (var i=1; i<", rhs, "; i++){", end, "=", end, ".successor;}"); endLine(); out("return ", clAlias, "Range("); out(lhs, ",", end, ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), GenerateJsVisitor.this); out(")"); endLine(); out("}else return ", clAlias, "getEmpty();}())"); } /** Generates the code for single or multiple parameter lists, with a callback function to generate the function blocks. */ private void generateParameterLists(List<ParameterList> plist, Scope scope, ParameterListCallback callback) { if (plist.size() == 1) { out(function); ParameterList paramList = plist.get(0); paramList.visit(this); callback.completeFunction(); } else { int count=0; for (ParameterList paramList : plist) { if (count==0) { out(function); } else { //TODO add metamodel out("return function"); } paramList.visit(this); if (count == 0) { beginBlock(); initSelf(scope); initParameters(paramList, null); } else { out("{"); } count++; } callback.completeFunction(); for (int i=0; i < count; i++) { endBlock(false, i==count-1); } } } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(Block block) { boolean wrap=encloser.encloseBlock(block); if (wrap) { beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false;"); endLine(); out("var ", c.getBreakName(), "=false;"); endLine(); out("var ", c.getReturnName(), "=(function()"); } block.visit(this); if (wrap) { Continuation c = continues.pop(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if (", c.getBreakName(),"===true){break;}"); } endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable("cntvar"); rvar = names.createTempVariable("retvar"); bvar = names.createTempVariable("brkvar"); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } private static interface ParameterListCallback { void completeFunction(); } /** This interface is used inside type initialization method. */ private interface PrototypeInitCallback { void addToPrototypeCallback(); } @Override public void visit(Tuple that) { int count = 0; SequencedArgument sarg = that.getSequencedArgument(); if (sarg == null) { out(clAlias, "getEmpty()"); } else { List<Map<TypeParameter,ProducedType>> targs = new ArrayList<Map<TypeParameter,ProducedType>>(); List<PositionalArgument> positionalArguments = sarg.getPositionalArguments(); boolean spread = !positionalArguments.isEmpty() && positionalArguments.get(positionalArguments.size()-1) instanceof Tree.ListedArgument == false; int lim = positionalArguments.size()-1; for (PositionalArgument expr : positionalArguments) { if (count > 0) { out(","); } ProducedType exprType = expr.getTypeModel(); if (count==lim && spread) { if (exprType.getDeclaration().inherits(types.tuple)) { expr.visit(this); } else { expr.visit(this); out(".sequence"); } } else { out(clAlias, "Tuple("); if (count > 0) { for (Map.Entry<TypeParameter,ProducedType> e : targs.get(0).entrySet()) { if (e.getKey().getName().equals("Rest")) { targs.add(0, e.getValue().getTypeArguments()); } } } else { targs.add(that.getTypeModel().getTypeArguments()); } if (dynblock > 0 && TypeUtils.isUnknown(exprType) && expr instanceof ListedArgument) { exprType = types.anything.getType(); TypeUtils.generateDynamicCheck(((ListedArgument)expr).getExpression(), exprType, this); } else { expr.visit(this); } } count++; } if (!spread) { if (count > 0) { out(","); } out(clAlias, "getEmpty()"); } else { count--; } for (Map<TypeParameter,ProducedType> t : targs) { out(","); TypeUtils.printTypeArguments(that, t, this); out(")"); } } } @Override public void visit(Assertion that) { out("//assert"); location(that); String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)).getExpression().getTerm().getText(); } } } endLine(); StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, "if (!"); //escape custom = escapeStringLiteral(sb.toString()); out(") { throw ", clAlias, "AssertionException('", custom, "'); }"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1) { out("/*Begin dynamic block*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1) { out("/*End dynamic block*/"); endLine(); } dynblock--; } /** Closes a native array and invokes reifyCeylonType with the specified type parameters. */ void closeSequenceWithReifiedType(Node that, Map<TypeParameter,ProducedType> types) { out("].reifyCeylonType("); TypeUtils.printTypeArguments(that, types, this); out(")"); } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(TypeLiteral that) { out(clAlias, "typeLiteral$metamodel({Type:"); final StaticType type = that.getType(); final ProducedType pt = type.getTypeModel().resolveAliases(); TypeUtils.typeNameOrList(that, pt, this, true); out("})"); } }
diff --git a/src/com/aetrion/flickr/util/UrlUtilities.java b/src/com/aetrion/flickr/util/UrlUtilities.java index f6b1ce0..5725503 100644 --- a/src/com/aetrion/flickr/util/UrlUtilities.java +++ b/src/com/aetrion/flickr/util/UrlUtilities.java @@ -1,68 +1,68 @@ /* * Copyright (c) 2005 Aetrion LLC. */ package com.aetrion.flickr.util; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.aetrion.flickr.Parameter; import com.aetrion.flickr.RequestContext; import com.aetrion.flickr.auth.Auth; import com.aetrion.flickr.auth.AuthUtilities; /** * @author Anthony Eden */ public class UrlUtilities { /** * Build a request URL. * * @param host The host * @param port The port * @param path The path * @param parameters The parameters * @return The URL * @throws MalformedURLException */ public static URL buildUrl(String host, int port, String path, List parameters) throws MalformedURLException { StringBuffer buffer = new StringBuffer(); buffer.append("http://"); buffer.append(host); if (port > 0) { buffer.append(":"); buffer.append(port); } if (path == null) { path = "/"; } buffer.append(path); Iterator iter = parameters.iterator(); if (iter.hasNext()) { buffer.append("?"); } while (iter.hasNext()) { Parameter p = (Parameter) iter.next(); buffer.append(p.getName()); buffer.append("="); buffer.append(p.getValue()); if (iter.hasNext()) buffer.append("&"); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { - buffer.append("auth_token=" + auth.getToken()); - buffer.append("auth_sig=" + AuthUtilities.getSignature(parameters)); + buffer.append("&auth_token=" + auth.getToken()); + buffer.append("&auth_sig=" + AuthUtilities.getSignature(parameters)); } return new URL(buffer.toString()); } }
true
true
public static URL buildUrl(String host, int port, String path, List parameters) throws MalformedURLException { StringBuffer buffer = new StringBuffer(); buffer.append("http://"); buffer.append(host); if (port > 0) { buffer.append(":"); buffer.append(port); } if (path == null) { path = "/"; } buffer.append(path); Iterator iter = parameters.iterator(); if (iter.hasNext()) { buffer.append("?"); } while (iter.hasNext()) { Parameter p = (Parameter) iter.next(); buffer.append(p.getName()); buffer.append("="); buffer.append(p.getValue()); if (iter.hasNext()) buffer.append("&"); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { buffer.append("auth_token=" + auth.getToken()); buffer.append("auth_sig=" + AuthUtilities.getSignature(parameters)); } return new URL(buffer.toString()); }
public static URL buildUrl(String host, int port, String path, List parameters) throws MalformedURLException { StringBuffer buffer = new StringBuffer(); buffer.append("http://"); buffer.append(host); if (port > 0) { buffer.append(":"); buffer.append(port); } if (path == null) { path = "/"; } buffer.append(path); Iterator iter = parameters.iterator(); if (iter.hasNext()) { buffer.append("?"); } while (iter.hasNext()) { Parameter p = (Parameter) iter.next(); buffer.append(p.getName()); buffer.append("="); buffer.append(p.getValue()); if (iter.hasNext()) buffer.append("&"); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { buffer.append("&auth_token=" + auth.getToken()); buffer.append("&auth_sig=" + AuthUtilities.getSignature(parameters)); } return new URL(buffer.toString()); }
diff --git a/src/org/mozilla/javascript/NativeGenerator.java b/src/org/mozilla/javascript/NativeGenerator.java index 34d95a58..d008c6de 100755 --- a/src/org/mozilla/javascript/NativeGenerator.java +++ b/src/org/mozilla/javascript/NativeGenerator.java @@ -1,243 +1,244 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * This class implements generator objects. See * http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Generators * * @author Norris Boyd */ public final class NativeGenerator extends IdScriptableObject { private static final Object GENERATOR_TAG = new Object(); static NativeGenerator init(ScriptableObject scope, boolean sealed) { // Generator // Can't use "NativeGenerator().exportAsJSClass" since we don't want // to define "Generator" as a constructor in the top-level scope. NativeGenerator prototype = new NativeGenerator(); if (scope != null) { prototype.setParentScope(scope); prototype.setPrototype(getObjectPrototype(scope)); } prototype.activatePrototypeMap(MAX_PROTOTYPE_ID); if (sealed) { prototype.sealObject(); } // Need to access Generator prototype when constructing // Generator instances, but don't have a generator constructor // to use to find the prototype. Use the "associateValue" // approach instead. scope.associateValue(GENERATOR_TAG, prototype); return prototype; } /** * Only for constructing the prototype object. */ private NativeGenerator() { } public NativeGenerator(Scriptable scope, NativeFunction function, Object savedState) { this.function = function; this.savedState = savedState; // Set parent and prototype properties. Since we don't have a // "Generator" constructor in the top scope, we stash the // prototype in the top scope's associated value. Scriptable top = ScriptableObject.getTopLevelScope(scope); this.setParentScope(top); NativeGenerator prototype = (NativeGenerator) ScriptableObject.getTopScopeValue(top, GENERATOR_TAG); this.setPrototype(prototype); } public static final int GENERATOR_SEND = 0, GENERATOR_THROW = 1, GENERATOR_CLOSE = 2; public String getClassName() { return "Generator"; } protected void initPrototypeId(int id) { String s; int arity; switch (id) { case Id_close: arity=1; s="close"; break; case Id_next: arity=1; s="next"; break; case Id_send: arity=0; s="send"; break; case Id_throw: arity=0; s="throw"; break; case Id___iterator__: arity=1; s="__iterator__"; break; default: throw new IllegalArgumentException(String.valueOf(id)); } initPrototypeMethod(GENERATOR_TAG, id, s, arity); } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(GENERATOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (!(thisObj instanceof NativeGenerator)) throw incompatibleCallError(f); NativeGenerator generator = (NativeGenerator) thisObj; switch (id) { case Id_close: // need to run any pending finally clauses return generator.resume(cx, scope, GENERATOR_CLOSE, new GeneratorClosedException()); case Id_next: // arguments to next() are ignored generator.firstTime = false; return generator.resume(cx, scope, GENERATOR_SEND, Undefined.instance); - case Id_send: - if (generator.firstTime) { + case Id_send: { + Object arg = args.length > 0 ? args[0] : Undefined.instance; + if (generator.firstTime && !arg.equals(Undefined.instance)) { throw ScriptRuntime.typeError0("msg.send.newborn"); } - return generator.resume(cx, scope, GENERATOR_SEND, - args.length > 0 ? args[0] : Undefined.instance); + return generator.resume(cx, scope, GENERATOR_SEND, arg); + } case Id_throw: return generator.resume(cx, scope, GENERATOR_THROW, args.length > 0 ? args[0] : Undefined.instance); case Id___iterator__: return thisObj; default: throw new IllegalArgumentException(String.valueOf(id)); } } private Object resume(Context cx, Scriptable scope, int operation, Object value) { if (savedState == null) { if (operation == GENERATOR_CLOSE) return Undefined.instance; Object thrown; if (operation == GENERATOR_THROW) { thrown = value; } else { Scriptable top = ScriptableObject.getTopLevelScope(scope); thrown = top.get(NativeIterator.STOP_ITERATION, scope); } throw new JavaScriptException(thrown, lineSource, lineNumber); } try { synchronized (this) { // generator execution is necessarily single-threaded and // non-reentrant. // See https://bugzilla.mozilla.org/show_bug.cgi?id=349263 if (locked) throw ScriptRuntime.typeError0("msg.already.exec.gen"); locked = true; } return function.resumeGenerator(cx, scope, operation, savedState, value); } catch (GeneratorClosedException e) { // On closing a generator in the compile path, the generator // throws a special execption. This ensures execution of all pending // finalisers and will not get caught by user code. return Undefined.instance; } catch (RhinoException e) { lineNumber = e.lineNumber(); lineSource = e.lineSource(); savedState = null; throw e; } finally { synchronized (this) { locked = false; } if (operation == GENERATOR_CLOSE) savedState = null; } } // #string_id_map# protected int findPrototypeId(String s) { int id; // #generated# Last update: 2007-06-14 13:13:03 EDT L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==4) { c=s.charAt(0); if (c=='n') { X="next";id=Id_next; } else if (c=='s') { X="send";id=Id_send; } } else if (s_length==5) { c=s.charAt(0); if (c=='c') { X="close";id=Id_close; } else if (c=='t') { X="throw";id=Id_throw; } } else if (s_length==12) { X="__iterator__";id=Id___iterator__; } if (X!=null && X!=s && !X.equals(s)) id = 0; break L0; } // #/generated# return id; } private static final int Id_close = 1, Id_next = 2, Id_send = 3, Id_throw = 4, Id___iterator__ = 5, MAX_PROTOTYPE_ID = 5; // #/string_id_map# private NativeFunction function; private Object savedState; private String lineSource; private int lineNumber; private boolean firstTime = true; private boolean locked; public static class GeneratorClosedException extends RuntimeException { } }
false
true
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(GENERATOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (!(thisObj instanceof NativeGenerator)) throw incompatibleCallError(f); NativeGenerator generator = (NativeGenerator) thisObj; switch (id) { case Id_close: // need to run any pending finally clauses return generator.resume(cx, scope, GENERATOR_CLOSE, new GeneratorClosedException()); case Id_next: // arguments to next() are ignored generator.firstTime = false; return generator.resume(cx, scope, GENERATOR_SEND, Undefined.instance); case Id_send: if (generator.firstTime) { throw ScriptRuntime.typeError0("msg.send.newborn"); } return generator.resume(cx, scope, GENERATOR_SEND, args.length > 0 ? args[0] : Undefined.instance); case Id_throw: return generator.resume(cx, scope, GENERATOR_THROW, args.length > 0 ? args[0] : Undefined.instance); case Id___iterator__: return thisObj; default: throw new IllegalArgumentException(String.valueOf(id)); } }
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(GENERATOR_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); if (!(thisObj instanceof NativeGenerator)) throw incompatibleCallError(f); NativeGenerator generator = (NativeGenerator) thisObj; switch (id) { case Id_close: // need to run any pending finally clauses return generator.resume(cx, scope, GENERATOR_CLOSE, new GeneratorClosedException()); case Id_next: // arguments to next() are ignored generator.firstTime = false; return generator.resume(cx, scope, GENERATOR_SEND, Undefined.instance); case Id_send: { Object arg = args.length > 0 ? args[0] : Undefined.instance; if (generator.firstTime && !arg.equals(Undefined.instance)) { throw ScriptRuntime.typeError0("msg.send.newborn"); } return generator.resume(cx, scope, GENERATOR_SEND, arg); } case Id_throw: return generator.resume(cx, scope, GENERATOR_THROW, args.length > 0 ? args[0] : Undefined.instance); case Id___iterator__: return thisObj; default: throw new IllegalArgumentException(String.valueOf(id)); } }
diff --git a/src/minecraft/ljdp/minechem/common/items/ItemHangableTableOfElements.java b/src/minecraft/ljdp/minechem/common/items/ItemHangableTableOfElements.java index 4371144..a932c7c 100644 --- a/src/minecraft/ljdp/minechem/common/items/ItemHangableTableOfElements.java +++ b/src/minecraft/ljdp/minechem/common/items/ItemHangableTableOfElements.java @@ -1,62 +1,62 @@ package ljdp.minechem.common.items; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import ljdp.minechem.common.ModMinechem; import ljdp.minechem.common.entity.EntityTableOfElements; import net.minecraft.entity.EntityHanging; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.world.World; public class ItemHangableTableOfElements extends Item { public ItemHangableTableOfElements(int id) { super(id); this.setUnlocalizedName("minechem.itemPeriodicTable"); setCreativeTab(ModMinechem.minechemTab); } @Override public boolean onItemUse(ItemStack itemstack, EntityPlayer entityPlayer, World world, int x, int y, int z, int side, float par8, float par9, float par10) { if (side == 0) return false; else if (side == 1) return false; else { - int orientation = Direction.directionToFacing[side]; + int orientation = Direction.facingToDirection[side]; EntityHanging hangingEntity = this.createHangingEntity(world, x, y, z, orientation); if (!entityPlayer.canPlayerEdit(x, y, z, side, itemstack)) return false; else { if (hangingEntity != null && hangingEntity.onValidSurface()) { if (!world.isRemote) world.spawnEntityInWorld(hangingEntity); --itemstack.stackSize; } return true; } } } private EntityHanging createHangingEntity(World world, int x, int y, int z, int orientation) { return new EntityTableOfElements(world, x, y, z, orientation); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemstack, EntityPlayer entityPlayer, List list, boolean par4) { list.add("Dimensions: 9 x 5"); } }
true
true
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityPlayer, World world, int x, int y, int z, int side, float par8, float par9, float par10) { if (side == 0) return false; else if (side == 1) return false; else { int orientation = Direction.directionToFacing[side]; EntityHanging hangingEntity = this.createHangingEntity(world, x, y, z, orientation); if (!entityPlayer.canPlayerEdit(x, y, z, side, itemstack)) return false; else { if (hangingEntity != null && hangingEntity.onValidSurface()) { if (!world.isRemote) world.spawnEntityInWorld(hangingEntity); --itemstack.stackSize; } return true; } } }
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityPlayer, World world, int x, int y, int z, int side, float par8, float par9, float par10) { if (side == 0) return false; else if (side == 1) return false; else { int orientation = Direction.facingToDirection[side]; EntityHanging hangingEntity = this.createHangingEntity(world, x, y, z, orientation); if (!entityPlayer.canPlayerEdit(x, y, z, side, itemstack)) return false; else { if (hangingEntity != null && hangingEntity.onValidSurface()) { if (!world.isRemote) world.spawnEntityInWorld(hangingEntity); --itemstack.stackSize; } return true; } } }
diff --git a/plugins/org.eclipse.viatra2.emf.incquery.tooling.gui/src/org/eclipse/viatra2/emf/incquery/queryexplorer/content/matcher/ObservablePatternMatcherRoot.java b/plugins/org.eclipse.viatra2.emf.incquery.tooling.gui/src/org/eclipse/viatra2/emf/incquery/queryexplorer/content/matcher/ObservablePatternMatcherRoot.java index 27fd2d44..1931a2f2 100644 --- a/plugins/org.eclipse.viatra2.emf.incquery.tooling.gui/src/org/eclipse/viatra2/emf/incquery/queryexplorer/content/matcher/ObservablePatternMatcherRoot.java +++ b/plugins/org.eclipse.viatra2.emf.incquery.tooling.gui/src/org/eclipse/viatra2/emf/incquery/queryexplorer/content/matcher/ObservablePatternMatcherRoot.java @@ -1,110 +1,110 @@ package org.eclipse.viatra2.emf.incquery.queryexplorer.content.matcher; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.ui.IEditorPart; import org.eclipse.viatra2.emf.incquery.gui.IncQueryGUIPlugin; import org.eclipse.viatra2.emf.incquery.queryexplorer.QueryExplorer; import org.eclipse.viatra2.emf.incquery.runtime.api.GenericPatternMatch; import org.eclipse.viatra2.emf.incquery.runtime.api.GenericPatternMatcher; import org.eclipse.viatra2.emf.incquery.runtime.api.IPatternMatch; import org.eclipse.viatra2.emf.incquery.runtime.api.IncQueryMatcher; import org.eclipse.viatra2.emf.incquery.runtime.exception.IncQueryRuntimeException; import org.eclipse.viatra2.patternlanguage.core.helper.CorePatternLanguageHelper; import org.eclipse.viatra2.patternlanguage.core.patternLanguage.Pattern; /** * Each IEditingDomainProvider will be associated a PatternMatcherRoot element in the tree viewer. * PatterMatcherRoots are indexed with a ViewerRootKey. * * It's children element will be PatterMatchers. * * @author Tamas Szabo * */ public class ObservablePatternMatcherRoot { private Map<String, ObservablePatternMatcher> matchers; private MatcherTreeViewerRootKey key; private ILog logger = IncQueryGUIPlugin.getDefault().getLog(); public ObservablePatternMatcherRoot(MatcherTreeViewerRootKey key) { matchers = new HashMap<String, ObservablePatternMatcher>(); this.key = key; } public void addMatcher(IncQueryMatcher<? extends IPatternMatch> matcher, String patternFqn, boolean generated) { @SuppressWarnings("unchecked") //This cast could not be avoided because later the filtered delta monitor will need the base IPatternMatch ObservablePatternMatcher pm = new ObservablePatternMatcher(this, (IncQueryMatcher<IPatternMatch>) matcher, patternFqn, generated); this.matchers.put(patternFqn, pm); QueryExplorer.getInstance().getMatcherTreeViewer().refresh(this); } public void removeMatcher(String patternFqn) { //if the pattern is first deactivated then removed, than the matcher corresponding matcher is disposed ObservablePatternMatcher matcher = this.matchers.get(patternFqn); if (matcher != null) { this.matchers.get(patternFqn).dispose(); this.matchers.remove(patternFqn); QueryExplorer.getInstance().getMatcherTreeViewer().refresh(this); } } public static final String MATCHERS_ID = "matchers"; public List<ObservablePatternMatcher> getMatchers() { return new ArrayList<ObservablePatternMatcher>(matchers.values()); } public String getText() { return key.toString(); } public void dispose() { for (ObservablePatternMatcher pm : this.matchers.values()) { pm.dispose(); } } public MatcherTreeViewerRootKey getKey() { return key; } public IEditorPart getEditorPart() { return this.key.getEditor(); } public Notifier getNotifier() { return this.key.getNotifier(); } public void registerPattern(Pattern pattern) { IncQueryMatcher<GenericPatternMatch> matcher = null; try { matcher = new GenericPatternMatcher(pattern, key.getNotifier()); } catch (IncQueryRuntimeException e) { logger.log(new Status(IStatus.ERROR, IncQueryGUIPlugin.PLUGIN_ID, "Cannot initialize pattern matcher for pattern " + pattern.getName(), e)); matcher = null; } - addMatcher(matcher, CorePatternLanguageHelper.getFullyQualifiedName(pattern), false); + if (matcher!=null) addMatcher(matcher, CorePatternLanguageHelper.getFullyQualifiedName(pattern), false); } public void unregisterPattern(Pattern pattern) { removeMatcher(CorePatternLanguageHelper.getFullyQualifiedName(pattern)); } }
true
true
public void registerPattern(Pattern pattern) { IncQueryMatcher<GenericPatternMatch> matcher = null; try { matcher = new GenericPatternMatcher(pattern, key.getNotifier()); } catch (IncQueryRuntimeException e) { logger.log(new Status(IStatus.ERROR, IncQueryGUIPlugin.PLUGIN_ID, "Cannot initialize pattern matcher for pattern " + pattern.getName(), e)); matcher = null; } addMatcher(matcher, CorePatternLanguageHelper.getFullyQualifiedName(pattern), false); }
public void registerPattern(Pattern pattern) { IncQueryMatcher<GenericPatternMatch> matcher = null; try { matcher = new GenericPatternMatcher(pattern, key.getNotifier()); } catch (IncQueryRuntimeException e) { logger.log(new Status(IStatus.ERROR, IncQueryGUIPlugin.PLUGIN_ID, "Cannot initialize pattern matcher for pattern " + pattern.getName(), e)); matcher = null; } if (matcher!=null) addMatcher(matcher, CorePatternLanguageHelper.getFullyQualifiedName(pattern), false); }
diff --git a/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java b/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java index 3cea6d57aaf..5f5553ecdd0 100644 --- a/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java +++ b/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java @@ -1,411 +1,412 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.client.transport; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoAction; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; /** * */ public class TransportClientNodesService extends AbstractComponent { private final TimeValue nodesSamplerInterval; private final long pingTimeout; private final ClusterName clusterName; private final TransportService transportService; private final ThreadPool threadPool; // nodes that are added to be discovered private volatile ImmutableList<DiscoveryNode> listedNodes = ImmutableList.of(); private final Object transportMutex = new Object(); private volatile ImmutableList<DiscoveryNode> nodes = ImmutableList.of(); private final AtomicInteger tempNodeIdGenerator = new AtomicInteger(); private final NodeSampler nodesSampler; private volatile ScheduledFuture nodesSamplerFuture; private final AtomicInteger randomNodeGenerator = new AtomicInteger(); private volatile boolean closed; @Inject public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService, ThreadPool threadPool) { super(settings); this.clusterName = clusterName; this.transportService = transportService; this.threadPool = threadPool; this.nodesSamplerInterval = componentSettings.getAsTime("nodes_sampler_interval", timeValueSeconds(5)); this.pingTimeout = componentSettings.getAsTime("ping_timeout", timeValueSeconds(5)).millis(); if (logger.isDebugEnabled()) { logger.debug("node_sampler_interval[" + nodesSamplerInterval + "]"); } if (componentSettings.getAsBoolean("sniff", false)) { this.nodesSampler = new SniffNodesSampler(); } else { this.nodesSampler = new SimpleNodeSampler(); } this.nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, new ScheduledNodeSampler()); // we want the transport service to throw connect exceptions, so we can retry transportService.throwConnectException(true); } public ImmutableList<TransportAddress> transportAddresses() { ImmutableList.Builder<TransportAddress> lstBuilder = ImmutableList.builder(); for (DiscoveryNode listedNode : listedNodes) { lstBuilder.add(listedNode.address()); } return lstBuilder.build(); } public ImmutableList<DiscoveryNode> connectedNodes() { return this.nodes; } public TransportClientNodesService addTransportAddress(TransportAddress transportAddress) { synchronized (transportMutex) { ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder(); listedNodes = builder.addAll(listedNodes).add(new DiscoveryNode("#transport#-" + tempNodeIdGenerator.incrementAndGet(), transportAddress)).build(); } nodesSampler.sample(); return this; } public TransportClientNodesService removeTransportAddress(TransportAddress transportAddress) { synchronized (transportMutex) { ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder(); for (DiscoveryNode otherNode : listedNodes) { if (!otherNode.address().equals(transportAddress)) { builder.add(otherNode); } } listedNodes = builder.build(); } nodesSampler.sample(); return this; } public <T> T execute(NodeCallback<T> callback) throws ElasticSearchException { ImmutableList<DiscoveryNode> nodes = this.nodes; if (nodes.isEmpty()) { throw new NoNodeAvailableException(); } int index = randomNodeGenerator.incrementAndGet(); if (index < 0) { index = 0; randomNodeGenerator.set(0); } for (int i = 0; i < nodes.size(); i++) { DiscoveryNode node = nodes.get((index + i) % nodes.size()); try { return callback.doWithNode(node); } catch (ElasticSearchException e) { if (!(e.unwrapCause() instanceof ConnectTransportException)) { throw e; } } } throw new NoNodeAvailableException(); } public <Response> void execute(NodeListenerCallback<Response> callback, ActionListener<Response> listener) throws ElasticSearchException { ImmutableList<DiscoveryNode> nodes = this.nodes; if (nodes.isEmpty()) { throw new NoNodeAvailableException(); } int index = randomNodeGenerator.incrementAndGet(); if (index < 0) { index = 0; randomNodeGenerator.set(0); } RetryListener<Response> retryListener = new RetryListener<Response>(callback, listener, nodes, index); try { callback.doWithNode(nodes.get((index) % nodes.size()), retryListener); } catch (ElasticSearchException e) { if (e.unwrapCause() instanceof ConnectTransportException) { retryListener.onFailure(e); } else { throw e; } } } public static class RetryListener<Response> implements ActionListener<Response> { private final NodeListenerCallback<Response> callback; private final ActionListener<Response> listener; private final ImmutableList<DiscoveryNode> nodes; private final int index; private volatile int i; public RetryListener(NodeListenerCallback<Response> callback, ActionListener<Response> listener, ImmutableList<DiscoveryNode> nodes, int index) { this.callback = callback; this.listener = listener; this.nodes = nodes; this.index = index; } @Override public void onResponse(Response response) { listener.onResponse(response); } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof ConnectTransportException) { int i = ++this.i; if (i == nodes.size()) { listener.onFailure(new NoNodeAvailableException()); } else { try { callback.doWithNode(nodes.get((index + i) % nodes.size()), this); } catch (Exception e1) { // retry the next one... onFailure(e); } } } else { listener.onFailure(e); } } } public void close() { closed = true; nodesSamplerFuture.cancel(true); for (DiscoveryNode node : nodes) { transportService.disconnectFromNode(node); } for (DiscoveryNode listedNode : listedNodes) { transportService.disconnectFromNode(listedNode); } nodes = ImmutableList.of(); } interface NodeSampler { void sample(); } class ScheduledNodeSampler implements Runnable { @Override public void run() { try { nodesSampler.sample(); if (!closed) { nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, this); } } catch (Exception e) { logger.warn("failed to sample", e); } } } class SimpleNodeSampler implements NodeSampler { @Override public synchronized void sample() { if (closed) { return; } HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(); for (DiscoveryNode node : listedNodes) { if (!transportService.nodeConnected(node)) { try { transportService.connectToNode(node); } catch (Exception e) { logger.debug("failed to connect to node [{}], removed from nodes list", e, node); continue; } } try { NodesInfoResponse nodeInfo = transportService.submitRequest(node, NodesInfoAction.NAME, Requests.nodesInfoRequest("_local"), TransportRequestOptions.options().withTimeout(pingTimeout), new FutureTransportResponseHandler<NodesInfoResponse>() { @Override public NodesInfoResponse newInstance() { return new NodesInfoResponse(); } }).txGet(); if (!clusterName.equals(nodeInfo.clusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", node, clusterName); } else { newNodes.add(node); } } catch (Exception e) { logger.info("failed to get node info for {}, disconnecting...", e, node); transportService.disconnectFromNode(node); } } nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build(); } } class SniffNodesSampler implements NodeSampler { @Override public synchronized void sample() { if (closed) { return; } // the nodes we are going to ping include the core listed nodes that were added // and the last round of discovered nodes Map<TransportAddress, DiscoveryNode> nodesToPing = Maps.newHashMap(); for (DiscoveryNode node : listedNodes) { nodesToPing.put(node.address(), node); } for (DiscoveryNode node : nodes) { nodesToPing.put(node.address(), node); } final CountDownLatch latch = new CountDownLatch(nodesToPing.size()); final CopyOnWriteArrayList<NodesInfoResponse> nodesInfoResponses = new CopyOnWriteArrayList<NodesInfoResponse>(); for (final DiscoveryNode listedNode : nodesToPing.values()) { threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!transportService.nodeConnected(listedNode)) { try { transportService.connectToNode(listedNode); } catch (Exception e) { - logger.debug("failed to connect to node [{}], removed from nodes list", e, listedNode); + logger.debug("failed to connect to node [{}], ignoring...", e, listedNode); + latch.countDown(); return; } } transportService.sendRequest(listedNode, NodesInfoAction.NAME, Requests.nodesInfoRequest("_all"), TransportRequestOptions.options().withTimeout(pingTimeout), new BaseTransportResponseHandler<NodesInfoResponse>() { @Override public NodesInfoResponse newInstance() { return new NodesInfoResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(NodesInfoResponse response) { nodesInfoResponses.add(response); latch.countDown(); } @Override public void handleException(TransportException e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } }); } catch (Exception e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { return; } HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(); for (NodesInfoResponse nodesInfoResponse : nodesInfoResponses) { for (NodeInfo nodeInfo : nodesInfoResponse) { if (!clusterName.equals(nodesInfoResponse.clusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", nodeInfo.node(), clusterName); } else { if (nodeInfo.node().dataNode()) { // only add data nodes to connect to newNodes.add(nodeInfo.node()); } } } } // now, make sure we are connected to all the updated nodes for (Iterator<DiscoveryNode> it = newNodes.iterator(); it.hasNext(); ) { DiscoveryNode node = it.next(); try { transportService.connectToNode(node); } catch (Exception e) { it.remove(); logger.debug("failed to connect to discovered node [" + node + "]", e); } } nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build(); } } public static interface NodeCallback<T> { T doWithNode(DiscoveryNode node) throws ElasticSearchException; } public static interface NodeListenerCallback<Response> { void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticSearchException; } }
true
true
public synchronized void sample() { if (closed) { return; } // the nodes we are going to ping include the core listed nodes that were added // and the last round of discovered nodes Map<TransportAddress, DiscoveryNode> nodesToPing = Maps.newHashMap(); for (DiscoveryNode node : listedNodes) { nodesToPing.put(node.address(), node); } for (DiscoveryNode node : nodes) { nodesToPing.put(node.address(), node); } final CountDownLatch latch = new CountDownLatch(nodesToPing.size()); final CopyOnWriteArrayList<NodesInfoResponse> nodesInfoResponses = new CopyOnWriteArrayList<NodesInfoResponse>(); for (final DiscoveryNode listedNode : nodesToPing.values()) { threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!transportService.nodeConnected(listedNode)) { try { transportService.connectToNode(listedNode); } catch (Exception e) { logger.debug("failed to connect to node [{}], removed from nodes list", e, listedNode); return; } } transportService.sendRequest(listedNode, NodesInfoAction.NAME, Requests.nodesInfoRequest("_all"), TransportRequestOptions.options().withTimeout(pingTimeout), new BaseTransportResponseHandler<NodesInfoResponse>() { @Override public NodesInfoResponse newInstance() { return new NodesInfoResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(NodesInfoResponse response) { nodesInfoResponses.add(response); latch.countDown(); } @Override public void handleException(TransportException e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } }); } catch (Exception e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { return; } HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(); for (NodesInfoResponse nodesInfoResponse : nodesInfoResponses) { for (NodeInfo nodeInfo : nodesInfoResponse) { if (!clusterName.equals(nodesInfoResponse.clusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", nodeInfo.node(), clusterName); } else { if (nodeInfo.node().dataNode()) { // only add data nodes to connect to newNodes.add(nodeInfo.node()); } } } } // now, make sure we are connected to all the updated nodes for (Iterator<DiscoveryNode> it = newNodes.iterator(); it.hasNext(); ) { DiscoveryNode node = it.next(); try { transportService.connectToNode(node); } catch (Exception e) { it.remove(); logger.debug("failed to connect to discovered node [" + node + "]", e); } } nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build(); }
public synchronized void sample() { if (closed) { return; } // the nodes we are going to ping include the core listed nodes that were added // and the last round of discovered nodes Map<TransportAddress, DiscoveryNode> nodesToPing = Maps.newHashMap(); for (DiscoveryNode node : listedNodes) { nodesToPing.put(node.address(), node); } for (DiscoveryNode node : nodes) { nodesToPing.put(node.address(), node); } final CountDownLatch latch = new CountDownLatch(nodesToPing.size()); final CopyOnWriteArrayList<NodesInfoResponse> nodesInfoResponses = new CopyOnWriteArrayList<NodesInfoResponse>(); for (final DiscoveryNode listedNode : nodesToPing.values()) { threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!transportService.nodeConnected(listedNode)) { try { transportService.connectToNode(listedNode); } catch (Exception e) { logger.debug("failed to connect to node [{}], ignoring...", e, listedNode); latch.countDown(); return; } } transportService.sendRequest(listedNode, NodesInfoAction.NAME, Requests.nodesInfoRequest("_all"), TransportRequestOptions.options().withTimeout(pingTimeout), new BaseTransportResponseHandler<NodesInfoResponse>() { @Override public NodesInfoResponse newInstance() { return new NodesInfoResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(NodesInfoResponse response) { nodesInfoResponses.add(response); latch.countDown(); } @Override public void handleException(TransportException e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } }); } catch (Exception e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { return; } HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(); for (NodesInfoResponse nodesInfoResponse : nodesInfoResponses) { for (NodeInfo nodeInfo : nodesInfoResponse) { if (!clusterName.equals(nodesInfoResponse.clusterName())) { logger.warn("node {} not part of the cluster {}, ignoring...", nodeInfo.node(), clusterName); } else { if (nodeInfo.node().dataNode()) { // only add data nodes to connect to newNodes.add(nodeInfo.node()); } } } } // now, make sure we are connected to all the updated nodes for (Iterator<DiscoveryNode> it = newNodes.iterator(); it.hasNext(); ) { DiscoveryNode node = it.next(); try { transportService.connectToNode(node); } catch (Exception e) { it.remove(); logger.debug("failed to connect to discovered node [" + node + "]", e); } } nodes = new ImmutableList.Builder<DiscoveryNode>().addAll(newNodes).build(); }
diff --git a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java index 21f7cc630..e5440189a 100644 --- a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java +++ b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java @@ -1,566 +1,565 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.ingest; import java.awt.Component; import org.sleuthkit.autopsy.corecomponents.AdvancedConfigurationDialog; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import org.sleuthkit.autopsy.casemodule.IngestConfigurator; import org.sleuthkit.autopsy.ingest.IngestManager.UpdateFrequency; import org.sleuthkit.datamodel.Image; /** * main configuration panel for all ingest services, reusable JPanel component */ public class IngestDialogPanel extends javax.swing.JPanel implements IngestConfigurator { private IngestManager manager = null; private List<IngestServiceAbstract> services; private IngestServiceAbstract currentService; private Map<String, Boolean> serviceStates; private ServicesTableModel tableModel; private static final Logger logger = Logger.getLogger(IngestDialogPanel.class.getName()); // The image that's just been added to the database private Image image; private static IngestDialogPanel instance = null; /** Creates new form IngestDialogPanel */ private IngestDialogPanel() { tableModel = new ServicesTableModel(); services = new ArrayList<IngestServiceAbstract>(); serviceStates = new HashMap<String, Boolean>(); initComponents(); customizeComponents(); } synchronized static IngestDialogPanel getDefault() { if (instance == null) { instance = new IngestDialogPanel(); } return instance; } private void customizeComponents() { servicesTable.setModel(tableModel); this.manager = IngestManager.getDefault(); Collection<IngestServiceImage> imageServices = IngestManager.enumerateImageServices(); for (final IngestServiceImage service : imageServices) { addService(service); } Collection<IngestServiceAbstractFile> fsServices = IngestManager.enumerateAbstractFileServices(); for (final IngestServiceAbstractFile service : fsServices) { addService(service); } //time setting timeGroup.add(timeRadioButton1); timeGroup.add(timeRadioButton2); timeGroup.add(timeRadioButton3); if (manager.isIngestRunning()) { setTimeSettingEnabled(false); } else { setTimeSettingEnabled(true); } //set default final UpdateFrequency curFreq = manager.getUpdateFrequency(); switch (curFreq) { case FAST: timeRadioButton1.setSelected(true); break; case AVG: timeRadioButton2.setSelected(true); break; case SLOW: timeRadioButton3.setSelected(true); break; default: // } servicesTable.setTableHeader(null); servicesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //custom renderer for tooltips ServiceTableRenderer renderer = new ServiceTableRenderer(); //customize column witdhs final int width = servicesScrollPane.getPreferredSize().width; TableColumn column = null; for (int i = 0; i < servicesTable.getColumnCount(); i++) { column = servicesTable.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(((int) (width * 0.15))); } else { column.setCellRenderer(renderer); column.setPreferredWidth(((int) (width * 0.84))); } } servicesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource(); if (!listSelectionModel.isSelectionEmpty()) { save(); int index = listSelectionModel.getMinSelectionIndex(); currentService = services.get(index); reloadSimpleConfiguration(); advancedButton.setEnabled(currentService.hasAdvancedConfiguration()); } else { currentService = null; } } }); processUnallocCheckbox.setSelected(manager.getProcessUnallocSpace()); } private void setTimeSettingEnabled(boolean enabled) { timeRadioButton1.setEnabled(enabled); timeRadioButton2.setEnabled(enabled); timeRadioButton3.setEnabled(enabled); } private void setProcessUnallocSpaceEnabled(boolean enabled) { processUnallocCheckbox.setEnabled(enabled); } @Override public void paint(Graphics g) { super.paint(g); if (manager.isIngestRunning()) { setTimeSettingEnabled(false); setProcessUnallocSpaceEnabled(false); } else { setTimeSettingEnabled(true); setProcessUnallocSpaceEnabled(true); } } private void addService(IngestServiceAbstract service) { final String serviceName = service.getName(); services.add(service); serviceStates.put(serviceName, true); } /** 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup() - .addGap(0, 0, Short.MAX_VALUE) + .addGroup(timePanelLayout.createSequentialGroup() + .addGap(0, 0, 0) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) - .addComponent(timeRadioButton3)) - .addGap(0, 0, Short.MAX_VALUE))) - .addContainerGap()) + .addComponent(timeRadioButton3)))) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N processUnallocCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.toolTipText")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void advancedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advancedButtonActionPerformed final AdvancedConfigurationDialog dialog = new AdvancedConfigurationDialog(); dialog.addApplyButtonListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.close(); currentService.saveAdvancedConfiguration(); reloadSimpleConfiguration(); } }); dialog.display(currentService.getAdvancedConfiguration()); }//GEN-LAST:event_advancedButtonActionPerformed private void timeRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeRadioButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_timeRadioButton1ActionPerformed private void processUnallocCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processUnallocCheckboxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_processUnallocCheckboxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton advancedButton; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator2; private javax.swing.JCheckBox processUnallocCheckbox; private javax.swing.JPanel processUnallocPanel; private javax.swing.JScrollPane servicesScrollPane; private javax.swing.JTable servicesTable; private javax.swing.JPanel simplePanel; private javax.swing.ButtonGroup timeGroup; private javax.swing.JLabel timeLabel; private javax.swing.JPanel timePanel; private javax.swing.JRadioButton timeRadioButton1; private javax.swing.JRadioButton timeRadioButton2; private javax.swing.JRadioButton timeRadioButton3; // End of variables declaration//GEN-END:variables private class ServicesTableModel extends AbstractTableModel { @Override public int getRowCount() { return services.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { String name = services.get(rowIndex).getName(); if (columnIndex == 0) { return serviceStates.get(name); } else { return name; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 0) { serviceStates.put((String) getValueAt(rowIndex, 1), (Boolean) aValue); } } @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } } List<IngestServiceAbstract> getServicesToStart() { List<IngestServiceAbstract> servicesToStart = new ArrayList<IngestServiceAbstract>(); for (IngestServiceAbstract service : services) { boolean serviceEnabled = serviceStates.get(service.getName()); if (serviceEnabled) { servicesToStart.add(service); } } return servicesToStart; } private boolean timeSelectionEnabled() { return timeRadioButton1.isEnabled() && timeRadioButton2.isEnabled() && timeRadioButton3.isEnabled(); } private boolean processUnallocSpaceEnabled() { return processUnallocCheckbox.isEnabled(); } private UpdateFrequency getSelectedTimeValue() { if (timeRadioButton1.isSelected()) { return UpdateFrequency.FAST; } else if (timeRadioButton2.isSelected()) { return UpdateFrequency.AVG; } else { return UpdateFrequency.SLOW; } } private void reloadSimpleConfiguration() { simplePanel.removeAll(); if (currentService.hasSimpleConfiguration()) { simplePanel.add(currentService.getSimpleConfiguration()); } simplePanel.revalidate(); simplePanel.repaint(); } /** * To be called whenever the next, close, or start buttons are pressed. * */ @Override public void save() { if (currentService != null && currentService.hasSimpleConfiguration()) { currentService.saveSimpleConfiguration(); } } @Override public JPanel getIngestConfigPanel() { return this; } @Override public void setImage(Image image) { this.image = image; } @Override public void start() { //pick the services List<IngestServiceAbstract> servicesToStart = getServicesToStart(); if (!servicesToStart.isEmpty()) { manager.execute(servicesToStart, image); } //update ingest freq. refresh if (timeSelectionEnabled()) { manager.setUpdateFrequency(getSelectedTimeValue()); } //update ingest proc. unalloc space if (processUnallocSpaceEnabled() ) { manager.setProcessUnallocSpace(processUnallocCheckbox.isSelected()); } } @Override public boolean isIngestRunning() { return manager.isIngestRunning(); } /** * Custom cell renderer for tooltips with service description */ private class ServiceTableRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 1) { //String serviceName = (String) table.getModel().getValueAt(row, column); IngestServiceAbstract service = services.get(row); String serviceDescr = service.getDescription(); setToolTipText(serviceDescr); } return this; } } }
false
true
private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) .addComponent(timeRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N processUnallocCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.toolTipText")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { timeGroup = new javax.swing.ButtonGroup(); servicesScrollPane = new javax.swing.JScrollPane(); servicesTable = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); advancedButton = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane1 = new javax.swing.JScrollPane(); simplePanel = new javax.swing.JPanel(); timePanel = new javax.swing.JPanel(); timeRadioButton3 = new javax.swing.JRadioButton(); timeRadioButton2 = new javax.swing.JRadioButton(); timeLabel = new javax.swing.JLabel(); timeRadioButton1 = new javax.swing.JRadioButton(); processUnallocPanel = new javax.swing.JPanel(); processUnallocCheckbox = new javax.swing.JCheckBox(); setPreferredSize(new java.awt.Dimension(522, 257)); servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160)); servicesTable.setBackground(new java.awt.Color(240, 240, 240)); servicesTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); servicesTable.setShowHorizontalLines(false); servicesTable.setShowVerticalLines(false); servicesScrollPane.setViewportView(servicesTable); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); jPanel1.setPreferredSize(new java.awt.Dimension(338, 257)); advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N advancedButton.setEnabled(false); advancedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advancedButtonActionPerformed(evt); } }); jScrollPane1.setBorder(null); jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180)); simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(simplePanel); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(245, Short.MAX_VALUE) .addComponent(advancedButton) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(advancedButton) .addContainerGap()) ); timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N timeRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { timeRadioButton1ActionPerformed(evt); } }); javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel); timePanel.setLayout(timePanelLayout); timePanelLayout.setHorizontalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(timeRadioButton1)) .addGroup(timePanelLayout.createSequentialGroup() .addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(timeLabel) .addComponent(timeRadioButton2) .addComponent(timeRadioButton3)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); timePanelLayout.setVerticalGroup( timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(timePanelLayout.createSequentialGroup() .addGap(0, 4, Short.MAX_VALUE) .addComponent(timeLabel) .addGap(0, 0, 0) .addComponent(timeRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timeRadioButton3) .addGap(2, 2, 2)) ); processUnallocPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160))); processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N processUnallocCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.toolTipText")); // NOI18N processUnallocCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processUnallocCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout processUnallocPanelLayout = new javax.swing.GroupLayout(processUnallocPanel); processUnallocPanel.setLayout(processUnallocPanelLayout); processUnallocPanelLayout.setHorizontalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processUnallocCheckbox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processUnallocPanelLayout.setVerticalGroup( processUnallocPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processUnallocPanelLayout.createSequentialGroup() .addComponent(processUnallocCheckbox) .addGap(0, 2, 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processUnallocPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(servicesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(processUnallocPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/impl/src/main/java/org/jboss/weld/bean/proxy/Marker.java b/impl/src/main/java/org/jboss/weld/bean/proxy/Marker.java index c730ef8cc..18c998e5e 100644 --- a/impl/src/main/java/org/jboss/weld/bean/proxy/Marker.java +++ b/impl/src/main/java/org/jboss/weld/bean/proxy/Marker.java @@ -1,38 +1,38 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.bean.proxy; import java.lang.reflect.Method; /** * A marker class we can use to ensure that our method will not collide with a * user provided method * * @author pmuir */ public class Marker { public static final Marker INSTANCE = new Marker(); private Marker() { } public static boolean isMarker(int position, Method method, Object[] args) { - return method.getParameterTypes().length >= position && method.getParameterTypes()[position].equals(Marker.class) && INSTANCE.equals(args[position]); + return method.getParameterTypes().length > position && method.getParameterTypes()[position].equals(Marker.class) && INSTANCE.equals(args[position]); } }
true
true
public static boolean isMarker(int position, Method method, Object[] args) { return method.getParameterTypes().length >= position && method.getParameterTypes()[position].equals(Marker.class) && INSTANCE.equals(args[position]); }
public static boolean isMarker(int position, Method method, Object[] args) { return method.getParameterTypes().length > position && method.getParameterTypes()[position].equals(Marker.class) && INSTANCE.equals(args[position]); }
diff --git a/src/edu/ucdenver/ccp/PhenoGen/tools/promoter/AsyncMeme.java b/src/edu/ucdenver/ccp/PhenoGen/tools/promoter/AsyncMeme.java index 25dd6a7..4023797 100644 --- a/src/edu/ucdenver/ccp/PhenoGen/tools/promoter/AsyncMeme.java +++ b/src/edu/ucdenver/ccp/PhenoGen/tools/promoter/AsyncMeme.java @@ -1,182 +1,182 @@ package edu.ucdenver.ccp.PhenoGen.tools.promoter; /* for handling exceptions in Threads */ import au.com.forward.threads.ThreadReturn; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import javax.mail.MessagingException; import javax.mail.SendFailedException; import javax.servlet.http.HttpSession; import edu.ucdenver.ccp.PhenoGen.web.mail.Email; import edu.ucdenver.ccp.PhenoGen.data.GeneList; import edu.ucdenver.ccp.PhenoGen.data.GeneListAnalysis; import edu.ucdenver.ccp.PhenoGen.data.User; import edu.ucdenver.ccp.PhenoGen.driver.ExecHandler; import edu.ucdenver.ccp.util.FileHandler; import edu.ucdenver.ccp.util.sql.PropertiesConnection; import edu.ucdenver.ccp.util.Debugger; /* for logging messages */ import org.apache.log4j.Logger; public class AsyncMeme implements Runnable{ private Logger log = null; private HttpSession session = null; private String memeFileName = ""; private String sequenceFileName = ""; private String distribution = ""; private String maxMotifs = ""; private String minWidth = ""; private String maxWidth = ""; private User userLoggedIn = null; private String dbPropertiesFile = null; private String perlDir = null; private GeneListAnalysis myGeneListAnalysis = null; private String mainURL = null; private Thread waitThread = null; public AsyncMeme(HttpSession session, String memeFileName, String sequenceFileName, String distribution, String maxMotifs, String minWidth, String maxWidth, GeneListAnalysis myGeneListAnalysis, Thread waitThread) { log = Logger.getRootLogger(); this.session = session; this.memeFileName = memeFileName; this.sequenceFileName = sequenceFileName; this.distribution = distribution; this.maxMotifs = maxMotifs; this.minWidth = minWidth; this.maxWidth = maxWidth; this.userLoggedIn = (User) session.getAttribute("userLoggedIn"); this.dbPropertiesFile = (String) session.getAttribute("dbPropertiesFile"); this.perlDir = (String) session.getAttribute("perlDir"); this.myGeneListAnalysis = myGeneListAnalysis; this.mainURL = (String) session.getAttribute("mainURL"); this.waitThread = waitThread; } public void run() throws RuntimeException { log.debug("Starting run method of AsyncMeme " ); Thread thisThread = Thread.currentThread(); Email myEmail = new Email(); myEmail.setTo(userLoggedIn.getEmail()); GeneList thisGeneList = myGeneListAnalysis.getAnalysisGeneList(); String mainContent = userLoggedIn.getFormal_name() + ",\n\n" + "Thank you for using the PhenoGen Informatics website. "+ "The MEME process called '"+ myGeneListAnalysis.getDescription() + "' that you initiated "; String memeDir = perlDir + "MEME/meme490"; String[] envVariables = new String[4]; envVariables[0] = "MEME_DIRECTORY=" + memeDir; envVariables[1] = "MEME_BIN=" + memeDir + "/bin"; envVariables[2] = "MEME_LOGS=" + memeDir + "/LOGS"; - envVariables[3] = "PATH=$PATH:$MEME_BIN"; + envVariables[3] = "PATH=/usr/bin:/bin:$PATH:$MEME_BIN"; String functionDir = perlDir + "MEME/meme490/bin/meme"; String [] functionArgs = new String[] { functionDir, sequenceFileName, "-mod", distribution, "-nmotifs", maxMotifs, "-minw", minWidth, "-maxw", maxWidth, "-maxsize", "100000" }; log.debug("functionArgs = "); new Debugger().print(functionArgs); ExecHandler myExecHandler = new ExecHandler(memeDir + "/bin", functionArgs, envVariables, memeFileName); try { // // If this thread is interrupted, throw an Exception // ThreadReturn.ifInterruptedStop(); // // If waitThread threw an exception, then ThreadReturn will // detect it and throw the same exception // Otherwise, the join will happen, and will continue to the // next statement. // if (waitThread != null) { log.debug("waiting on thread "+waitThread.getName()); ThreadReturn.join(waitThread); log.debug("just finished waiting on thread "+waitThread.getName()); } myExecHandler.runExec(); //new FileHandler().copyFile(new File(memeDir + "/bin/meme_out/meme.html"), new File(memeFileName + ".html")); File src=new File(memeDir+"/bin/meme_out/"); File dest=new File(memeFileName); new FileHandler().copyDir(src,dest); String successContent = mainContent + "has completed. " + "You may now view the results on the website at " + mainURL + ". "; myEmail.setSubject("MEME process has completed"); myEmail.setContent(successContent); Connection conn = new PropertiesConnection().getConnection(dbPropertiesFile); try { myGeneListAnalysis.createGeneListAnalysis(conn); myGeneListAnalysis.updateVisible(conn); myEmail.sendEmail(); } catch (SendFailedException e) { log.error("in exception of AsyncMeme while sending email", e); } conn.close(); } catch (Exception e) { log.error("in exception of AsyncMeme", e); myEmail.setSubject("MEME process had errors"); String errorContent = mainContent + "was not completed successfully. "+ "The system administrator has been notified of the error. " + "\n" + "You will be contacted via email once the problem is resolved."; String adminErrorContent = "The following email was sent to " + userLoggedIn.getEmail() + ":\n" + errorContent + "\n" + "The file is " + memeFileName + "\n" + "The error type was "+e.getClass(); try { myEmail.setContent(errorContent); myEmail.sendEmail(); myEmail.setContent(adminErrorContent); myEmail.sendEmailToAdministrator((String) session.getAttribute("adminEmail")); log.debug("just sent email to administrator notifying of MEME errors"); } catch (MessagingException e2) { log.error("in exception of AsyncMEME while sending email", e2); throw new RuntimeException(); } throw new RuntimeException(e.getMessage()); } finally { log.debug("executing finally clause in AsyncMeme"); } log.debug("done with AsyncMeme run method"); } }
true
true
public void run() throws RuntimeException { log.debug("Starting run method of AsyncMeme " ); Thread thisThread = Thread.currentThread(); Email myEmail = new Email(); myEmail.setTo(userLoggedIn.getEmail()); GeneList thisGeneList = myGeneListAnalysis.getAnalysisGeneList(); String mainContent = userLoggedIn.getFormal_name() + ",\n\n" + "Thank you for using the PhenoGen Informatics website. "+ "The MEME process called '"+ myGeneListAnalysis.getDescription() + "' that you initiated "; String memeDir = perlDir + "MEME/meme490"; String[] envVariables = new String[4]; envVariables[0] = "MEME_DIRECTORY=" + memeDir; envVariables[1] = "MEME_BIN=" + memeDir + "/bin"; envVariables[2] = "MEME_LOGS=" + memeDir + "/LOGS"; envVariables[3] = "PATH=$PATH:$MEME_BIN"; String functionDir = perlDir + "MEME/meme490/bin/meme"; String [] functionArgs = new String[] { functionDir, sequenceFileName, "-mod", distribution, "-nmotifs", maxMotifs, "-minw", minWidth, "-maxw", maxWidth, "-maxsize", "100000" }; log.debug("functionArgs = "); new Debugger().print(functionArgs); ExecHandler myExecHandler = new ExecHandler(memeDir + "/bin", functionArgs, envVariables, memeFileName); try { // // If this thread is interrupted, throw an Exception // ThreadReturn.ifInterruptedStop(); // // If waitThread threw an exception, then ThreadReturn will // detect it and throw the same exception // Otherwise, the join will happen, and will continue to the // next statement. // if (waitThread != null) { log.debug("waiting on thread "+waitThread.getName()); ThreadReturn.join(waitThread); log.debug("just finished waiting on thread "+waitThread.getName()); } myExecHandler.runExec(); //new FileHandler().copyFile(new File(memeDir + "/bin/meme_out/meme.html"), new File(memeFileName + ".html")); File src=new File(memeDir+"/bin/meme_out/"); File dest=new File(memeFileName); new FileHandler().copyDir(src,dest); String successContent = mainContent + "has completed. " + "You may now view the results on the website at " + mainURL + ". "; myEmail.setSubject("MEME process has completed"); myEmail.setContent(successContent); Connection conn = new PropertiesConnection().getConnection(dbPropertiesFile); try { myGeneListAnalysis.createGeneListAnalysis(conn); myGeneListAnalysis.updateVisible(conn); myEmail.sendEmail(); } catch (SendFailedException e) { log.error("in exception of AsyncMeme while sending email", e); } conn.close(); } catch (Exception e) { log.error("in exception of AsyncMeme", e); myEmail.setSubject("MEME process had errors"); String errorContent = mainContent + "was not completed successfully. "+ "The system administrator has been notified of the error. " + "\n" + "You will be contacted via email once the problem is resolved."; String adminErrorContent = "The following email was sent to " + userLoggedIn.getEmail() + ":\n" + errorContent + "\n" + "The file is " + memeFileName + "\n" + "The error type was "+e.getClass(); try { myEmail.setContent(errorContent); myEmail.sendEmail(); myEmail.setContent(adminErrorContent); myEmail.sendEmailToAdministrator((String) session.getAttribute("adminEmail")); log.debug("just sent email to administrator notifying of MEME errors"); } catch (MessagingException e2) { log.error("in exception of AsyncMEME while sending email", e2); throw new RuntimeException(); } throw new RuntimeException(e.getMessage()); } finally { log.debug("executing finally clause in AsyncMeme"); } log.debug("done with AsyncMeme run method"); }
public void run() throws RuntimeException { log.debug("Starting run method of AsyncMeme " ); Thread thisThread = Thread.currentThread(); Email myEmail = new Email(); myEmail.setTo(userLoggedIn.getEmail()); GeneList thisGeneList = myGeneListAnalysis.getAnalysisGeneList(); String mainContent = userLoggedIn.getFormal_name() + ",\n\n" + "Thank you for using the PhenoGen Informatics website. "+ "The MEME process called '"+ myGeneListAnalysis.getDescription() + "' that you initiated "; String memeDir = perlDir + "MEME/meme490"; String[] envVariables = new String[4]; envVariables[0] = "MEME_DIRECTORY=" + memeDir; envVariables[1] = "MEME_BIN=" + memeDir + "/bin"; envVariables[2] = "MEME_LOGS=" + memeDir + "/LOGS"; envVariables[3] = "PATH=/usr/bin:/bin:$PATH:$MEME_BIN"; String functionDir = perlDir + "MEME/meme490/bin/meme"; String [] functionArgs = new String[] { functionDir, sequenceFileName, "-mod", distribution, "-nmotifs", maxMotifs, "-minw", minWidth, "-maxw", maxWidth, "-maxsize", "100000" }; log.debug("functionArgs = "); new Debugger().print(functionArgs); ExecHandler myExecHandler = new ExecHandler(memeDir + "/bin", functionArgs, envVariables, memeFileName); try { // // If this thread is interrupted, throw an Exception // ThreadReturn.ifInterruptedStop(); // // If waitThread threw an exception, then ThreadReturn will // detect it and throw the same exception // Otherwise, the join will happen, and will continue to the // next statement. // if (waitThread != null) { log.debug("waiting on thread "+waitThread.getName()); ThreadReturn.join(waitThread); log.debug("just finished waiting on thread "+waitThread.getName()); } myExecHandler.runExec(); //new FileHandler().copyFile(new File(memeDir + "/bin/meme_out/meme.html"), new File(memeFileName + ".html")); File src=new File(memeDir+"/bin/meme_out/"); File dest=new File(memeFileName); new FileHandler().copyDir(src,dest); String successContent = mainContent + "has completed. " + "You may now view the results on the website at " + mainURL + ". "; myEmail.setSubject("MEME process has completed"); myEmail.setContent(successContent); Connection conn = new PropertiesConnection().getConnection(dbPropertiesFile); try { myGeneListAnalysis.createGeneListAnalysis(conn); myGeneListAnalysis.updateVisible(conn); myEmail.sendEmail(); } catch (SendFailedException e) { log.error("in exception of AsyncMeme while sending email", e); } conn.close(); } catch (Exception e) { log.error("in exception of AsyncMeme", e); myEmail.setSubject("MEME process had errors"); String errorContent = mainContent + "was not completed successfully. "+ "The system administrator has been notified of the error. " + "\n" + "You will be contacted via email once the problem is resolved."; String adminErrorContent = "The following email was sent to " + userLoggedIn.getEmail() + ":\n" + errorContent + "\n" + "The file is " + memeFileName + "\n" + "The error type was "+e.getClass(); try { myEmail.setContent(errorContent); myEmail.sendEmail(); myEmail.setContent(adminErrorContent); myEmail.sendEmailToAdministrator((String) session.getAttribute("adminEmail")); log.debug("just sent email to administrator notifying of MEME errors"); } catch (MessagingException e2) { log.error("in exception of AsyncMEME while sending email", e2); throw new RuntimeException(); } throw new RuntimeException(e.getMessage()); } finally { log.debug("executing finally clause in AsyncMeme"); } log.debug("done with AsyncMeme run method"); }
diff --git a/src/ben_dude56/plugins/bencmd/warps/WarpableUser.java b/src/ben_dude56/plugins/bencmd/warps/WarpableUser.java index b02eb94..ef03739 100644 --- a/src/ben_dude56/plugins/bencmd/warps/WarpableUser.java +++ b/src/ben_dude56/plugins/bencmd/warps/WarpableUser.java @@ -1,171 +1,171 @@ package ben_dude56.plugins.bencmd.warps; import java.util.ArrayList; import java.util.List; import org.bukkit.Location; import org.bukkit.entity.Player; import ben_dude56.plugins.bencmd.BenCmd; import ben_dude56.plugins.bencmd.User; import ben_dude56.plugins.bencmd.permissions.PermissionUser; public class WarpableUser extends PermissionUser { private Player player; private BenCmd plugin; private boolean isConsole; public WarpableUser(BenCmd instance, Player entity) throws NullPointerException { super(instance, entity.getName(), new ArrayList<String>()); plugin = instance; player = entity; isConsole = false; } public WarpableUser(BenCmd instance) { super(instance, "*", new ArrayList<String>()); plugin = instance; isConsole = true; } public boolean CanWarpTo(String warpName) { if (isConsole) { return false; } return plugin.warps.getWarp(warpName).canWarpHere(this); } public void WarpTo(String warpName) { if (isConsole) { return; } plugin.warps.getWarp(warpName).WarpHere(this); } public void WarpTo(String warpName, User sender) { if (isConsole) { return; } plugin.warps.getWarp(warpName).WarpHere(this, sender.getWarpableUser()); } public List<Warp> ListWarps() { if (this.isConsole) { return plugin.warps.listAllWarps(); } else { return plugin.warps.listWarps(player); } } public void WarpTo(Warp warp) { if (isConsole) { return; } warp.WarpHere(this); } public void WarpTo(Warp warp, User sender) { if (isConsole) { return; } warp.WarpHere(this, sender.getWarpableUser()); } public void HomeWarp(Integer homeNumber) { if (isConsole) { return; } plugin.homes.WarpOwnHome(player, homeNumber); } public void HomeWarp(Integer homeNumber, PermissionUser homeOf) { if (isConsole || homeOf.getName().equalsIgnoreCase("*")) { return; } plugin.homes.WarpOtherHome(player, homeOf.getName(), homeNumber); } public boolean LastCheck() { if (isConsole) { return false; } return plugin.checkpoints.returnPreWarp(player); } public void SetHome(Integer homeNumber) { if (isConsole) { return; } plugin.homes.SetOwnHome(player, homeNumber); } public void SetHome(Integer homeNumber, PermissionUser homeOf) { if (isConsole || homeOf.getName().equalsIgnoreCase("*")) { return; } plugin.homes.SetOtherHome(player, homeOf.getName(), homeNumber); } public void Spawn() { if (isConsole) { return; } Location spawn; - if (plugin.mainProperties.getBoolean("PerWorldSpawn", false)) { + if (plugin.mainProperties.getBoolean("perWorldSpawn", false)) { try { - spawn = plugin.getServer().getWorld(plugin.mainProperties.getString("DefaultWorld", "world")).getSpawnLocation(); + spawn = plugin.getServer().getWorld(plugin.mainProperties.getString("defaultWorld", "world")).getSpawnLocation(); } catch (NullPointerException e) { spawn = player.getWorld().getSpawnLocation(); } } else { spawn = player.getWorld().getSpawnLocation(); } // *ABOVE* Get the spawn location new Warp(spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getYaw(), spawn.getPitch(), spawn.getWorld().getName(), "spawn", "", plugin).WarpHere(this); } public void Spawn(String world) { if (isConsole) { return; } Location spawn; try { spawn = plugin.getServer().getWorld(world).getSpawnLocation(); } catch (NullPointerException e) { Spawn(); return; } // Get the spawn location new Warp(spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getYaw(), spawn.getPitch(), spawn.getWorld().getName(), "spawn", "", plugin).WarpHere(this); } public WarpableUser getWarpableUser() { return this; } public void sendMessage(String message) { if (isConsole) { message = message.replaceAll("§.", ""); plugin.log.info(message); } else { player.sendMessage(message); } } public Player getHandle() { if (isConsole) { return null; } return player; } }
false
true
public void Spawn() { if (isConsole) { return; } Location spawn; if (plugin.mainProperties.getBoolean("PerWorldSpawn", false)) { try { spawn = plugin.getServer().getWorld(plugin.mainProperties.getString("DefaultWorld", "world")).getSpawnLocation(); } catch (NullPointerException e) { spawn = player.getWorld().getSpawnLocation(); } } else { spawn = player.getWorld().getSpawnLocation(); } // *ABOVE* Get the spawn location new Warp(spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getYaw(), spawn.getPitch(), spawn.getWorld().getName(), "spawn", "", plugin).WarpHere(this); }
public void Spawn() { if (isConsole) { return; } Location spawn; if (plugin.mainProperties.getBoolean("perWorldSpawn", false)) { try { spawn = plugin.getServer().getWorld(plugin.mainProperties.getString("defaultWorld", "world")).getSpawnLocation(); } catch (NullPointerException e) { spawn = player.getWorld().getSpawnLocation(); } } else { spawn = player.getWorld().getSpawnLocation(); } // *ABOVE* Get the spawn location new Warp(spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getYaw(), spawn.getPitch(), spawn.getWorld().getName(), "spawn", "", plugin).WarpHere(this); }
diff --git a/src/test/cli/cloudify/cloud/ExamplesTest.java b/src/test/cli/cloudify/cloud/ExamplesTest.java index f68f83ec..7a6993f2 100644 --- a/src/test/cli/cloudify/cloud/ExamplesTest.java +++ b/src/test/cli/cloudify/cloud/ExamplesTest.java @@ -1,50 +1,50 @@ package test.cli.cloudify.cloud; import java.io.IOException; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import test.cli.cloudify.CommandTestUtils; import framework.utils.LogUtils; import framework.utils.ScriptUtils; public class ExamplesTest extends AbstractCloudTest { private String appName; @Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, enabled = true, dataProvider = "supportedClouds") public void testTravel(String cloudName) throws IOException, InterruptedException { appName = "travel"; LogUtils.log("installing application travel on " + cloudName); setCloudToUse(cloudName); doTest("travel"); } @Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, enabled = true, dataProvider = "supportedClouds") public void testPetclinic(String cloudName) throws IOException, InterruptedException { appName = "petclinic"; LogUtils.log("installing application petclinic on " + cloudName); setCloudToUse(cloudName); doTest("petclinic"); } private void doTest(String applicationName) throws IOException, InterruptedException { String applicationPath = ScriptUtils.getBuildPath() + "/examples/" + applicationName; installApplicationAndWait(applicationPath, applicationName); } @AfterMethod public void cleanup() throws IOException, InterruptedException { - String command = "connect " + getService().getRestUrl() + ";list-application"; + String command = "connect " + getService().getRestUrl() + ";list-applications"; String output = CommandTestUtils.runCommandAndWait(command); if (output.contains(appName)) { uninstallApplicationAndWait(appName); } } }
true
true
public void cleanup() throws IOException, InterruptedException { String command = "connect " + getService().getRestUrl() + ";list-application"; String output = CommandTestUtils.runCommandAndWait(command); if (output.contains(appName)) { uninstallApplicationAndWait(appName); } }
public void cleanup() throws IOException, InterruptedException { String command = "connect " + getService().getRestUrl() + ";list-applications"; String output = CommandTestUtils.runCommandAndWait(command); if (output.contains(appName)) { uninstallApplicationAndWait(appName); } }
diff --git a/src/me/bootscreen/workingslots/FileManager.java b/src/me/bootscreen/workingslots/FileManager.java index 3f88fd2..ab89cbf 100644 --- a/src/me/bootscreen/workingslots/FileManager.java +++ b/src/me/bootscreen/workingslots/FileManager.java @@ -1,212 +1,212 @@ package me.bootscreen.workingslots; import java.io.File; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.util.config.*; /** * WorkingSlots for CraftBukkit/Spout * * handels all functions about the config * * @author Bootscreen * */ public class FileManager { private static String ordner = "plugins/WorkingSlots"; private static File configFile = new File(ordner + File.separator + "config.yml"); @SuppressWarnings("deprecation") private static Configuration config; @SuppressWarnings("deprecation") private Configuration loadConfig() { try{ Configuration config = new Configuration(configFile); config.load(); return config; } catch(Exception e) { e.printStackTrace(); return null; } } @SuppressWarnings("deprecation") public void createConfig() { new File(ordner).mkdir(); if(!configFile.exists()) { try { configFile.createNewFile(); config = loadConfig(); config.setProperty("Preset_0", 0); config.setProperty("Preset_1", 0); config.setProperty("Preset_2", 0); config.setProperty("Preset_3", 0); config.setProperty("Preset_4", 0); config.setProperty("Preset_5", 0); config.setProperty("Preset_6", 0); config.setProperty("Preset_7", 0); config.setProperty("Preset_8", 0); config.setProperty("Preset_9", 0); config.save(); } catch(Exception e) { e.printStackTrace(); } } config = loadConfig(); } @SuppressWarnings("deprecation") public boolean savePreset(Player player, int number) { String wert = ""; if(configFile.exists()) { try { ItemStack item; for(int i = 0; i < 9; i++) { item = player.getInventory().getItem(i); if(i != 0) { wert += ","; } wert += item.getTypeId(); if(item.getType().getMaxDurability() == 0 && item.getDurability() > 0) { wert += "-"+item.getDurability(); } } switch(number) { case 0: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_0", wert); config.save(); return true; case 1: config.setProperty("Preset_1", wert); config.save(); return true; case 2: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_2", wert); config.save(); return true; case 3: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_3", wert); config.save(); return true; case 4: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_4", wert); config.save(); return true; case 5: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_5", wert); config.save(); return true; case 6: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_6", wert); config.save(); return true; case 7: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_7", wert); config.save(); return true; case 8: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_8", wert); config.save(); return true; case 9: - config.setProperty("Preset_1", wert); + config.setProperty("Preset_9", wert); config.save(); return true; default: } } catch(Exception e) { e.printStackTrace(); } } return false; } public String readString(String key) { String value = config.getString(key,""); return value; } public boolean loadPreset(Player player, int presetnum) { boolean succeed = false; try { String[] presets = new String[10]; presets[0] = readString("Preset_0"); presets[1] = readString("Preset_1"); presets[2] = readString("Preset_2"); presets[3] = readString("Preset_3"); presets[4] = readString("Preset_4"); presets[5] = readString("Preset_5"); presets[6] = readString("Preset_6"); presets[7] = readString("Preset_7"); presets[8] = readString("Preset_8"); presets[9] = readString("Preset_9"); String[] temp; String delimiter = ","; temp = presets[presetnum].split(delimiter); for(int i = 0; i < temp.length && i < 9 ; i++) { String[] temp2; String delimiter2 = "-"; temp2 = temp[i].split(delimiter2); int item = Integer.parseInt(temp2[0]); if(temp2.length == 2) { short dmgvalue = Short.parseShort(temp2[1]); player.getInventory().setItem(i, new ItemStack(item, 1, dmgvalue)); } else { player.getInventory().setItem(i, new ItemStack(item, 1)); } } succeed = true; } catch(Exception e) { e.printStackTrace(); succeed = false; } return succeed; } }
false
true
public boolean savePreset(Player player, int number) { String wert = ""; if(configFile.exists()) { try { ItemStack item; for(int i = 0; i < 9; i++) { item = player.getInventory().getItem(i); if(i != 0) { wert += ","; } wert += item.getTypeId(); if(item.getType().getMaxDurability() == 0 && item.getDurability() > 0) { wert += "-"+item.getDurability(); } } switch(number) { case 0: config.setProperty("Preset_1", wert); config.save(); return true; case 1: config.setProperty("Preset_1", wert); config.save(); return true; case 2: config.setProperty("Preset_1", wert); config.save(); return true; case 3: config.setProperty("Preset_1", wert); config.save(); return true; case 4: config.setProperty("Preset_1", wert); config.save(); return true; case 5: config.setProperty("Preset_1", wert); config.save(); return true; case 6: config.setProperty("Preset_1", wert); config.save(); return true; case 7: config.setProperty("Preset_1", wert); config.save(); return true; case 8: config.setProperty("Preset_1", wert); config.save(); return true; case 9: config.setProperty("Preset_1", wert); config.save(); return true; default: } } catch(Exception e) { e.printStackTrace(); } } return false; }
public boolean savePreset(Player player, int number) { String wert = ""; if(configFile.exists()) { try { ItemStack item; for(int i = 0; i < 9; i++) { item = player.getInventory().getItem(i); if(i != 0) { wert += ","; } wert += item.getTypeId(); if(item.getType().getMaxDurability() == 0 && item.getDurability() > 0) { wert += "-"+item.getDurability(); } } switch(number) { case 0: config.setProperty("Preset_0", wert); config.save(); return true; case 1: config.setProperty("Preset_1", wert); config.save(); return true; case 2: config.setProperty("Preset_2", wert); config.save(); return true; case 3: config.setProperty("Preset_3", wert); config.save(); return true; case 4: config.setProperty("Preset_4", wert); config.save(); return true; case 5: config.setProperty("Preset_5", wert); config.save(); return true; case 6: config.setProperty("Preset_6", wert); config.save(); return true; case 7: config.setProperty("Preset_7", wert); config.save(); return true; case 8: config.setProperty("Preset_8", wert); config.save(); return true; case 9: config.setProperty("Preset_9", wert); config.save(); return true; default: } } catch(Exception e) { e.printStackTrace(); } } return false; }
diff --git a/src/com/storassa/android/scuolasci/MeteoFragment.java b/src/com/storassa/android/scuolasci/MeteoFragment.java index 313806d..63b0d2f 100755 --- a/src/com/storassa/android/scuolasci/MeteoFragment.java +++ b/src/com/storassa/android/scuolasci/MeteoFragment.java @@ -1,226 +1,228 @@ package com.storassa.android.scuolasci; import java.util.ArrayList; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.google.analytics.tracking.android.EasyTracker; import com.google.analytics.tracking.android.MapBuilder; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import dme.forecastiolib.FIOCurrently; import dme.forecastiolib.FIODaily; import dme.forecastiolib.FIODataPoint; import dme.forecastiolib.ForecastIO; public class MeteoFragment extends Fragment { private FIODataPoint[] dataPoint; private ArrayList<MeteoItem> meteoItems; private ArrayAdapter<MeteoItem> adapter; private StartingActivity parentActivity; FIODaily daily; private int counter = 0; @Override public void onAttach(Activity activity) { super.onAttach(activity); parentActivity = (StartingActivity) activity; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View result = inflater.inflate(R.layout.meteo_fragment, container, false); final ListView meteoListView = (ListView) result .findViewById(R.id.meteo_list); meteoListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // only the first two days can be expanded in hourly // forecast if (id < 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else if (id == 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(R.string.meteo_list_restriction) .setTitle(R.string.warning); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ; } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); // retrieve the saved meteo items, if available meteoItems = new ArrayList<MeteoItem>(); // initialize the dataPoint array with the max number of forecast // plus today dataPoint = new FIODataPoint[MAX_FORECAST_DAYS + 1]; // get the meteo information in a different thread ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Runnable() { @Override public void run() { try { String forecastIoKey = getResources().getString( R.string.forecastio_api_key); String limoneLatitude = getResources().getString( R.string.limone_latitude); String limoneLongitude = getResources().getString( R.string.limone_longitude); ForecastIO fio = new ForecastIO(forecastIoKey); fio.setUnits(ForecastIO.UNITS_SI); fio.setExcludeURL("hourly,minutely"); fio.getForecast(limoneLatitude, limoneLongitude); daily = new FIODaily(fio); } catch (Exception e) { // if there are problems print the stack and warn the user e.printStackTrace(); parentActivity.runOnUiThread(new Runnable() { @Override public void run() { + if(parentActivity.progressDialog.isShowing()) + parentActivity.progressDialog.dismiss(); CommonHelper.exitMessage(R.string.http_issue, R.string.http_issue_dialog_title, parentActivity); } }); } } }); // wait for the http response or exit after 10s Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (daily != null) { // initialize the summary string (plus one for today) String[] meteoIconString = new String[MAX_FORECAST_DAYS]; // get the meteo icon for each day for (int i = 0; i < MAX_FORECAST_DAYS; i++) meteoIconString[i] = daily.getDay(i).icon() .replace('\"', ' ').trim(); // get the meteo data for next days for (int i = 0; i < MAX_FORECAST_DAYS; i++) { dataPoint[i] = daily.getDay(i); meteoItems.add(CommonHelper.getMeteoItemFromDataPoint( dataPoint[i], true)); } // get the meteo array adapter and set it to the listview int resId = R.layout.meteo_list; adapter = new MeteoArrayAdapter(parentActivity, resId, meteoItems, true, 0, 0); parentActivity.runOnUiThread(new Runnable() { public void run() { meteoListView.setAdapter(adapter); } }); // cancel the waiting thread this.cancel(); } else if (counter < WAITING_TICKS) { counter++; } else { CommonHelper.exitMessage(R.string.http_issue_dialog_title, R.string.http_issue, getActivity()); } } }, 0, REPETITION_TIME); return result; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); } // private static final String LIMONE_LATITUDE = "44.2013202"; // private static final String LIMONE_LONGITUDE = "7.576090300000033"; // private static final String METEO_API_FIO_KEY = // "66d2edf03dbf0185e0cb48f1a23a29ed"; // TODO put the website for snow reports private void trackAction() { EasyTracker easyTracker = EasyTracker.getInstance(getActivity()); // MapBuilder.createEvent().build() returns a Map of event // fields and values that are set and sent with the hit. easyTracker.send(MapBuilder.createEvent("ui_action", // category (req) "item_selected", // action (required) "daily_meteo", // label null) // value .build()); } private static final int MAX_FORECAST_DAYS = 7; private static final int REPETITION_TIME = 1000; private static final int WAITING_TICKS = 40; }
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View result = inflater.inflate(R.layout.meteo_fragment, container, false); final ListView meteoListView = (ListView) result .findViewById(R.id.meteo_list); meteoListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // only the first two days can be expanded in hourly // forecast if (id < 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else if (id == 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(R.string.meteo_list_restriction) .setTitle(R.string.warning); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ; } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); // retrieve the saved meteo items, if available meteoItems = new ArrayList<MeteoItem>(); // initialize the dataPoint array with the max number of forecast // plus today dataPoint = new FIODataPoint[MAX_FORECAST_DAYS + 1]; // get the meteo information in a different thread ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Runnable() { @Override public void run() { try { String forecastIoKey = getResources().getString( R.string.forecastio_api_key); String limoneLatitude = getResources().getString( R.string.limone_latitude); String limoneLongitude = getResources().getString( R.string.limone_longitude); ForecastIO fio = new ForecastIO(forecastIoKey); fio.setUnits(ForecastIO.UNITS_SI); fio.setExcludeURL("hourly,minutely"); fio.getForecast(limoneLatitude, limoneLongitude); daily = new FIODaily(fio); } catch (Exception e) { // if there are problems print the stack and warn the user e.printStackTrace(); parentActivity.runOnUiThread(new Runnable() { @Override public void run() { CommonHelper.exitMessage(R.string.http_issue, R.string.http_issue_dialog_title, parentActivity); } }); } } }); // wait for the http response or exit after 10s Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (daily != null) { // initialize the summary string (plus one for today) String[] meteoIconString = new String[MAX_FORECAST_DAYS]; // get the meteo icon for each day for (int i = 0; i < MAX_FORECAST_DAYS; i++) meteoIconString[i] = daily.getDay(i).icon() .replace('\"', ' ').trim(); // get the meteo data for next days for (int i = 0; i < MAX_FORECAST_DAYS; i++) { dataPoint[i] = daily.getDay(i); meteoItems.add(CommonHelper.getMeteoItemFromDataPoint( dataPoint[i], true)); } // get the meteo array adapter and set it to the listview int resId = R.layout.meteo_list; adapter = new MeteoArrayAdapter(parentActivity, resId, meteoItems, true, 0, 0); parentActivity.runOnUiThread(new Runnable() { public void run() { meteoListView.setAdapter(adapter); } }); // cancel the waiting thread this.cancel(); } else if (counter < WAITING_TICKS) { counter++; } else { CommonHelper.exitMessage(R.string.http_issue_dialog_title, R.string.http_issue, getActivity()); } } }, 0, REPETITION_TIME); return result; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View result = inflater.inflate(R.layout.meteo_fragment, container, false); final ListView meteoListView = (ListView) result .findViewById(R.id.meteo_list); meteoListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // only the first two days can be expanded in hourly // forecast if (id < 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else if (id == 2) { // Google Analytics tracking trackAction(); Intent myIntent = new Intent(getActivity(), MeteoActivity.class); Calendar c = Calendar.getInstance(); myIntent.putExtra("current_hour", c .get(Calendar.HOUR_OF_DAY)); myIntent.putExtra("day", (int) id); myIntent.putExtra("customer", parentActivity.customerName); getActivity().startActivity(myIntent); } else { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(R.string.meteo_list_restriction) .setTitle(R.string.warning); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ; } }); AlertDialog dialog = builder.create(); dialog.show(); } } }); // retrieve the saved meteo items, if available meteoItems = new ArrayList<MeteoItem>(); // initialize the dataPoint array with the max number of forecast // plus today dataPoint = new FIODataPoint[MAX_FORECAST_DAYS + 1]; // get the meteo information in a different thread ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Runnable() { @Override public void run() { try { String forecastIoKey = getResources().getString( R.string.forecastio_api_key); String limoneLatitude = getResources().getString( R.string.limone_latitude); String limoneLongitude = getResources().getString( R.string.limone_longitude); ForecastIO fio = new ForecastIO(forecastIoKey); fio.setUnits(ForecastIO.UNITS_SI); fio.setExcludeURL("hourly,minutely"); fio.getForecast(limoneLatitude, limoneLongitude); daily = new FIODaily(fio); } catch (Exception e) { // if there are problems print the stack and warn the user e.printStackTrace(); parentActivity.runOnUiThread(new Runnable() { @Override public void run() { if(parentActivity.progressDialog.isShowing()) parentActivity.progressDialog.dismiss(); CommonHelper.exitMessage(R.string.http_issue, R.string.http_issue_dialog_title, parentActivity); } }); } } }); // wait for the http response or exit after 10s Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (daily != null) { // initialize the summary string (plus one for today) String[] meteoIconString = new String[MAX_FORECAST_DAYS]; // get the meteo icon for each day for (int i = 0; i < MAX_FORECAST_DAYS; i++) meteoIconString[i] = daily.getDay(i).icon() .replace('\"', ' ').trim(); // get the meteo data for next days for (int i = 0; i < MAX_FORECAST_DAYS; i++) { dataPoint[i] = daily.getDay(i); meteoItems.add(CommonHelper.getMeteoItemFromDataPoint( dataPoint[i], true)); } // get the meteo array adapter and set it to the listview int resId = R.layout.meteo_list; adapter = new MeteoArrayAdapter(parentActivity, resId, meteoItems, true, 0, 0); parentActivity.runOnUiThread(new Runnable() { public void run() { meteoListView.setAdapter(adapter); } }); // cancel the waiting thread this.cancel(); } else if (counter < WAITING_TICKS) { counter++; } else { CommonHelper.exitMessage(R.string.http_issue_dialog_title, R.string.http_issue, getActivity()); } } }, 0, REPETITION_TIME); return result; }