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/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/view/swing/MpiBlastExampleJobCreationPanel.java b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/view/swing/MpiBlastExampleJobCreationPanel.java index d3cdace0..f724e624 100644 --- a/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/view/swing/MpiBlastExampleJobCreationPanel.java +++ b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/view/swing/MpiBlastExampleJobCreationPanel.java @@ -1,503 +1,503 @@ package org.vpac.grisu.frontend.view.swing; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.vpac.grisu.control.ServiceInterface; import org.vpac.grisu.control.exceptions.BatchJobException; import org.vpac.grisu.frontend.model.job.BatchJobObject; import org.vpac.grisu.frontend.model.job.JobObject; import org.vpac.grisu.frontend.view.swing.files.GrisuFileDialog; import org.vpac.grisu.frontend.view.swing.jobcreation.JobCreationPanel; import org.vpac.grisu.model.FileManager; import org.vpac.grisu.model.GrisuRegistryManager; import org.vpac.grisu.model.UserEnvironmentManager; import org.vpac.grisu.model.files.GlazedFile; import org.vpac.historyRepeater.HistoryManager; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; public class MpiBlastExampleJobCreationPanel extends JPanel implements JobCreationPanel, PropertyChangeListener { static final Logger myLogger = Logger .getLogger(MpiBlastExampleJobCreationPanel.class.getName()); static final int DEFAULT_WALLTIME = 3600 * 24; private ServiceInterface si; private JLabel jobnameLabel; private JTextField jobnameField; private JLabel lblProgram; private JComboBox programCombobox; private JLabel lblDatabase; private JComboBox databaseComboBox; private JLabel lblFastaFile; private JComboBox inputFileComboBox; private JButton btnBrowse; private JLabel lblOfJobs; private JSlider slider; private BatchJobObject currentBatchJob; private GrisuFileDialog dialog; private GlazedFile currentFile; private List<String> currentFastaInput; private FileManager fm; private UserEnvironmentManager uem; private HistoryManager hm; private JLabel noJobsLabel; private JButton submitButton; private JobSubmissionLogPanel jobSubmissionLogPanel; private Thread subThread; private static final NumberFormat formatter = new DecimalFormat("0000"); /** * Create the panel. */ public MpiBlastExampleJobCreationPanel() { setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(16dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, }, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"), FormFactory.RELATED_GAP_ROWSPEC, })); add(getLblFastaFile(), "2, 2, right, default"); add(getInputFileComboBox(), "4, 2, 5, 1, fill, default"); add(getBtnBrowse(), "10, 2"); add(getJobnameLabel(), "2, 4, right, default"); add(getJobnameField(), "4, 4, 7, 1, fill, default"); add(getLblProgram(), "2, 6, right, default"); add(getProgramCombobox(), "4, 6, fill, default"); add(getLblDatabase(), "6, 6, right, default"); add(getDatabaseComboBox(), "8, 6, 3, 1, fill, default"); add(getLblOfJobs(), "2, 10, right, default"); add(getSlider(), "4, 10, 5, 1"); add(getNoJobsLabel(), "10, 10, center, default"); add(getSubmitButton(), "10, 12"); add(getJobSubmissionLogPanel(), "2, 14, 9, 1, fill, fill"); } private void cleanUpUI() { getInputFileComboBox().setSelectedItem(null); getSlider().setEnabled(false); getSlider().setMaximum(1); getNoJobsLabel().setText("n/a"); getSubmitButton().setText("Submit"); getJobSubmissionLogPanel().clear(); getJobnameField().setText(""); currentFastaInput = null; currentFile = null; } public boolean createsBatchJob() { return true; } public boolean createsSingleJob() { return false; } private JButton getBtnBrowse() { if (btnBrowse == null) { btnBrowse = new JButton("Browse"); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (si == null) { myLogger.error("ServiceInterface not set yet."); return; } GlazedFile file = popupFileDialogAndAskForFile(); if (file == null) { return; } setInputFile(file); } }); } return btnBrowse; } private JComboBox getDatabaseComboBox() { if (databaseComboBox == null) { databaseComboBox = new JComboBox(); databaseComboBox.setModel(new DefaultComboBoxModel(new String[] { "nt", "nr" })); } return databaseComboBox; } public GrisuFileDialog getFileDialog() { if (si == null) { myLogger.error("Serviceinterface not set yet..."); return null; } if (dialog == null) { String url = hm .getLastEntry("MPIBLAST_EXAMPLE_LAST_INPUT_FILE_DIR"); if (StringUtils.isBlank(url)) { url = new File(System.getProperty("user.home")).toURI() .toString(); } dialog = new GrisuFileDialog(si, url); } return dialog; } private JComboBox getInputFileComboBox() { if (inputFileComboBox == null) { inputFileComboBox = new JComboBox(); inputFileComboBox.setEditable(true); } return inputFileComboBox; } private JTextField getJobnameField() { if (jobnameField == null) { jobnameField = new JTextField(); jobnameField.setColumns(10); } return jobnameField; } private JLabel getJobnameLabel() { if (jobnameLabel == null) { jobnameLabel = new JLabel("Jobname:"); } return jobnameLabel; } private JobSubmissionLogPanel getJobSubmissionLogPanel() { if (jobSubmissionLogPanel == null) { jobSubmissionLogPanel = new JobSubmissionLogPanel(); } return jobSubmissionLogPanel; } private JLabel getLblDatabase() { if (lblDatabase == null) { lblDatabase = new JLabel("Database:"); } return lblDatabase; } private JLabel getLblFastaFile() { if (lblFastaFile == null) { lblFastaFile = new JLabel("Fasta file:"); } return lblFastaFile; } private JLabel getLblOfJobs() { if (lblOfJobs == null) { lblOfJobs = new JLabel("# of jobs"); } return lblOfJobs; } private JLabel getLblProgram() { if (lblProgram == null) { lblProgram = new JLabel("Program:"); } return lblProgram; } private JLabel getNoJobsLabel() { if (noJobsLabel == null) { noJobsLabel = new JLabel("n/a"); } return noJobsLabel; } public JPanel getPanel() { return this; } public String getPanelName() { return "MPIBlast batch"; } private JComboBox getProgramCombobox() { if (programCombobox == null) { programCombobox = new JComboBox(); programCombobox.setModel(new DefaultComboBoxModel(new String[] { "blastn", "blastp", "blastx", "tblastn", "tblastx" })); } return programCombobox; } private JSlider getSlider() { if (slider == null) { slider = new JSlider(); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setEnabled(false); slider.setMinimum(1); slider.setMaximum(1); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { getNoJobsLabel().setText( new Integer(slider.getValue()).toString()); } }); } return slider; } private JButton getSubmitButton() { if (submitButton == null) { submitButton = new JButton("Submit"); submitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if ("Submit".equals(submitButton.getText())) { if (subThread != null) { subThread.interrupt(); } subThread = new Thread() { @Override public void run() { try { submitJob(); } catch (BatchJobException e) { e.printStackTrace(); cleanUpUI(); } } }; subThread.start(); submitButton.setText("Cancel"); } else if ("Cancel".equals(submitButton.getText())) { subThread.interrupt(); submitButton.setText("Ok"); } else if ("Ok".equals(submitButton.getText())) { cleanUpUI(); } } }); } return submitButton; } public String getSupportedApplication() { return "mpiBlast"; } private void parseFastaFile() { try { currentFastaInput = FileUtils.readLines(fm .getLocalCacheFile(currentFile.getUrl())); Iterator<String> it = currentFastaInput.iterator(); while (it.hasNext()) { String line = it.next(); if (StringUtils.isBlank(line)) { it.remove(); } } } catch (IOException e) { e.printStackTrace(); } } protected GlazedFile popupFileDialogAndAskForFile() { getFileDialog().setVisible(true); GlazedFile file = getFileDialog().getSelectedFile(); getFileDialog().clearSelection(); GlazedFile currentDir = getFileDialog().getCurrentDirectory(); hm.addHistoryEntry("MPIBLAST_EXAMPLE_LAST_INPUT_FILE_DIR", currentDir .getUrl()); return file; } public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(BatchJobObject.SUBMITTING)) { if ((Boolean) (evt.getOldValue()) && !(Boolean) (evt.getNewValue())) { getSubmitButton().setText("Ok"); } } } private void setInputFile(GlazedFile file) { currentFile = file; getInputFileComboBox().setSelectedItem(file.getUrl()); if (currentFile == null) { return; } getSlider().setEnabled(true); parseFastaFile(); getSlider().setMaximum(currentFastaInput.size()); getJobnameField().setText( uem.calculateUniqueJobname(currentFile .getNameWithoutExtension() + "_job")); } public void setServiceInterface(ServiceInterface si) { this.si = si; this.fm = GrisuRegistryManager.getDefault(si).getFileManager(); this.uem = GrisuRegistryManager.getDefault(si) .getUserEnvironmentManager(); this.hm = GrisuRegistryManager.getDefault(si).getHistoryManager(); } public void submitJob() throws BatchJobException { if (currentBatchJob != null) { currentBatchJob.removePropertyChangeListener(this); } currentBatchJob = new BatchJobObject(si, getJobnameField().getText(), "/ACC", "mpiblast", "1.5.0"); currentBatchJob.addPropertyChangeListener(this); getJobSubmissionLogPanel().setBatchJob(currentBatchJob); Map<String, List<String>> inputFiles = new LinkedHashMap<String, List<String>>(); int noJobs = getSlider().getValue(); Double linesPerJobD = new Double(currentFastaInput.size()) / new Double(noJobs); int linesPerJob = new Long(Math.round(linesPerJobD + 0.499999)) .intValue(); for (int i = 0; i < currentFastaInput.size(); i = i + linesPerJob) { int end = i + linesPerJob; if (end > currentFastaInput.size()) { end = currentFastaInput.size(); } List<String> tempList = currentFastaInput.subList(i, end); inputFiles.put("line" + formatter.format(i) + "-line" + formatter.format(end - 1), tempList); } for (String jobname : inputFiles.keySet()) { // create temp file String inputFIlename = jobname + "_" + currentBatchJob.getJobname(); File tempFile = new File(System.getProperty("java.io.tmpdir"), inputFIlename); tempFile.delete(); try { FileUtils.writeLines(tempFile, inputFiles.get(jobname)); } catch (IOException e) { throw new BatchJobException(e); } JobObject tempJob = new JobObject(si); tempJob.setJobname(uem.calculateUniqueJobname(jobname + "_" + currentBatchJob.getJobname())); tempJob.addInputFileUrl(tempFile.toURI().toString()); tempJob.setApplication("mpiblast"); tempJob.setApplicationVersion("1.5.0"); // tempJob.setWalltimeInSeconds(604800); tempJob.setWalltimeInSeconds(DEFAULT_WALLTIME); - String commandline = "mpiblast -np 8 -p blastp -d nr -i " - + inputFIlename + " -o " + jobname + "out.txt"; + String commandline = "mpiblast -p blastp -d nr -i " + inputFIlename + + " -o " + jobname + "out.txt"; tempJob.setCommandline(commandline); tempJob.setForce_mpi(true); tempJob.setCpus(8); currentBatchJob.addJob(tempJob); } currentBatchJob.setDefaultNoCpus(8); // currentBatchJob.setDefaultWalltimeInSeconds(604800); currentBatchJob.setDefaultWalltimeInSeconds(DEFAULT_WALLTIME); try { currentBatchJob.prepareAndCreateJobs(true); } catch (Exception e) { throw new BatchJobException(e); } try { currentBatchJob.submit(); } catch (Exception e) { throw new BatchJobException(e); } } }
true
true
public void submitJob() throws BatchJobException { if (currentBatchJob != null) { currentBatchJob.removePropertyChangeListener(this); } currentBatchJob = new BatchJobObject(si, getJobnameField().getText(), "/ACC", "mpiblast", "1.5.0"); currentBatchJob.addPropertyChangeListener(this); getJobSubmissionLogPanel().setBatchJob(currentBatchJob); Map<String, List<String>> inputFiles = new LinkedHashMap<String, List<String>>(); int noJobs = getSlider().getValue(); Double linesPerJobD = new Double(currentFastaInput.size()) / new Double(noJobs); int linesPerJob = new Long(Math.round(linesPerJobD + 0.499999)) .intValue(); for (int i = 0; i < currentFastaInput.size(); i = i + linesPerJob) { int end = i + linesPerJob; if (end > currentFastaInput.size()) { end = currentFastaInput.size(); } List<String> tempList = currentFastaInput.subList(i, end); inputFiles.put("line" + formatter.format(i) + "-line" + formatter.format(end - 1), tempList); } for (String jobname : inputFiles.keySet()) { // create temp file String inputFIlename = jobname + "_" + currentBatchJob.getJobname(); File tempFile = new File(System.getProperty("java.io.tmpdir"), inputFIlename); tempFile.delete(); try { FileUtils.writeLines(tempFile, inputFiles.get(jobname)); } catch (IOException e) { throw new BatchJobException(e); } JobObject tempJob = new JobObject(si); tempJob.setJobname(uem.calculateUniqueJobname(jobname + "_" + currentBatchJob.getJobname())); tempJob.addInputFileUrl(tempFile.toURI().toString()); tempJob.setApplication("mpiblast"); tempJob.setApplicationVersion("1.5.0"); // tempJob.setWalltimeInSeconds(604800); tempJob.setWalltimeInSeconds(DEFAULT_WALLTIME); String commandline = "mpiblast -np 8 -p blastp -d nr -i " + inputFIlename + " -o " + jobname + "out.txt"; tempJob.setCommandline(commandline); tempJob.setForce_mpi(true); tempJob.setCpus(8); currentBatchJob.addJob(tempJob); } currentBatchJob.setDefaultNoCpus(8); // currentBatchJob.setDefaultWalltimeInSeconds(604800); currentBatchJob.setDefaultWalltimeInSeconds(DEFAULT_WALLTIME); try { currentBatchJob.prepareAndCreateJobs(true); } catch (Exception e) { throw new BatchJobException(e); } try { currentBatchJob.submit(); } catch (Exception e) { throw new BatchJobException(e); } }
public void submitJob() throws BatchJobException { if (currentBatchJob != null) { currentBatchJob.removePropertyChangeListener(this); } currentBatchJob = new BatchJobObject(si, getJobnameField().getText(), "/ACC", "mpiblast", "1.5.0"); currentBatchJob.addPropertyChangeListener(this); getJobSubmissionLogPanel().setBatchJob(currentBatchJob); Map<String, List<String>> inputFiles = new LinkedHashMap<String, List<String>>(); int noJobs = getSlider().getValue(); Double linesPerJobD = new Double(currentFastaInput.size()) / new Double(noJobs); int linesPerJob = new Long(Math.round(linesPerJobD + 0.499999)) .intValue(); for (int i = 0; i < currentFastaInput.size(); i = i + linesPerJob) { int end = i + linesPerJob; if (end > currentFastaInput.size()) { end = currentFastaInput.size(); } List<String> tempList = currentFastaInput.subList(i, end); inputFiles.put("line" + formatter.format(i) + "-line" + formatter.format(end - 1), tempList); } for (String jobname : inputFiles.keySet()) { // create temp file String inputFIlename = jobname + "_" + currentBatchJob.getJobname(); File tempFile = new File(System.getProperty("java.io.tmpdir"), inputFIlename); tempFile.delete(); try { FileUtils.writeLines(tempFile, inputFiles.get(jobname)); } catch (IOException e) { throw new BatchJobException(e); } JobObject tempJob = new JobObject(si); tempJob.setJobname(uem.calculateUniqueJobname(jobname + "_" + currentBatchJob.getJobname())); tempJob.addInputFileUrl(tempFile.toURI().toString()); tempJob.setApplication("mpiblast"); tempJob.setApplicationVersion("1.5.0"); // tempJob.setWalltimeInSeconds(604800); tempJob.setWalltimeInSeconds(DEFAULT_WALLTIME); String commandline = "mpiblast -p blastp -d nr -i " + inputFIlename + " -o " + jobname + "out.txt"; tempJob.setCommandline(commandline); tempJob.setForce_mpi(true); tempJob.setCpus(8); currentBatchJob.addJob(tempJob); } currentBatchJob.setDefaultNoCpus(8); // currentBatchJob.setDefaultWalltimeInSeconds(604800); currentBatchJob.setDefaultWalltimeInSeconds(DEFAULT_WALLTIME); try { currentBatchJob.prepareAndCreateJobs(true); } catch (Exception e) { throw new BatchJobException(e); } try { currentBatchJob.submit(); } catch (Exception e) { throw new BatchJobException(e); } }
diff --git a/test/selenium/com.ibm.sbt.automation.test/src/com/ibm/sbt/test/controls/grid/communities/CommunityMembersGrid.java b/test/selenium/com.ibm.sbt.automation.test/src/com/ibm/sbt/test/controls/grid/communities/CommunityMembersGrid.java index 52db4f79d..604484209 100644 --- a/test/selenium/com.ibm.sbt.automation.test/src/com/ibm/sbt/test/controls/grid/communities/CommunityMembersGrid.java +++ b/test/selenium/com.ibm.sbt.automation.test/src/com/ibm/sbt/test/controls/grid/communities/CommunityMembersGrid.java @@ -1,58 +1,58 @@ /* * � Copyright IBM Corp. 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.ibm.sbt.test.controls.grid.communities; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.ibm.sbt.automation.core.test.connections.BaseCommunitiesGridTest; import com.ibm.sbt.services.client.connections.communities.Member; /** * @author Benjamin Jakobus * * @date 24 Oct 2013 */ public class CommunityMembersGrid extends BaseCommunitiesGridTest { public CommunityMembersGrid() { setAuthType(AuthType.AUTO_DETECT); } @Test public void testCreateCommunity() { // Check grid assertTrue("Expected the test to generate a grid", checkGrid("Social_Communities_Controls_CommunityMembers",true,true)); } @Before public void initCommunity() { addSnippetParam("sample.userId3", getCommunityUuid()); try { - addMember(new Member(getCommunityService(), "[email protected]")); + addMember(new Member(getCommunityService(), "sample.userId3")); } catch(Exception e) { e.printStackTrace(); } } @After public void destroyCommunity() { destroy(); } }
true
true
public void initCommunity() { addSnippetParam("sample.userId3", getCommunityUuid()); try { addMember(new Member(getCommunityService(), "[email protected]")); } catch(Exception e) { e.printStackTrace(); } }
public void initCommunity() { addSnippetParam("sample.userId3", getCommunityUuid()); try { addMember(new Member(getCommunityService(), "sample.userId3")); } catch(Exception e) { e.printStackTrace(); } }
diff --git a/hazelcast-monitor/src/main/java/com/hazelcast/monitor/server/event/QueueStatisticsGenerator.java b/hazelcast-monitor/src/main/java/com/hazelcast/monitor/server/event/QueueStatisticsGenerator.java index 569ac103..faca9552 100644 --- a/hazelcast-monitor/src/main/java/com/hazelcast/monitor/server/event/QueueStatisticsGenerator.java +++ b/hazelcast-monitor/src/main/java/com/hazelcast/monitor/server/event/QueueStatisticsGenerator.java @@ -1,102 +1,102 @@ /* * Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.monitor.server.event; import com.hazelcast.client.HazelcastClient; import com.hazelcast.core.Member; import com.hazelcast.core.MultiTask; import com.hazelcast.monitor.DistributedQueueStatsCallable; import com.hazelcast.monitor.LocalQueueOperationStats; import com.hazelcast.monitor.client.event.ChangeEvent; import com.hazelcast.monitor.client.event.ChangeEventType; import com.hazelcast.monitor.client.event.QueueStatistics; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; public class QueueStatisticsGenerator extends InstanceStatisticsGenerator { public QueueStatisticsGenerator(HazelcastClient client, String name, int clusterId) { super(name, client, clusterId); } public ChangeEvent generateEvent() { ExecutorService esService = client.getExecutorService(); Set<Member> members = client.getCluster().getMembers(); final List<Member> lsMembers = new ArrayList<Member>(members); MultiTask<DistributedQueueStatsCallable.MemberQueueStats> task = new MultiTask<DistributedQueueStatsCallable.MemberQueueStats>(new DistributedQueueStatsCallable(name), members); esService.execute(task); Collection<DistributedQueueStatsCallable.MemberQueueStats> queueStats; try { queueStats = task.get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { return null; } if (queueStats == null) { return null; } if (members.size() != queueStats.size()) { return null; } List<DistributedQueueStatsCallable.MemberQueueStats> lsQueueStats = new ArrayList(queueStats); Collections.sort(lsQueueStats, new Comparator<DistributedQueueStatsCallable.MemberQueueStats>() { public int compare(DistributedQueueStatsCallable.MemberQueueStats o1, DistributedQueueStatsCallable.MemberQueueStats o2) { int i1 = lsMembers.indexOf(o1.getMember()); int i2 = lsMembers.indexOf(o2.getMember()); return i1 - i2; } }); List<QueueStatistics.LocalQueueStatistics> listOfStats = new ArrayList<QueueStatistics.LocalQueueStatistics>(); for (DistributedQueueStatsCallable.MemberQueueStats memberQStat : lsQueueStats) { QueueStatistics.LocalQueueStatistics stat = new QueueStatistics.LocalQueueStatistics(); stat.ownedItemCount = memberQStat.getLocalQueueStats().getOwnedItemCount(); stat.backupItemCount = memberQStat.getLocalQueueStats().getBackupItemCount(); stat.maxAge = memberQStat.getLocalQueueStats().getMaxAge(); stat.minAge = memberQStat.getLocalQueueStats().getMinAge(); stat.aveAge = memberQStat.getLocalQueueStats().getAveAge(); - stat.periodEnd = memberQStat.getLocalQueueStats().getQueueOperationStats().getPeriodEnd(); - stat.periodStart = memberQStat.getLocalQueueStats().getQueueOperationStats().getPeriodStart(); + stat.periodEnd = memberQStat.getLocalQueueStats().getOperationStats().getPeriodEnd(); + stat.periodStart = memberQStat.getLocalQueueStats().getOperationStats().getPeriodStart(); stat.memberName = memberQStat.getMember().getInetSocketAddress().getHostName() + ":" + memberQStat.getMember().getInetSocketAddress().getPort(); long periodInSec = (stat.periodEnd - stat.periodStart) / 1000; - LocalQueueOperationStats localQueueOperationStats = memberQStat.getLocalQueueStats().getQueueOperationStats(); + LocalQueueOperationStats localQueueOperationStats = memberQStat.getLocalQueueStats().getOperationStats(); stat.numberOfEmptyPollsInSec = localQueueOperationStats.getNumberOfEmptyPolls() / periodInSec; stat.numberOfOffersInSec = localQueueOperationStats.getNumberOfOffers() / periodInSec; stat.numberOfPollsInSec = localQueueOperationStats.getNumberOfPolls() / periodInSec; stat.numberOfRejectedOffersInSec = localQueueOperationStats.getNumberOfRejectedOffers() / periodInSec; listOfStats.add(stat); } QueueStatistics event = new QueueStatistics(this.clusterId); event.setName(name); event.setList(listOfStats); storeEvent(event); return event; } public ChangeEventType getChangeEventType() { return ChangeEventType.QUEUE_STATISTICS; } public int getClusterId() { return clusterId; } }
false
true
public ChangeEvent generateEvent() { ExecutorService esService = client.getExecutorService(); Set<Member> members = client.getCluster().getMembers(); final List<Member> lsMembers = new ArrayList<Member>(members); MultiTask<DistributedQueueStatsCallable.MemberQueueStats> task = new MultiTask<DistributedQueueStatsCallable.MemberQueueStats>(new DistributedQueueStatsCallable(name), members); esService.execute(task); Collection<DistributedQueueStatsCallable.MemberQueueStats> queueStats; try { queueStats = task.get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { return null; } if (queueStats == null) { return null; } if (members.size() != queueStats.size()) { return null; } List<DistributedQueueStatsCallable.MemberQueueStats> lsQueueStats = new ArrayList(queueStats); Collections.sort(lsQueueStats, new Comparator<DistributedQueueStatsCallable.MemberQueueStats>() { public int compare(DistributedQueueStatsCallable.MemberQueueStats o1, DistributedQueueStatsCallable.MemberQueueStats o2) { int i1 = lsMembers.indexOf(o1.getMember()); int i2 = lsMembers.indexOf(o2.getMember()); return i1 - i2; } }); List<QueueStatistics.LocalQueueStatistics> listOfStats = new ArrayList<QueueStatistics.LocalQueueStatistics>(); for (DistributedQueueStatsCallable.MemberQueueStats memberQStat : lsQueueStats) { QueueStatistics.LocalQueueStatistics stat = new QueueStatistics.LocalQueueStatistics(); stat.ownedItemCount = memberQStat.getLocalQueueStats().getOwnedItemCount(); stat.backupItemCount = memberQStat.getLocalQueueStats().getBackupItemCount(); stat.maxAge = memberQStat.getLocalQueueStats().getMaxAge(); stat.minAge = memberQStat.getLocalQueueStats().getMinAge(); stat.aveAge = memberQStat.getLocalQueueStats().getAveAge(); stat.periodEnd = memberQStat.getLocalQueueStats().getQueueOperationStats().getPeriodEnd(); stat.periodStart = memberQStat.getLocalQueueStats().getQueueOperationStats().getPeriodStart(); stat.memberName = memberQStat.getMember().getInetSocketAddress().getHostName() + ":" + memberQStat.getMember().getInetSocketAddress().getPort(); long periodInSec = (stat.periodEnd - stat.periodStart) / 1000; LocalQueueOperationStats localQueueOperationStats = memberQStat.getLocalQueueStats().getQueueOperationStats(); stat.numberOfEmptyPollsInSec = localQueueOperationStats.getNumberOfEmptyPolls() / periodInSec; stat.numberOfOffersInSec = localQueueOperationStats.getNumberOfOffers() / periodInSec; stat.numberOfPollsInSec = localQueueOperationStats.getNumberOfPolls() / periodInSec; stat.numberOfRejectedOffersInSec = localQueueOperationStats.getNumberOfRejectedOffers() / periodInSec; listOfStats.add(stat); } QueueStatistics event = new QueueStatistics(this.clusterId); event.setName(name); event.setList(listOfStats); storeEvent(event); return event; }
public ChangeEvent generateEvent() { ExecutorService esService = client.getExecutorService(); Set<Member> members = client.getCluster().getMembers(); final List<Member> lsMembers = new ArrayList<Member>(members); MultiTask<DistributedQueueStatsCallable.MemberQueueStats> task = new MultiTask<DistributedQueueStatsCallable.MemberQueueStats>(new DistributedQueueStatsCallable(name), members); esService.execute(task); Collection<DistributedQueueStatsCallable.MemberQueueStats> queueStats; try { queueStats = task.get(); } catch (InterruptedException e) { return null; } catch (ExecutionException e) { return null; } if (queueStats == null) { return null; } if (members.size() != queueStats.size()) { return null; } List<DistributedQueueStatsCallable.MemberQueueStats> lsQueueStats = new ArrayList(queueStats); Collections.sort(lsQueueStats, new Comparator<DistributedQueueStatsCallable.MemberQueueStats>() { public int compare(DistributedQueueStatsCallable.MemberQueueStats o1, DistributedQueueStatsCallable.MemberQueueStats o2) { int i1 = lsMembers.indexOf(o1.getMember()); int i2 = lsMembers.indexOf(o2.getMember()); return i1 - i2; } }); List<QueueStatistics.LocalQueueStatistics> listOfStats = new ArrayList<QueueStatistics.LocalQueueStatistics>(); for (DistributedQueueStatsCallable.MemberQueueStats memberQStat : lsQueueStats) { QueueStatistics.LocalQueueStatistics stat = new QueueStatistics.LocalQueueStatistics(); stat.ownedItemCount = memberQStat.getLocalQueueStats().getOwnedItemCount(); stat.backupItemCount = memberQStat.getLocalQueueStats().getBackupItemCount(); stat.maxAge = memberQStat.getLocalQueueStats().getMaxAge(); stat.minAge = memberQStat.getLocalQueueStats().getMinAge(); stat.aveAge = memberQStat.getLocalQueueStats().getAveAge(); stat.periodEnd = memberQStat.getLocalQueueStats().getOperationStats().getPeriodEnd(); stat.periodStart = memberQStat.getLocalQueueStats().getOperationStats().getPeriodStart(); stat.memberName = memberQStat.getMember().getInetSocketAddress().getHostName() + ":" + memberQStat.getMember().getInetSocketAddress().getPort(); long periodInSec = (stat.periodEnd - stat.periodStart) / 1000; LocalQueueOperationStats localQueueOperationStats = memberQStat.getLocalQueueStats().getOperationStats(); stat.numberOfEmptyPollsInSec = localQueueOperationStats.getNumberOfEmptyPolls() / periodInSec; stat.numberOfOffersInSec = localQueueOperationStats.getNumberOfOffers() / periodInSec; stat.numberOfPollsInSec = localQueueOperationStats.getNumberOfPolls() / periodInSec; stat.numberOfRejectedOffersInSec = localQueueOperationStats.getNumberOfRejectedOffers() / periodInSec; listOfStats.add(stat); } QueueStatistics event = new QueueStatistics(this.clusterId); event.setName(name); event.setList(listOfStats); storeEvent(event); return event; }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ParameterUtil.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ParameterUtil.java index a1997b28b..5af26e95f 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ParameterUtil.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ParameterUtil.java @@ -1,405 +1,418 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.sql.Blob; import java.sql.Clob; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.data.DataType.AnyType; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IInputParameterBinding; import org.eclipse.birt.data.engine.api.IParameterDefinition; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ExprEvaluateUtil; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.odaconsumer.ParameterHint; import org.eclipse.datatools.connectivity.oda.IBlob; import org.eclipse.datatools.connectivity.oda.IClob; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import com.ibm.icu.text.SimpleDateFormat; /** * Merge the paramter definition and evaluate the expression of paramter */ class ParameterUtil { private IQueryService outerResults; private DataSetRuntime dsRT; private IQueryDefinition queryDefn; private Scriptable scope; private Logger logger = Logger.getLogger( ParameterUtil.class.getName( ) ); /** * @param outerResults * @param dsRT * @param queryDefn * @param scope */ ParameterUtil( IQueryService outerResults, DataSetRuntime dsRT, IQueryDefinition queryDefn, Scriptable scope ) { Object[] params = { outerResults, dsRT, queryDefn, scope }; logger.entering( ParameterUtil.class.getName( ), "ParameterUtil", //$NON-NLS-1$ params ); this.outerResults = outerResults; this.dsRT = dsRT; this.queryDefn = queryDefn; this.scope = scope; logger.exiting( ParameterUtil.class.getName( ), "ParameterUtil" ); //$NON-NLS-1$ } /** * Resolve parameter bindings and return a Collection of ParameterHints, which merged information obtained * from query parameter binding and the data set parameter definition * */ Collection resolveDataSetParameters( boolean evaluateValue ) throws DataException { List paramDefns = this.dsRT.getParameters( ); int nParams = paramDefns == null ? 0 : paramDefns.size( ); // array of parameter hints ParameterHint[] paramHints = new ParameterHint[nParams]; // whether corresponding item in paramHints has been bound boolean[] bindingResolved = new boolean[nParams]; // First create param hints for all data set params for ( int i = 0; i < nParams; i++ ) { IParameterDefinition paramDefn = (IParameterDefinition) paramDefns.get( i ); paramHints[i] = createParameterHint( paramDefn, paramDefn.getDefaultInputValue( ) ); bindingResolved[i] = false; // Can the data set RT provide an input parameter value? (this has the highest // priority, over bindings) if ( paramDefn.isInputMode( ) && paramDefn.getName( ) != null ) { Object paramValue = DataSetRuntime.UNSET_VALUE; try { paramValue = this.dsRT.getInputParameterValue( paramDefn.getName( ) ); } catch ( BirtException e ) { // This is unexpected; the parameter must be in the list assert false; throw DataException.wrap( e ); } if ( paramValue != DataSetRuntime.UNSET_VALUE ) { + if ( paramHints[i].getDataType( ) == null ) //for AnyType parameter + { + if ( paramValue != null ) + { + Class clazz = paramValue.getClass( ); + paramHints[i].setDataType( clazz ); + } + else + { + //AnyType parameter and the parameter value is null + paramHints[i].setDataType( String.class ); + } + } String paramValueStr = this.getParameterValueString( paramHints[i].getDataType( ), paramValue ); paramHints[i].setDefaultInputValue( paramValueStr ); bindingResolved[i] = true; } } } if ( evaluateValue ) { Context cx = null; cx = Context.enter( ); try { // Resolve parameter bindings // Parameter values are determined in the following order of priority // (1) Input param values set by scripts (already resolved above) // (2) Query parameter bindings // (3) Data set parameter bindings resolveParameterBindings( this.queryDefn.getInputParamBindings( ), paramHints, bindingResolved, cx ); resolveParameterBindings( this.dsRT.getInputParamBindings( ), paramHints, bindingResolved, cx ); } finally { if ( cx != null ) Context.exit( ); } } return Arrays.asList( paramHints ); } /** * Resolve a list of parameter bindings and update the hints * @param cx JS context to evaluate binding. If null, binding does not need to be evaluated */ private void resolveParameterBindings( Collection bindings, ParameterHint[] paramHints, boolean[] bindingResolved, Context cx ) throws DataException { if ( bindings == null ) return; Iterator it = bindings.iterator( ); while ( it.hasNext( ) ) { resolveParameterBinding( (IInputParameterBinding) it.next( ), paramHints, bindingResolved, cx ); } } /** * Resolve a parameter binding and update the hints * @param cx JS context to evaluate binding. If null, binding does not need to be evaluated */ private void resolveParameterBinding( IInputParameterBinding binding, ParameterHint[] paramHints, boolean[] bindingResolved, Context cx ) throws DataException { // Find the hint which matches the binding int i = findParameterHint( paramHints, binding.getPosition( ), binding.getName( ) ); if ( i < 0 ) { // A binding exists but the data set has no definition for the // bound parameter, log an error and ignore the param if ( logger != null ) logger.warning( "Ignored binding defined for non-exising data set parameter: " //$NON-NLS-1$ + "name=" //$NON-NLS-1$ + binding.getName( ) + ", position=" //$NON-NLS-1$ + binding.getPosition( ) ); } // Do not set binding value if the parameter has already been resolved // (e.g., query binding has already been evaluated for this param, and // we are now checking data set binding for the same param ) else if ( !bindingResolved[i] ) { Object value = ( cx != null ) ? evaluateInputParameterValue( this.scope, cx, binding ) : binding.getExpr( ); //binding.getExpr()??? if ( paramHints[i].getDataType( ) == null ) //for AnyType parameter { if ( value != null ) { Class clazz = value.getClass( ); paramHints[i].setDataType( clazz ); } else { //AnyType parameter and the parameter value is null paramHints[i].setDataType( String.class ); } } String valueStr = getParameterValueString( paramHints[i].getDataType( ), value ); paramHints[i].setDefaultInputValue( valueStr ); bindingResolved[i] = true; // Also give the value to data set RT for script access if ( cx != null && paramHints[i].isInputMode( ) && paramHints[i].getName( ) != null ) { try { this.dsRT.setInputParameterValue( paramHints[i].getName( ), value ); } catch ( BirtException e ) { // Unexpected assert false; throw DataException.wrap( e ); } } } } /** * Find index of matching parameter hint in paramHints array, based on * param name or position. * Returns index of param hint found in array, or -1 if no match */ private int findParameterHint( ParameterHint[] hints, int position, String name ) { for ( int i = 0; i < hints.length; i++ ) { ParameterHint paramHint = hints[i]; if ( position <= 0 ) { if ( paramHint.getName( ).equalsIgnoreCase( name ) ) return i; } else { if ( paramHint.getPosition( ) == position ) return i; } } return -1; } /** * @param scope * @param cx * @param iParamBind * @return * @throws DataException */ private Object evaluateInputParameterValue( Scriptable scope, Context cx, IInputParameterBinding iParamBind ) throws DataException { // Evaluate Expression: // If the expression has been prepared, // use its handle to getValue() from outerResultIterator // else use Rhino to evaluate in corresponding scope Object evaluateResult = null; Scriptable evaluateScope = scope; try { evaluateResult = ExprEvaluateUtil.evaluateRawExpression2( iParamBind.getExpr( ), outerResults == null ? evaluateScope : outerResults.getQueryScope( ) ); } catch ( BirtException e ) { // do not expect a exception here. DataException dataEx = new DataException( ResourceConstants.UNEXPECTED_ERROR, e ); if ( logger != null ) logger.logp( Level.FINE, PreparedOdaDSQuery.class.getName( ), "getMergedParameters", //$NON-NLS-1$ "Error occurs in IQueryResults.getResultIterator()", //$NON-NLS-1$ e ); throw dataEx; } //TODO throw DataException // if( evaluateResult instanceof DataExceptionMocker ) // { // BirtException e = ((DataExceptionMocker) evaluateResult).getCause( ); // DataException dataEx = new DataException( ResourceConstants.UNEXPECTED_ERROR, // e ); // if ( logger != null ) // logger.logp( Level.FINE, // PreparedOdaDSQuery.class.getName( ), // "getMergedParameters", // "Error occurs in IQueryResults.getResultIterator()", // e ); // throw dataEx; // } // if ( evaluateResult == null ) // throw new DataException( ResourceConstants.DEFAULT_INPUT_PARAMETER_VALUE_CANNOT_BE_NULL ); return evaluateResult; } /** * Converts a parameter value to a String expected by ParameterHint */ private String getParameterValueString( Class paramType, Object paramValue ) throws DataException { if ( paramValue instanceof String ) return (String) paramValue; // Type conversion note: An integer constant like "1" will be // interpreted as a floating number by Rhino, which will then be converted // to "1.0", which some drivers don't like. // So we will first convert the value to the type required by the input // parameter, then convert it to String. This guarantees that an input // value "1" will be pass on as "1", and not "1.0" try { paramValue = DataTypeUtil.convert( paramValue, paramType ); if( paramValue instanceof Date ) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); //$NON-NLS-1$ return sdf.format( (Date)paramValue ); } if( paramValue != null ) { return paramValue.toString( ); } return null; } catch ( BirtException e ) { throw new DataException( ResourceConstants.DATATYPEUTIL_ERROR, e ); } } /** * Create a parameter hint based on Parameter definition and value * @param paramDefn * @param evaValue */ private ParameterHint createParameterHint( IParameterDefinition paramDefn, Object paramValue ) throws DataException { ParameterHint parameterHint = new ParameterHint( paramDefn.getName( ), paramDefn.isInputMode( ), paramDefn.isOutputMode( ) ); if ( paramDefn.getPosition( ) > 0 ) parameterHint.setPosition( paramDefn.getPosition( ) ); parameterHint.setNativeName( paramDefn.getNativeName() ); Class dataTypeClass = DataType.getClass( paramDefn.getType( ) ); parameterHint.setNativeDataType( paramDefn.getNativeType() ); parameterHint.setIsInputOptional( paramDefn.isInputOptional( ) ); if ( parameterHint.isInputMode( ) ) parameterHint.setDefaultInputValue( getParameterValueString( dataTypeClass, paramValue ) ); parameterHint.setIsNullable( paramDefn.isNullable( ) ); //ParameterHint does not support AnyType //the real type for AnyType is determined by the real parameter value if ( dataTypeClass!= AnyType.class ) { if( dataTypeClass == Blob.class ) parameterHint.setDataType( IBlob.class ); else if ( dataTypeClass == Clob.class ) parameterHint.setDataType( IClob.class ); else parameterHint.setDataType( dataTypeClass ); } return parameterHint; } }
true
true
Collection resolveDataSetParameters( boolean evaluateValue ) throws DataException { List paramDefns = this.dsRT.getParameters( ); int nParams = paramDefns == null ? 0 : paramDefns.size( ); // array of parameter hints ParameterHint[] paramHints = new ParameterHint[nParams]; // whether corresponding item in paramHints has been bound boolean[] bindingResolved = new boolean[nParams]; // First create param hints for all data set params for ( int i = 0; i < nParams; i++ ) { IParameterDefinition paramDefn = (IParameterDefinition) paramDefns.get( i ); paramHints[i] = createParameterHint( paramDefn, paramDefn.getDefaultInputValue( ) ); bindingResolved[i] = false; // Can the data set RT provide an input parameter value? (this has the highest // priority, over bindings) if ( paramDefn.isInputMode( ) && paramDefn.getName( ) != null ) { Object paramValue = DataSetRuntime.UNSET_VALUE; try { paramValue = this.dsRT.getInputParameterValue( paramDefn.getName( ) ); } catch ( BirtException e ) { // This is unexpected; the parameter must be in the list assert false; throw DataException.wrap( e ); } if ( paramValue != DataSetRuntime.UNSET_VALUE ) { String paramValueStr = this.getParameterValueString( paramHints[i].getDataType( ), paramValue ); paramHints[i].setDefaultInputValue( paramValueStr ); bindingResolved[i] = true; } } } if ( evaluateValue ) { Context cx = null; cx = Context.enter( ); try { // Resolve parameter bindings // Parameter values are determined in the following order of priority // (1) Input param values set by scripts (already resolved above) // (2) Query parameter bindings // (3) Data set parameter bindings resolveParameterBindings( this.queryDefn.getInputParamBindings( ), paramHints, bindingResolved, cx ); resolveParameterBindings( this.dsRT.getInputParamBindings( ), paramHints, bindingResolved, cx ); } finally { if ( cx != null ) Context.exit( ); } } return Arrays.asList( paramHints ); }
Collection resolveDataSetParameters( boolean evaluateValue ) throws DataException { List paramDefns = this.dsRT.getParameters( ); int nParams = paramDefns == null ? 0 : paramDefns.size( ); // array of parameter hints ParameterHint[] paramHints = new ParameterHint[nParams]; // whether corresponding item in paramHints has been bound boolean[] bindingResolved = new boolean[nParams]; // First create param hints for all data set params for ( int i = 0; i < nParams; i++ ) { IParameterDefinition paramDefn = (IParameterDefinition) paramDefns.get( i ); paramHints[i] = createParameterHint( paramDefn, paramDefn.getDefaultInputValue( ) ); bindingResolved[i] = false; // Can the data set RT provide an input parameter value? (this has the highest // priority, over bindings) if ( paramDefn.isInputMode( ) && paramDefn.getName( ) != null ) { Object paramValue = DataSetRuntime.UNSET_VALUE; try { paramValue = this.dsRT.getInputParameterValue( paramDefn.getName( ) ); } catch ( BirtException e ) { // This is unexpected; the parameter must be in the list assert false; throw DataException.wrap( e ); } if ( paramValue != DataSetRuntime.UNSET_VALUE ) { if ( paramHints[i].getDataType( ) == null ) //for AnyType parameter { if ( paramValue != null ) { Class clazz = paramValue.getClass( ); paramHints[i].setDataType( clazz ); } else { //AnyType parameter and the parameter value is null paramHints[i].setDataType( String.class ); } } String paramValueStr = this.getParameterValueString( paramHints[i].getDataType( ), paramValue ); paramHints[i].setDefaultInputValue( paramValueStr ); bindingResolved[i] = true; } } } if ( evaluateValue ) { Context cx = null; cx = Context.enter( ); try { // Resolve parameter bindings // Parameter values are determined in the following order of priority // (1) Input param values set by scripts (already resolved above) // (2) Query parameter bindings // (3) Data set parameter bindings resolveParameterBindings( this.queryDefn.getInputParamBindings( ), paramHints, bindingResolved, cx ); resolveParameterBindings( this.dsRT.getInputParamBindings( ), paramHints, bindingResolved, cx ); } finally { if ( cx != null ) Context.exit( ); } } return Arrays.asList( paramHints ); }
diff --git a/src/com/android/contacts/quickcontact/QuickContactWindow.java b/src/com/android/contacts/quickcontact/QuickContactWindow.java index 454ac70c8..cf2e81d11 100644 --- a/src/com/android/contacts/quickcontact/QuickContactWindow.java +++ b/src/com/android/contacts/quickcontact/QuickContactWindow.java @@ -1,1718 +1,1723 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.quickcontact; import com.android.contacts.Collapser; import com.android.contacts.ContactPresenceIconUtil; import com.android.contacts.ContactsUtils; import com.android.contacts.R; import com.android.contacts.model.BaseAccountType; import com.android.contacts.model.BaseAccountType.DataKind; import com.android.contacts.model.AccountTypes; import com.android.contacts.util.Constants; import com.android.contacts.util.DataStatus; import com.android.contacts.util.NotifyingAsyncQueryHandler; import com.android.contacts.util.PhoneCapabilityTester; import com.android.internal.policy.PolicyManager; import com.google.android.collect.Sets; import android.content.ActivityNotFoundException; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.SipAddress; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.QuickContact; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.StatusUpdates; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.ActionMode; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.Window; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Window that shows QuickContact dialog for a specific {@link Contacts#_ID}. */ public class QuickContactWindow implements Window.Callback, NotifyingAsyncQueryHandler.AsyncQueryListener, View.OnClickListener, AbsListView.OnItemClickListener, CompoundButton.OnCheckedChangeListener, KeyEvent.Callback, OnGlobalLayoutListener { private static final String TAG = "QuickContactWindow"; /** * Interface used to allow the person showing a {@link QuickContactWindow} to * know when the window has been dismissed. */ public interface OnDismissListener { public void onDismiss(QuickContactWindow dialog); } /** * Custom layout the sole purpose of which is to intercept the BACK key and * close QC even when the soft keyboard is open. */ public static class RootLayout extends RelativeLayout { QuickContactWindow mQuickContactWindow; public RootLayout(Context context, AttributeSet attrs) { super(context, attrs); } /** * Intercepts the BACK key event and dismisses QuickContact window. */ @Override public boolean dispatchKeyEventPreIme(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { mQuickContactWindow.onBackPressed(); return true; } else { return super.dispatchKeyEventPreIme(event); } } } private final Context mContext; private final LayoutInflater mInflater; private final WindowManager mWindowManager; private Window mWindow; private View mDecor; private final Rect mRect = new Rect(); private boolean mDismissed = false; private boolean mQuerying = false; private boolean mShowing = false; private NotifyingAsyncQueryHandler mHandler; private OnDismissListener mDismissListener; private ResolveCache mResolveCache; private Uri mLookupUri; private Rect mAnchor; private int mShadowHoriz; private int mShadowVert; private int mShadowTouch; private int mScreenWidth; private int mScreenHeight; private int mRequestedY; private boolean mHasValidSocial = false; private boolean mMakePrimary = false; private ImageView mArrowUp; private ImageView mArrowDown; private int mMode; private RootLayout mRootView; private View mHeader; private HorizontalScrollView mTrackScroll; private ViewGroup mTrack; private Animation mTrackAnim; private View mFooter; private View mFooterDisambig; private ListView mResolveList; private CheckableImageView mLastAction; private CheckBox mSetPrimaryCheckBox; private int mWindowRecycled = 0; private int mActionRecycled = 0; /** * Set of {@link Action} that are associated with the aggregate currently * displayed by this dialog, represented as a map from {@link String} * MIME-type to {@link ActionList}. */ private ActionMap mActions = new ActionMap(); /** * Pool of unused {@link CheckableImageView} that have previously been * inflated, and are ready to be recycled through {@link #obtainView()}. */ private LinkedList<View> mActionPool = new LinkedList<View>(); private String[] mExcludeMimes; /** * {@link #PRECEDING_MIMETYPES} and {@link #FOLLOWING_MIMETYPES} are used to sort MIME-types. * * <p>The MIME-types in {@link #PRECEDING_MIMETYPES} appear in the front of the dialog, * in the order in the array. * * <p>The ones in {@link #FOLLOWING_MIMETYPES} appear in the end of the dialog, in alphabetical * order. * * <p>The rest go between them, in the order in the array. */ private static final String[] PRECEDING_MIMETYPES = new String[] { Phone.CONTENT_ITEM_TYPE, SipAddress.CONTENT_ITEM_TYPE, Contacts.CONTENT_ITEM_TYPE, Constants.MIME_SMS_ADDRESS, Email.CONTENT_ITEM_TYPE, }; /** * See {@link #PRECEDING_MIMETYPES}. */ private static final String[] FOLLOWING_MIMETYPES = new String[] { StructuredPostal.CONTENT_ITEM_TYPE, Website.CONTENT_ITEM_TYPE, }; /** * Specific list {@link ApplicationInfo#packageName} of apps that are * prefered <strong>only</strong> for the purposes of default icons when * multiple {@link ResolveInfo} are found to match. This only happens when * the user has not selected a default app yet, and they will still be * presented with the system disambiguation dialog. */ private static final HashSet<String> sPreferResolve = Sets.newHashSet( "com.android.email", "com.android.calendar", "com.android.contacts", "com.android.mms", "com.android.phone", "com.android.browser"); private static final int TOKEN_DATA = 1; static final boolean LOGD = false; static final boolean TRACE_LAUNCH = false; static final String TRACE_TAG = "quickcontact"; /** * Prepare a dialog to show in the given {@link Context}. */ public QuickContactWindow(Context context) { mContext = new ContextThemeWrapper(context, R.style.QuickContact); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); mWindow = PolicyManager.makeNewWindow(mContext); mWindow.setCallback(this); mWindow.setWindowManager(mWindowManager, null, null); mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED); mWindow.setContentView(R.layout.quickcontact); mRootView = (RootLayout)mWindow.findViewById(R.id.root); mRootView.mQuickContactWindow = this; mRootView.setFocusable(true); mRootView.setFocusableInTouchMode(true); mRootView.setDescendantFocusability(RootLayout.FOCUS_AFTER_DESCENDANTS); mArrowUp = (ImageView)mWindow.findViewById(R.id.arrow_up); mArrowDown = (ImageView)mWindow.findViewById(R.id.arrow_down); mResolveCache = new ResolveCache(mContext); final Resources res = mContext.getResources(); mShadowHoriz = res.getDimensionPixelSize(R.dimen.quickcontact_shadow_horiz); mShadowVert = res.getDimensionPixelSize(R.dimen.quickcontact_shadow_vert); mShadowTouch = res.getDimensionPixelSize(R.dimen.quickcontact_shadow_touch); mScreenWidth = mWindowManager.getDefaultDisplay().getWidth(); mScreenHeight = mWindowManager.getDefaultDisplay().getHeight(); mTrack = (ViewGroup)mWindow.findViewById(R.id.quickcontact); mTrackScroll = (HorizontalScrollView)mWindow.findViewById(R.id.scroll); mFooter = mWindow.findViewById(R.id.footer); mFooterDisambig = mWindow.findViewById(R.id.footer_disambig); mResolveList = (ListView)mWindow.findViewById(android.R.id.list); mSetPrimaryCheckBox = (CheckBox)mWindow.findViewById(android.R.id.checkbox); mSetPrimaryCheckBox.setOnCheckedChangeListener(this); // Prepare track entrance animation mTrackAnim = AnimationUtils.loadAnimation(mContext, R.anim.quickcontact); mTrackAnim.setInterpolator(new Interpolator() { public float getInterpolation(float t) { // Pushes past the target area, then snaps back into place. // Equation for graphing: 1.2-((x*1.6)-1.1)^2 final float inner = (t * 1.55f) - 1.1f; return 1.2f - inner * inner; } }); mHandler = new NotifyingAsyncQueryHandler(mContext, this); } /** * Prepare a dialog to show in the given {@link Context}, and notify the * given {@link OnDismissListener} each time this dialog is dismissed. */ public QuickContactWindow(Context context, OnDismissListener dismissListener) { this(context); mDismissListener = dismissListener; } private View getHeaderView(int mode) { View header = null; switch (mode) { case QuickContact.MODE_SMALL: header = mWindow.findViewById(R.id.header_small); break; case QuickContact.MODE_MEDIUM: header = mWindow.findViewById(R.id.header_medium); break; case QuickContact.MODE_LARGE: header = mWindow.findViewById(R.id.header_large); break; } if (header instanceof ViewStub) { // Inflate actual header if we picked a stub final ViewStub stub = (ViewStub)header; header = stub.inflate(); } else if (header != null) { header.setVisibility(View.VISIBLE); } return header; } /** * Start showing a dialog for the given {@link Contacts#_ID} pointing * towards the given location. */ public synchronized void show(Uri lookupUri, Rect anchor, int mode, String[] excludeMimes) { if (mQuerying || mShowing) { Log.w(TAG, "dismissing before showing"); dismissInternal(); } if (TRACE_LAUNCH && !android.os.Debug.isMethodTracingActive()) { android.os.Debug.startMethodTracing(TRACE_TAG); } // Validate incoming parameters final boolean validMode = (mode == QuickContact.MODE_SMALL || mode == QuickContact.MODE_MEDIUM || mode == QuickContact.MODE_LARGE); if (!validMode) { throw new IllegalArgumentException("Invalid mode, expecting MODE_LARGE, " + "MODE_MEDIUM, or MODE_SMALL"); } if (anchor == null) { throw new IllegalArgumentException("Missing anchor rectangle"); } // Prepare header view for requested mode mLookupUri = lookupUri; mAnchor = new Rect(anchor); mMode = mode; mExcludeMimes = excludeMimes; mHeader = getHeaderView(mode); setHeaderText(R.id.name, R.string.quickcontact_missing_name); setHeaderText(R.id.status, null); setHeaderText(R.id.timestamp, null); setHeaderImage(R.id.presence, null); resetTrack(); // We need to have a focused view inside the QuickContact window so // that the BACK key event can be intercepted mRootView.requestFocus(); mHasValidSocial = false; mDismissed = false; mQuerying = true; // Start background query for data, but only select photo rows when they // directly match the super-primary PHOTO_ID. final Uri dataUri = getDataUri(lookupUri); mHandler.cancelOperation(TOKEN_DATA); // Only request photo data when required by mode if (mMode == QuickContact.MODE_LARGE) { // Select photos, but only super-primary mHandler.startQuery(TOKEN_DATA, lookupUri, dataUri, DataQuery.PROJECTION, Data.MIMETYPE + "!=? OR (" + Data.MIMETYPE + "=? AND " + Data._ID + "=" + Contacts.PHOTO_ID + ")", new String[] { Photo.CONTENT_ITEM_TYPE, Photo.CONTENT_ITEM_TYPE }, null); } else { // Exclude all photos from cursor mHandler.startQuery(TOKEN_DATA, lookupUri, dataUri, DataQuery.PROJECTION, Data.MIMETYPE + "!=?", new String[] { Photo.CONTENT_ITEM_TYPE }, null); } } /** * Build a {@link Uri} into the {@link Data} table for the requested * {@link Contacts#CONTENT_LOOKUP_URI} style {@link Uri}. */ private Uri getDataUri(Uri lookupUri) { // TODO: Formalize method of extracting LOOKUP_KEY final List<String> path = lookupUri.getPathSegments(); final boolean validLookup = path.size() >= 3 && "lookup".equals(path.get(1)); if (!validLookup) { // We only accept valid lookup-style Uris throw new IllegalArgumentException("Expecting lookup-style Uri"); } else if (path.size() == 3) { // No direct _ID provided, so force a lookup lookupUri = Contacts.lookupContact(mContext.getContentResolver(), lookupUri); } final long contactId = ContentUris.parseId(lookupUri); return Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId), Contacts.Data.CONTENT_DIRECTORY); } /** * Show the correct call-out arrow based on a {@link R.id} reference. */ private void showArrow(int whichArrow, int requestedX) { final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown; final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp; final int arrowWidth = mArrowUp.getMeasuredWidth(); showArrow.setVisibility(View.VISIBLE); ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams(); param.leftMargin = requestedX - arrowWidth / 2; hideArrow.setVisibility(View.INVISIBLE); } /** * Actual internal method to show this dialog. Called only by * {@link #considerShowing()} when all data requirements have been met. */ private void showInternal() { mDecor = mWindow.getDecorView(); mDecor.getViewTreeObserver().addOnGlobalLayoutListener(this); WindowManager.LayoutParams l = mWindow.getAttributes(); l.width = mScreenWidth + mShadowHoriz + mShadowHoriz; l.height = WindowManager.LayoutParams.WRAP_CONTENT; // Force layout measuring pass so we have baseline numbers mDecor.measure(l.width, l.height); final int blockHeight = mDecor.getMeasuredHeight(); l.gravity = Gravity.TOP | Gravity.LEFT; l.x = -mShadowHoriz; if (mAnchor.top > blockHeight) { // Show downwards callout when enough room, aligning bottom block // edge with top of anchor area, and adjusting to inset arrow. showArrow(R.id.arrow_down, mAnchor.centerX()); l.y = mAnchor.top - blockHeight + mShadowVert; l.windowAnimations = R.style.QuickContactAboveAnimation; } else { // Otherwise show upwards callout, aligning block top with bottom of // anchor area, and adjusting to inset arrow. showArrow(R.id.arrow_up, mAnchor.centerX()); l.y = mAnchor.bottom - mShadowVert; l.windowAnimations = R.style.QuickContactBelowAnimation; } l.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; mRequestedY = l.y; mWindowManager.addView(mDecor, l); mShowing = true; mQuerying = false; mDismissed = false; mTrack.startAnimation(mTrackAnim); if (TRACE_LAUNCH) { android.os.Debug.stopMethodTracing(); Log.d(TAG, "Window recycled " + mWindowRecycled + " times, chiclets " + mActionRecycled + " times"); } } /** {@inheritDoc} */ public void onGlobalLayout() { layoutInScreen(); } /** * Adjust vertical {@link WindowManager.LayoutParams} to fit window as best * as possible, shifting up to display content as needed. */ private void layoutInScreen() { if (!mShowing) return; final WindowManager.LayoutParams l = mWindow.getAttributes(); final int originalY = l.y; final int blockHeight = mDecor.getHeight(); l.y = mRequestedY; if (mRequestedY + blockHeight > mScreenHeight) { // Shift up from bottom when overflowing l.y = mScreenHeight - blockHeight; } if (originalY != l.y) { // Only update when value is changed mWindow.setAttributes(l); } } /** * Dismiss this dialog if showing. */ public synchronized void dismiss() { // Notify any listeners that we've been dismissed if (mDismissListener != null) { mDismissListener.onDismiss(this); } dismissInternal(); } private void dismissInternal() { // Remove any attached window decor for recycling boolean hadDecor = mDecor != null; if (hadDecor) { mWindowManager.removeView(mDecor); mWindowRecycled++; mDecor.getViewTreeObserver().removeGlobalOnLayoutListener(this); mDecor = null; mWindow.closeAllPanels(); } mShowing = false; mDismissed = true; // Cancel any pending queries mHandler.cancelOperation(TOKEN_DATA); mQuerying = false; // Completely hide header and reset track mHeader.setVisibility(View.GONE); resetTrack(); } /** * Reset track to initial state, recycling any chiclets. */ private void resetTrack() { // Release reference to last chiclet mLastAction = null; // Clear track actions and scroll to hard left mResolveCache.clear(); mActions.clear(); // Recycle any chiclets in use while (mTrack.getChildCount() > 2) { this.releaseView(mTrack.getChildAt(1)); mTrack.removeViewAt(1); } mTrackScroll.fullScroll(View.FOCUS_LEFT); mWasDownArrow = false; // Clear any primary requests mMakePrimary = false; mSetPrimaryCheckBox.setChecked(false); setResolveVisible(false, null); } /** * Consider showing this window, which will only call through to * {@link #showInternal()} when all data items are present. */ private void considerShowing() { if (!mShowing && !mDismissed) { if (mMode == QuickContact.MODE_MEDIUM && !mHasValidSocial) { // Missing valid social, swap medium for small header mHeader.setVisibility(View.GONE); mHeader = getHeaderView(QuickContact.MODE_SMALL); } // All queries have returned, pull curtain showInternal(); } } /** {@inheritDoc} */ public synchronized void onQueryComplete(int token, Object cookie, Cursor cursor) { // Bail early when query is stale if (cookie != mLookupUri) return; if (cursor == null) { // Problem while running query, so bail without showing Log.w(TAG, "Missing cursor for token=" + token); this.dismiss(); return; } handleData(cursor); if (!cursor.isClosed()) { cursor.close(); } considerShowing(); } /** Assign this string to the view, if found in {@link #mHeader}. */ private void setHeaderText(int id, int resId) { setHeaderText(id, mContext.getResources().getText(resId)); } /** Assign this string to the view, if found in {@link #mHeader}. */ private void setHeaderText(int id, CharSequence value) { final View view = mHeader.findViewById(id); if (view instanceof TextView) { ((TextView)view).setText(value); view.setVisibility(TextUtils.isEmpty(value) ? View.GONE : View.VISIBLE); } } /** Assign this image to the view, if found in {@link #mHeader}. */ private void setHeaderImage(int id, Drawable drawable) { final View view = mHeader.findViewById(id); if (view instanceof ImageView) { ((ImageView)view).setImageDrawable(drawable); view.setVisibility(drawable == null ? View.GONE : View.VISIBLE); } } /** * Find the QuickContact-specific presence icon for showing in chiclets. */ private Drawable getTrackPresenceIcon(int status) { int resId; switch (status) { case StatusUpdates.AVAILABLE: resId = R.drawable.quickcontact_slider_presence_active; break; case StatusUpdates.IDLE: case StatusUpdates.AWAY: resId = R.drawable.quickcontact_slider_presence_away; break; case StatusUpdates.DO_NOT_DISTURB: resId = R.drawable.quickcontact_slider_presence_busy; break; case StatusUpdates.INVISIBLE: resId = R.drawable.quickcontact_slider_presence_inactive; break; case StatusUpdates.OFFLINE: default: resId = R.drawable.quickcontact_slider_presence_inactive; } return mContext.getResources().getDrawable(resId); } /** Read {@link String} from the given {@link Cursor}. */ private static String getAsString(Cursor cursor, String columnName) { final int index = cursor.getColumnIndex(columnName); return cursor.getString(index); } /** Read {@link Integer} from the given {@link Cursor}. */ private static int getAsInt(Cursor cursor, String columnName) { final int index = cursor.getColumnIndex(columnName); return cursor.getInt(index); } /** * Abstract definition of an action that could be performed, along with * string description and icon. */ private interface Action extends Collapser.Collapsible<Action> { public CharSequence getHeader(); public CharSequence getBody(); public String getMimeType(); public Drawable getFallbackIcon(); /** * Build an {@link Intent} that will perform this action. */ public Intent getIntent(); /** * Checks if the contact data for this action is primary. */ public Boolean isPrimary(); /** * Returns a lookup (@link Uri) for the contact data item. */ public Uri getDataUri(); } /** * Description of a specific {@link Data#_ID} item, with style information * defined by a {@link DataKind}. */ private static class DataAction implements Action { private final Context mContext; private final DataKind mKind; private final String mMimeType; private CharSequence mHeader; private CharSequence mBody; private Intent mIntent; private boolean mAlternate; private Uri mDataUri; private boolean mIsPrimary; /** * Create an action from common {@link Data} elements. */ public DataAction(Context context, String mimeType, DataKind kind, long dataId, Cursor cursor) { mContext = context; mKind = kind; mMimeType = mimeType; // Inflate strings from cursor mAlternate = Constants.MIME_SMS_ADDRESS.equals(mimeType); if (mAlternate && mKind.actionAltHeader != null) { mHeader = mKind.actionAltHeader.inflateUsing(context, cursor); } else if (mKind.actionHeader != null) { mHeader = mKind.actionHeader.inflateUsing(context, cursor); } if (getAsInt(cursor, Data.IS_SUPER_PRIMARY) != 0) { mIsPrimary = true; } if (mKind.actionBody != null) { mBody = mKind.actionBody.inflateUsing(context, cursor); } mDataUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId); // Handle well-known MIME-types with special care if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) { if (PhoneCapabilityTester.isPhone(mContext)) { final String number = getAsString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(number)) { final Uri callUri = Uri.fromParts(Constants.SCHEME_TEL, number, null); mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri); } } } else if (SipAddress.CONTENT_ITEM_TYPE.equals(mimeType)) { if (PhoneCapabilityTester.isSipPhone(mContext)) { final String address = getAsString(cursor, SipAddress.SIP_ADDRESS); if (!TextUtils.isEmpty(address)) { final Uri callUri = Uri.fromParts(Constants.SCHEME_SIP, address, null); mIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, callUri); // Note that this item will get a SIP-specific variant // of the "call phone" icon, rather than the standard // app icon for the Phone app (which we show for // regular phone numbers.) That's because the phone // app explicitly specifies an android:icon attribute // for the SIP-related intent-filters in its manifest. } } } else if (Constants.MIME_SMS_ADDRESS.equals(mimeType)) { if (PhoneCapabilityTester.isSmsIntentRegistered(mContext)) { final String number = getAsString(cursor, Phone.NUMBER); if (!TextUtils.isEmpty(number)) { final Uri smsUri = Uri.fromParts(Constants.SCHEME_SMSTO, number, null); mIntent = new Intent(Intent.ACTION_SENDTO, smsUri); } } } else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) { final String address = getAsString(cursor, Email.DATA); if (!TextUtils.isEmpty(address)) { final Uri mailUri = Uri.fromParts(Constants.SCHEME_MAILTO, address, null); mIntent = new Intent(Intent.ACTION_SENDTO, mailUri); } } else if (Website.CONTENT_ITEM_TYPE.equals(mimeType)) { final String url = getAsString(cursor, Website.URL); if (!TextUtils.isEmpty(url)) { mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); } } else if (Im.CONTENT_ITEM_TYPE.equals(mimeType)) { final boolean isEmail = Email.CONTENT_ITEM_TYPE.equals( getAsString(cursor, Data.MIMETYPE)); if (isEmail || isProtocolValid(cursor)) { final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : getAsInt(cursor, Im.PROTOCOL); if (isEmail) { // Use Google Talk string when using Email, and clear data // Uri so we don't try saving Email as primary. mHeader = context.getText(R.string.chat_gtalk); mDataUri = null; } String host = getAsString(cursor, Im.CUSTOM_PROTOCOL); String data = getAsString(cursor, isEmail ? Email.DATA : Im.DATA); if (protocol != Im.PROTOCOL_CUSTOM) { // Try bringing in a well-known host for specific protocols host = ContactsUtils.lookupProviderNameFromId(protocol); } if (!TextUtils.isEmpty(host) && !TextUtils.isEmpty(data)) { final String authority = host.toLowerCase(); final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority( authority).appendPath(data).build(); mIntent = new Intent(Intent.ACTION_SENDTO, imUri); } } } if (mIntent == null) { // Otherwise fall back to default VIEW action mIntent = new Intent(Intent.ACTION_VIEW, mDataUri); } // Always launch as new task, since we're like a launcher mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); } private boolean isProtocolValid(Cursor cursor) { final int columnIndex = cursor.getColumnIndex(Im.PROTOCOL); if (cursor.isNull(columnIndex)) { return false; } try { Integer.valueOf(cursor.getString(columnIndex)); } catch (NumberFormatException e) { return false; } return true; } /** {@inheritDoc} */ public CharSequence getHeader() { return mHeader; } /** {@inheritDoc} */ public CharSequence getBody() { return mBody; } /** {@inheritDoc} */ public String getMimeType() { return mMimeType; } /** {@inheritDoc} */ public Uri getDataUri() { return mDataUri; } /** {@inheritDoc} */ public Boolean isPrimary() { return mIsPrimary; } /** {@inheritDoc} */ public Drawable getFallbackIcon() { // Bail early if no valid resources final String resPackageName = mKind.resPackageName; if (resPackageName == null) return null; final PackageManager pm = mContext.getPackageManager(); if (mAlternate && mKind.iconAltRes != -1) { return pm.getDrawable(resPackageName, mKind.iconAltRes, null); } else if (mKind.iconRes != -1) { return pm.getDrawable(resPackageName, mKind.iconRes, null); } else { return null; } } /** {@inheritDoc} */ public Intent getIntent() { return mIntent; } /** {@inheritDoc} */ public boolean collapseWith(Action other) { if (!shouldCollapseWith(other)) { return false; } return true; } /** {@inheritDoc} */ public boolean shouldCollapseWith(Action t) { if (t == null) { return false; } if (!(t instanceof DataAction)) { Log.e(TAG, "t must be DataAction"); return false; } DataAction other = (DataAction)t; if (!ContactsUtils.areObjectsEqual(mKind, other.mKind)) { return false; } if (!ContactsUtils.shouldCollapse(mContext, mMimeType, mBody, other.mMimeType, other.mBody)) { return false; } if (!TextUtils.equals(mMimeType, other.mMimeType) || !ContactsUtils.areIntentActionEqual(mIntent, other.mIntent) ) { return false; } return true; } } /** * Specific action that launches the profile card. */ private static class ProfileAction implements Action { private final Context mContext; private final Uri mLookupUri; public ProfileAction(Context context, Uri lookupUri) { mContext = context; mLookupUri = lookupUri; } /** {@inheritDoc} */ public CharSequence getHeader() { return null; } /** {@inheritDoc} */ public CharSequence getBody() { return null; } /** {@inheritDoc} */ public String getMimeType() { return Contacts.CONTENT_ITEM_TYPE; } /** {@inheritDoc} */ public Drawable getFallbackIcon() { return mContext.getResources().getDrawable(R.drawable.ic_contacts_details); } /** {@inheritDoc} */ public Intent getIntent() { final Intent intent = new Intent(Intent.ACTION_VIEW, mLookupUri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } /** {@inheritDoc} */ public Boolean isPrimary() { return null; } /** {@inheritDoc} */ public Uri getDataUri() { return null; } /** {@inheritDoc} */ public boolean collapseWith(Action t) { return false; // Never dup. } /** {@inheritDoc} */ public boolean shouldCollapseWith(Action t) { return false; // Never dup. } } /** * Internally hold a cache of scaled icons based on {@link PackageManager} * queries, keyed internally on MIME-type. */ private static class ResolveCache { private PackageManager mPackageManager; /** * Cached entry holding the best {@link ResolveInfo} for a specific * MIME-type, along with a {@link SoftReference} to its icon. */ private static class Entry { public ResolveInfo bestResolve; public SoftReference<Drawable> icon; } private HashMap<String, Entry> mCache = new HashMap<String, Entry>(); public ResolveCache(Context context) { mPackageManager = context.getPackageManager(); } /** * Get the {@link Entry} best associated with the given {@link Action}, * or create and populate a new one if it doesn't exist. */ protected Entry getEntry(Action action) { final String mimeType = action.getMimeType(); Entry entry = mCache.get(mimeType); if (entry != null) return entry; entry = new Entry(); final Intent intent = action.getIntent(); if (intent != null) { final List<ResolveInfo> matches = mPackageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); // Pick first match, otherwise best found ResolveInfo bestResolve = null; final int size = matches.size(); if (size == 1) { bestResolve = matches.get(0); } else if (size > 1) { bestResolve = getBestResolve(intent, matches); } if (bestResolve != null) { final Drawable icon = bestResolve.loadIcon(mPackageManager); entry.bestResolve = bestResolve; entry.icon = new SoftReference<Drawable>(icon); } } mCache.put(mimeType, entry); return entry; } /** * Best {@link ResolveInfo} when multiple found. Ties are broken by * selecting first from the {QuickContactWindow#sPreferResolve} list of * preferred packages, second by apps that live on the system partition, * otherwise the app from the top of the list. This is * <strong>only</strong> used for selecting a default icon for * displaying in the track, and does not shortcut the system * {@link Intent} disambiguation dialog. */ protected ResolveInfo getBestResolve(Intent intent, List<ResolveInfo> matches) { // Try finding preferred activity, otherwise detect disambig final ResolveInfo foundResolve = mPackageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); final boolean foundDisambig = (foundResolve.match & IntentFilter.MATCH_CATEGORY_MASK) == 0; if (!foundDisambig) { // Found concrete match, so return directly return foundResolve; } // Accept any package from prefer list, otherwise first system app ResolveInfo firstSystem = null; for (ResolveInfo info : matches) { final boolean isSystem = (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; final boolean isPrefer = QuickContactWindow.sPreferResolve .contains(info.activityInfo.applicationInfo.packageName); if (isPrefer) return info; if (isSystem && firstSystem == null) firstSystem = info; } // Return first system found, otherwise first from list return firstSystem != null ? firstSystem : matches.get(0); } /** * Check {@link PackageManager} to see if any apps offer to handle the * given {@link Action}. */ public boolean hasResolve(Action action) { return getEntry(action).bestResolve != null; } /** * Find the best description for the given {@link Action}, usually used * for accessibility purposes. */ public CharSequence getDescription(Action action) { final CharSequence actionHeader = action.getHeader(); final ResolveInfo info = getEntry(action).bestResolve; if (!TextUtils.isEmpty(actionHeader)) { return actionHeader; } else if (info != null) { return info.loadLabel(mPackageManager); } else { return null; } } /** * Return the best icon for the given {@link Action}, which is usually * based on the {@link ResolveInfo} found through a * {@link PackageManager} query. */ public Drawable getIcon(Action action) { final SoftReference<Drawable> iconRef = getEntry(action).icon; return (iconRef == null) ? null : iconRef.get(); } public void clear() { mCache.clear(); } } /** * Provide a strongly-typed {@link LinkedList} that holds a list of * {@link Action} objects. */ private class ActionList extends ArrayList<Action> { } /** * Provide a simple way of collecting one or more {@link Action} objects * under a MIME-type key. */ private class ActionMap extends HashMap<String, ActionList> { private void collect(String mimeType, Action info) { // Create list for this MIME-type when needed ActionList collectList = get(mimeType); if (collectList == null) { collectList = new ActionList(); put(mimeType, collectList); } collectList.add(info); } } /** * Check if the given MIME-type appears in the list of excluded MIME-types * that the most-recent caller requested. */ private boolean isMimeExcluded(String mimeType) { if (mExcludeMimes == null) return false; for (String excludedMime : mExcludeMimes) { if (TextUtils.equals(excludedMime, mimeType)) { return true; } } return false; } /** * Handle the result from the {@link #TOKEN_DATA} query. */ private void handleData(Cursor cursor) { if (cursor == null) return; + if (cursor.getCount() == 0) { + Toast.makeText(mContext, R.string.invalidContactMessage, Toast.LENGTH_LONG).show(); + dismiss(); + return; + } if (!isMimeExcluded(Contacts.CONTENT_ITEM_TYPE)) { // Add the profile shortcut action final Action action = new ProfileAction(mContext, mLookupUri); mActions.collect(Contacts.CONTENT_ITEM_TYPE, action); } final DataStatus status = new DataStatus(); final AccountTypes sources = AccountTypes.getInstance(mContext); final ImageView photoView = (ImageView)mHeader.findViewById(R.id.photo); Bitmap photoBitmap = null; while (cursor.moveToNext()) { final long dataId = cursor.getLong(DataQuery._ID); final String accountType = cursor.getString(DataQuery.ACCOUNT_TYPE); final String mimeType = cursor.getString(DataQuery.MIMETYPE); // Handle any social status updates from this row status.possibleUpdate(cursor); // Skip this data item if MIME-type excluded if (isMimeExcluded(mimeType)) continue; // Handle photos included as data row if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) { final int colPhoto = cursor.getColumnIndex(Photo.PHOTO); final byte[] photoBlob = cursor.getBlob(colPhoto); if (photoBlob != null) { photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length); } continue; } final DataKind kind = sources.getKindOrFallback(accountType, mimeType, mContext, BaseAccountType.LEVEL_MIMETYPES); if (kind != null) { // Build an action for this data entry, find a mapping to a UI // element, build its summary from the cursor, and collect it // along with all others of this MIME-type. final Action action = new DataAction(mContext, mimeType, kind, dataId, cursor); considerAdd(action, mimeType); } // If phone number, also insert as text message action if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && kind != null) { final Action action = new DataAction(mContext, Constants.MIME_SMS_ADDRESS, kind, dataId, cursor); considerAdd(action, Constants.MIME_SMS_ADDRESS); } // Handle Email rows with presence data as Im entry final boolean hasPresence = !cursor.isNull(DataQuery.PRESENCE); if (hasPresence && Email.CONTENT_ITEM_TYPE.equals(mimeType)) { final DataKind imKind = sources.getKindOrFallback(accountType, Im.CONTENT_ITEM_TYPE, mContext, BaseAccountType.LEVEL_MIMETYPES); if (imKind != null) { final Action action = new DataAction(mContext, Im.CONTENT_ITEM_TYPE, imKind, dataId, cursor); considerAdd(action, Im.CONTENT_ITEM_TYPE); } } } if (cursor.moveToLast()) { // Read contact information from last data row final String name = cursor.getString(DataQuery.DISPLAY_NAME); final int presence = cursor.getInt(DataQuery.CONTACT_PRESENCE); final Drawable statusIcon = ContactPresenceIconUtil.getPresenceIcon(mContext, presence); setHeaderText(R.id.name, name); setHeaderImage(R.id.presence, statusIcon); } if (photoView != null) { // Place photo when discovered in data, otherwise hide photoView.setVisibility(photoBitmap != null ? View.VISIBLE : View.GONE); photoView.setImageBitmap(photoBitmap); } mHasValidSocial = status.isValid(); if (mHasValidSocial && mMode != QuickContact.MODE_SMALL) { // Update status when valid was found setHeaderText(R.id.status, status.getStatus()); setHeaderText(R.id.timestamp, status.getTimestampLabel(mContext)); } // Turn our list of actions into UI elements // Index where we start adding child views. int index = mTrack.getChildCount() - 1; // All the mime-types to add. final Set<String> containedTypes = new HashSet<String>(mActions.keySet()); boolean hasData = false; // First, add PRECEDING_MIMETYPES, which are most common. for (String mimeType : PRECEDING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Keep the current index to append non PRECEDING/FOLLOWING items. final int indexAfterPreceding = index; // Then, add FOLLOWING_MIMETYPES, which are least common. for (String mimeType : FOLLOWING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Go back to just after PRECEDING_MIMETYPES, and append the rest. index = indexAfterPreceding; final String[] remainingTypes = containedTypes.toArray(new String[containedTypes.size()]); if (remainingTypes.length > 0) hasData = true; Arrays.sort(remainingTypes); for (String mimeType : remainingTypes) { mTrack.addView(inflateAction(mimeType), index++); } // When there is no data to display, add a TextView to show the user there's no data if (!hasData) { View view = mInflater.inflate(R.layout.quickcontact_item_nodata, mTrack, false); mTrack.addView(view, index++); } } /** * Consider adding the given {@link Action}, which will only happen if * {@link PackageManager} finds an application to handle * {@link Action#getIntent()}. */ private void considerAdd(Action action, String mimeType) { if (mResolveCache.hasResolve(action)) { mActions.collect(mimeType, action); } } /** * Obtain a new {@link CheckableImageView} for a new chiclet, either by * recycling one from {@link #mActionPool}, or by inflating a new one. When * finished, use {@link #releaseView(View)} to return back into the pool for * later recycling. */ private synchronized View obtainView() { View view = mActionPool.poll(); if (view == null || QuickContactActivity.FORCE_CREATE) { view = mInflater.inflate(R.layout.quickcontact_item, mTrack, false); } return view; } /** * Return the given {@link CheckableImageView} into our internal pool for * possible recycling during another pass. */ private synchronized void releaseView(View view) { // Only add CheckableImageViews if (!(view instanceof CheckableImageView)) { return; } mActionPool.offer(view); mActionRecycled++; } /** * Inflate the in-track view for the action of the given MIME-type, collapsing duplicate values. * Will use the icon provided by the {@link DataKind}. */ private View inflateAction(String mimeType) { final CheckableImageView view = (CheckableImageView)obtainView(); boolean isActionSet = false; // Add direct intent if single child, otherwise flag for multiple ActionList children = mActions.get(mimeType); if (children.size() > 1) { Collapser.collapseList(children); } Action firstInfo = children.get(0); if (children.size() == 1) { view.setTag(firstInfo); } else { for (Action action : children) { if (action.isPrimary()) { view.setTag(action); isActionSet = true; break; } } if (!isActionSet) { view.setTag(children); } } // Set icon and listen for clicks final CharSequence descrip = mResolveCache.getDescription(firstInfo); final Drawable icon = mResolveCache.getIcon(firstInfo); view.setChecked(false); view.setContentDescription(descrip); view.setImageDrawable(icon); view.setOnClickListener(this); return view; } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Pass list item clicks along so that Intents are handled uniformly onClick(view); } /** * Flag indicating if {@link #mArrowDown} was visible during the last call * to {@link #setResolveVisible(boolean, CheckableImageView)}. Used to * decide during a later call if the arrow should be restored. */ private boolean mWasDownArrow = false; /** * Helper for showing and hiding {@link #mFooterDisambig}, which will * correctly manage {@link #mArrowDown} as needed. */ private void setResolveVisible(boolean visible, CheckableImageView actionView) { // Show or hide the resolve list if needed boolean visibleNow = mFooterDisambig.getVisibility() == View.VISIBLE; if (mLastAction != null) mLastAction.setChecked(false); if (actionView != null) actionView.setChecked(true); mLastAction = actionView; // Bail early if already in desired state if (visible == visibleNow) return; mFooter.setVisibility(visible ? View.GONE : View.VISIBLE); mFooterDisambig.setVisibility(visible ? View.VISIBLE : View.GONE); if (visible) { // If showing list, then hide and save state of down arrow mWasDownArrow = mWasDownArrow || (mArrowDown.getVisibility() == View.VISIBLE); mArrowDown.setVisibility(View.INVISIBLE); } else { // If hiding list, restore any down arrow state mArrowDown.setVisibility(mWasDownArrow ? View.VISIBLE : View.INVISIBLE); } } /** {@inheritDoc} */ public void onClick(View view) { final boolean isActionView = (view instanceof CheckableImageView); final CheckableImageView actionView = isActionView ? (CheckableImageView)view : null; final Object tag = view.getTag(); if (tag instanceof Action) { // Incoming tag is concrete intent, so try launching final Action action = (Action)tag; final boolean makePrimary = mMakePrimary; try { mContext.startActivity(action.getIntent()); } catch (ActivityNotFoundException e) { Toast.makeText(mContext, R.string.quickcontact_missing_app, Toast.LENGTH_SHORT) .show(); } // Hide the resolution list, if present setResolveVisible(false, null); this.dismiss(); if (makePrimary) { ContentValues values = new ContentValues(1); values.put(Data.IS_SUPER_PRIMARY, 1); final Uri dataUri = action.getDataUri(); if (dataUri != null) { mContext.getContentResolver().update(dataUri, values, null, null); } } } else if (tag instanceof ActionList) { // Incoming tag is a MIME-type, so show resolution list final ActionList children = (ActionList)tag; // Show resolution list and set adapter setResolveVisible(true, actionView); mResolveList.setOnItemClickListener(this); mResolveList.setAdapter(new BaseAdapter() { public int getCount() { return children.size(); } public Object getItem(int position) { return children.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate( R.layout.quickcontact_resolve_item, parent, false); } // Set action title based on summary value final Action action = (Action)getItem(position); TextView text1 = (TextView)convertView.findViewById(android.R.id.text1); TextView text2 = (TextView)convertView.findViewById(android.R.id.text2); text1.setText(action.getHeader()); text2.setText(action.getBody()); convertView.setTag(action); return convertView; } }); // Make sure we resize to make room for ListView mDecor.forceLayout(); mDecor.invalidate(); } } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mMakePrimary = isChecked; } private void onBackPressed() { // Back key will first dismiss any expanded resolve list, otherwise // it will close the entire dialog. if (mFooterDisambig.getVisibility() == View.VISIBLE) { setResolveVisible(false, null); mDecor.forceLayout(); mDecor.invalidate(); } else { dismiss(); } } /** {@inheritDoc} */ public boolean dispatchKeyEvent(KeyEvent event) { if (mWindow.superDispatchKeyEvent(event)) { return true; } return event.dispatch(this, mDecor != null ? mDecor.getKeyDispatcherState() : null, this); } /** {@inheritDoc} */ public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { event.startTracking(); return true; } return false; } /** {@inheritDoc} */ public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) { onBackPressed(); return true; } return false; } /** {@inheritDoc} */ public boolean onKeyLongPress(int keyCode, KeyEvent event) { return false; } /** {@inheritDoc} */ public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) { return false; } /** {@inheritDoc} */ public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { // TODO: make this window accessible return false; } /** * Detect if the given {@link MotionEvent} is outside the boundaries of this * window, which usually means we should dismiss. */ protected void detectEventOutside(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN && mDecor != null) { // Only try detecting outside events on down-press mDecor.getHitRect(mRect); mRect.top = mRect.top + mShadowTouch; mRect.bottom = mRect.bottom - mShadowTouch; final int x = (int)event.getX(); final int y = (int)event.getY(); if (!mRect.contains(x, y)) { event.setAction(MotionEvent.ACTION_OUTSIDE); } } } /** {@inheritDoc} */ public boolean dispatchTouchEvent(MotionEvent event) { detectEventOutside(event); if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { dismiss(); return true; } else { return mWindow.superDispatchTouchEvent(event); } } /** {@inheritDoc} */ public boolean dispatchTrackballEvent(MotionEvent event) { return mWindow.superDispatchTrackballEvent(event); } /** {@inheritDoc} */ public void onContentChanged() { } /** {@inheritDoc} */ public boolean onCreatePanelMenu(int featureId, Menu menu) { return false; } /** {@inheritDoc} */ public View onCreatePanelView(int featureId) { return null; } /** {@inheritDoc} */ public boolean onMenuItemSelected(int featureId, MenuItem item) { return false; } /** {@inheritDoc} */ public boolean onMenuOpened(int featureId, Menu menu) { return false; } /** {@inheritDoc} */ public void onPanelClosed(int featureId, Menu menu) { } /** {@inheritDoc} */ public boolean onPreparePanel(int featureId, View view, Menu menu) { return false; } /** {@inheritDoc} */ public boolean onSearchRequested() { return false; } /** {@inheritDoc} */ public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams attrs) { if (mDecor != null) { mWindowManager.updateViewLayout(mDecor, attrs); } } /** {@inheritDoc} */ public void onWindowFocusChanged(boolean hasFocus) { } /** {@inheritDoc} */ public void onAttachedToWindow() { // No actions } /** {@inheritDoc} */ public void onDetachedFromWindow() { // No actions } /** {@inheritDoc} */ public ActionMode onStartActionMode(ActionMode.Callback callback) { return null; } private interface DataQuery { final String[] PROJECTION = new String[] { Data._ID, RawContacts.ACCOUNT_TYPE, Contacts.STARRED, Contacts.DISPLAY_NAME, Contacts.CONTACT_PRESENCE, Data.STATUS, Data.STATUS_RES_PACKAGE, Data.STATUS_ICON, Data.STATUS_LABEL, Data.STATUS_TIMESTAMP, Data.PRESENCE, Data.RES_PACKAGE, Data.MIMETYPE, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.RAW_CONTACT_ID, Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10, Data.DATA11, Data.DATA12, Data.DATA13, Data.DATA14, Data.DATA15, }; final int _ID = 0; final int ACCOUNT_TYPE = 1; final int STARRED = 2; final int DISPLAY_NAME = 3; final int CONTACT_PRESENCE = 4; final int STATUS = 5; final int STATUS_RES_PACKAGE = 6; final int STATUS_ICON = 7; final int STATUS_LABEL = 8; final int STATUS_TIMESTAMP = 9; final int PRESENCE = 10; final int RES_PACKAGE = 11; final int MIMETYPE = 12; final int IS_PRIMARY = 13; final int IS_SUPER_PRIMARY = 14; } }
true
true
private void handleData(Cursor cursor) { if (cursor == null) return; if (!isMimeExcluded(Contacts.CONTENT_ITEM_TYPE)) { // Add the profile shortcut action final Action action = new ProfileAction(mContext, mLookupUri); mActions.collect(Contacts.CONTENT_ITEM_TYPE, action); } final DataStatus status = new DataStatus(); final AccountTypes sources = AccountTypes.getInstance(mContext); final ImageView photoView = (ImageView)mHeader.findViewById(R.id.photo); Bitmap photoBitmap = null; while (cursor.moveToNext()) { final long dataId = cursor.getLong(DataQuery._ID); final String accountType = cursor.getString(DataQuery.ACCOUNT_TYPE); final String mimeType = cursor.getString(DataQuery.MIMETYPE); // Handle any social status updates from this row status.possibleUpdate(cursor); // Skip this data item if MIME-type excluded if (isMimeExcluded(mimeType)) continue; // Handle photos included as data row if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) { final int colPhoto = cursor.getColumnIndex(Photo.PHOTO); final byte[] photoBlob = cursor.getBlob(colPhoto); if (photoBlob != null) { photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length); } continue; } final DataKind kind = sources.getKindOrFallback(accountType, mimeType, mContext, BaseAccountType.LEVEL_MIMETYPES); if (kind != null) { // Build an action for this data entry, find a mapping to a UI // element, build its summary from the cursor, and collect it // along with all others of this MIME-type. final Action action = new DataAction(mContext, mimeType, kind, dataId, cursor); considerAdd(action, mimeType); } // If phone number, also insert as text message action if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && kind != null) { final Action action = new DataAction(mContext, Constants.MIME_SMS_ADDRESS, kind, dataId, cursor); considerAdd(action, Constants.MIME_SMS_ADDRESS); } // Handle Email rows with presence data as Im entry final boolean hasPresence = !cursor.isNull(DataQuery.PRESENCE); if (hasPresence && Email.CONTENT_ITEM_TYPE.equals(mimeType)) { final DataKind imKind = sources.getKindOrFallback(accountType, Im.CONTENT_ITEM_TYPE, mContext, BaseAccountType.LEVEL_MIMETYPES); if (imKind != null) { final Action action = new DataAction(mContext, Im.CONTENT_ITEM_TYPE, imKind, dataId, cursor); considerAdd(action, Im.CONTENT_ITEM_TYPE); } } } if (cursor.moveToLast()) { // Read contact information from last data row final String name = cursor.getString(DataQuery.DISPLAY_NAME); final int presence = cursor.getInt(DataQuery.CONTACT_PRESENCE); final Drawable statusIcon = ContactPresenceIconUtil.getPresenceIcon(mContext, presence); setHeaderText(R.id.name, name); setHeaderImage(R.id.presence, statusIcon); } if (photoView != null) { // Place photo when discovered in data, otherwise hide photoView.setVisibility(photoBitmap != null ? View.VISIBLE : View.GONE); photoView.setImageBitmap(photoBitmap); } mHasValidSocial = status.isValid(); if (mHasValidSocial && mMode != QuickContact.MODE_SMALL) { // Update status when valid was found setHeaderText(R.id.status, status.getStatus()); setHeaderText(R.id.timestamp, status.getTimestampLabel(mContext)); } // Turn our list of actions into UI elements // Index where we start adding child views. int index = mTrack.getChildCount() - 1; // All the mime-types to add. final Set<String> containedTypes = new HashSet<String>(mActions.keySet()); boolean hasData = false; // First, add PRECEDING_MIMETYPES, which are most common. for (String mimeType : PRECEDING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Keep the current index to append non PRECEDING/FOLLOWING items. final int indexAfterPreceding = index; // Then, add FOLLOWING_MIMETYPES, which are least common. for (String mimeType : FOLLOWING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Go back to just after PRECEDING_MIMETYPES, and append the rest. index = indexAfterPreceding; final String[] remainingTypes = containedTypes.toArray(new String[containedTypes.size()]); if (remainingTypes.length > 0) hasData = true; Arrays.sort(remainingTypes); for (String mimeType : remainingTypes) { mTrack.addView(inflateAction(mimeType), index++); } // When there is no data to display, add a TextView to show the user there's no data if (!hasData) { View view = mInflater.inflate(R.layout.quickcontact_item_nodata, mTrack, false); mTrack.addView(view, index++); } }
private void handleData(Cursor cursor) { if (cursor == null) return; if (cursor.getCount() == 0) { Toast.makeText(mContext, R.string.invalidContactMessage, Toast.LENGTH_LONG).show(); dismiss(); return; } if (!isMimeExcluded(Contacts.CONTENT_ITEM_TYPE)) { // Add the profile shortcut action final Action action = new ProfileAction(mContext, mLookupUri); mActions.collect(Contacts.CONTENT_ITEM_TYPE, action); } final DataStatus status = new DataStatus(); final AccountTypes sources = AccountTypes.getInstance(mContext); final ImageView photoView = (ImageView)mHeader.findViewById(R.id.photo); Bitmap photoBitmap = null; while (cursor.moveToNext()) { final long dataId = cursor.getLong(DataQuery._ID); final String accountType = cursor.getString(DataQuery.ACCOUNT_TYPE); final String mimeType = cursor.getString(DataQuery.MIMETYPE); // Handle any social status updates from this row status.possibleUpdate(cursor); // Skip this data item if MIME-type excluded if (isMimeExcluded(mimeType)) continue; // Handle photos included as data row if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) { final int colPhoto = cursor.getColumnIndex(Photo.PHOTO); final byte[] photoBlob = cursor.getBlob(colPhoto); if (photoBlob != null) { photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length); } continue; } final DataKind kind = sources.getKindOrFallback(accountType, mimeType, mContext, BaseAccountType.LEVEL_MIMETYPES); if (kind != null) { // Build an action for this data entry, find a mapping to a UI // element, build its summary from the cursor, and collect it // along with all others of this MIME-type. final Action action = new DataAction(mContext, mimeType, kind, dataId, cursor); considerAdd(action, mimeType); } // If phone number, also insert as text message action if (Phone.CONTENT_ITEM_TYPE.equals(mimeType) && kind != null) { final Action action = new DataAction(mContext, Constants.MIME_SMS_ADDRESS, kind, dataId, cursor); considerAdd(action, Constants.MIME_SMS_ADDRESS); } // Handle Email rows with presence data as Im entry final boolean hasPresence = !cursor.isNull(DataQuery.PRESENCE); if (hasPresence && Email.CONTENT_ITEM_TYPE.equals(mimeType)) { final DataKind imKind = sources.getKindOrFallback(accountType, Im.CONTENT_ITEM_TYPE, mContext, BaseAccountType.LEVEL_MIMETYPES); if (imKind != null) { final Action action = new DataAction(mContext, Im.CONTENT_ITEM_TYPE, imKind, dataId, cursor); considerAdd(action, Im.CONTENT_ITEM_TYPE); } } } if (cursor.moveToLast()) { // Read contact information from last data row final String name = cursor.getString(DataQuery.DISPLAY_NAME); final int presence = cursor.getInt(DataQuery.CONTACT_PRESENCE); final Drawable statusIcon = ContactPresenceIconUtil.getPresenceIcon(mContext, presence); setHeaderText(R.id.name, name); setHeaderImage(R.id.presence, statusIcon); } if (photoView != null) { // Place photo when discovered in data, otherwise hide photoView.setVisibility(photoBitmap != null ? View.VISIBLE : View.GONE); photoView.setImageBitmap(photoBitmap); } mHasValidSocial = status.isValid(); if (mHasValidSocial && mMode != QuickContact.MODE_SMALL) { // Update status when valid was found setHeaderText(R.id.status, status.getStatus()); setHeaderText(R.id.timestamp, status.getTimestampLabel(mContext)); } // Turn our list of actions into UI elements // Index where we start adding child views. int index = mTrack.getChildCount() - 1; // All the mime-types to add. final Set<String> containedTypes = new HashSet<String>(mActions.keySet()); boolean hasData = false; // First, add PRECEDING_MIMETYPES, which are most common. for (String mimeType : PRECEDING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Keep the current index to append non PRECEDING/FOLLOWING items. final int indexAfterPreceding = index; // Then, add FOLLOWING_MIMETYPES, which are least common. for (String mimeType : FOLLOWING_MIMETYPES) { if (containedTypes.contains(mimeType)) { hasData = true; mTrack.addView(inflateAction(mimeType), index++); containedTypes.remove(mimeType); } } // Go back to just after PRECEDING_MIMETYPES, and append the rest. index = indexAfterPreceding; final String[] remainingTypes = containedTypes.toArray(new String[containedTypes.size()]); if (remainingTypes.length > 0) hasData = true; Arrays.sort(remainingTypes); for (String mimeType : remainingTypes) { mTrack.addView(inflateAction(mimeType), index++); } // When there is no data to display, add a TextView to show the user there's no data if (!hasData) { View view = mInflater.inflate(R.layout.quickcontact_item_nodata, mTrack, false); mTrack.addView(view, index++); } }
diff --git a/tests/jscribble/notebook/NoteSheetTest.java b/tests/jscribble/notebook/NoteSheetTest.java index 6499b48..04d8918 100644 --- a/tests/jscribble/notebook/NoteSheetTest.java +++ b/tests/jscribble/notebook/NoteSheetTest.java @@ -1,73 +1,73 @@ // Copyright (c) 2011 Martin Ueding <[email protected]> package tests.jscribble.notebook; import java.awt.Dimension; import java.io.File; import java.io.IOException; import jscribble.notebook.NoteSheet; import junit.framework.TestCase; public class NoteSheetTest extends TestCase { /** * Generates a temporary NoteSheet for testing. */ private NoteSheet getTempNoteSheet() { return new NoteSheet(new Dimension(1024, 600), 0, null); } public NoteSheetTest() { super(); } /** * Tests whether drawing a line causes a change in color in the image. */ public void testDrawing() { NoteSheet n = getTempNoteSheet(); assertNotNull(n); assertNotNull(n.getImg()); int previousColor = n.getImg().getRGB(100, 100); n.drawLine(100, 100, 100, 200); int rgbarray[] = n.getImg().getRGB(100, 100, 1, 1, null, 0, 1); assertTrue(rgbarray.length > 0); assertFalse(rgbarray[0] == previousColor); } /** * Tests whether a new NoteSheet is untouched and does not need any saving. */ public void testTouched() { NoteSheet n = getTempNoteSheet(); assertFalse(n.touched()); assertFalse(n.unsaved()); n.drawLine(0, 0, 0, 0); assertTrue(n.touched()); assertTrue(n.unsaved()); } /** * Creates a single NoteSheet with an existing temporary file and tests whether it is untouched and does not need any saving. */ public void testTouchedWithEmptyTempfile() { try { - File tempfile = File.createTempFile("", ".png"); + File tempfile = File.createTempFile("JUnit-", ".png"); tempfile.createNewFile(); NoteSheet n = new NoteSheet(new Dimension(100, 100), 0, tempfile); assertFalse(n.unsaved()); assertFalse(n.touched()); n.drawLine(0, 0, 0, 0); assertTrue(n.touched()); assertTrue(n.unsaved()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
public void testTouchedWithEmptyTempfile() { try { File tempfile = File.createTempFile("", ".png"); tempfile.createNewFile(); NoteSheet n = new NoteSheet(new Dimension(100, 100), 0, tempfile); assertFalse(n.unsaved()); assertFalse(n.touched()); n.drawLine(0, 0, 0, 0); assertTrue(n.touched()); assertTrue(n.unsaved()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void testTouchedWithEmptyTempfile() { try { File tempfile = File.createTempFile("JUnit-", ".png"); tempfile.createNewFile(); NoteSheet n = new NoteSheet(new Dimension(100, 100), 0, tempfile); assertFalse(n.unsaved()); assertFalse(n.touched()); n.drawLine(0, 0, 0, 0); assertTrue(n.touched()); assertTrue(n.unsaved()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/hibernate-core/src/test/java/org/hibernate/test/collectionalias/CollectionAliasTest.java b/hibernate-core/src/test/java/org/hibernate/test/collectionalias/CollectionAliasTest.java index 90104b4d98..ac1c1e9c58 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/collectionalias/CollectionAliasTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/collectionalias/CollectionAliasTest.java @@ -1,77 +1,78 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, 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.collectionalias; import org.junit.Test; import org.hibernate.Session; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; /** * @author Dave Stephan * @author Gail Badner */ public class CollectionAliasTest extends BaseCoreFunctionalTestCase { @TestForIssue( jiraKey = "HHH-7545" ) @Test public void test() { Session s = openSession(); s.getTransaction().begin(); ATable aTable = new ATable( 1 ); TableB tableB = new TableB( new TableBId( 1, "a", "b" ) ); aTable.getTablebs().add( tableB ); tableB.setTablea( aTable ); s.save( aTable ); s.getTransaction().commit(); s.close(); s = openSession(); aTable = (ATable) s.createQuery( "select distinct tablea from ATable tablea LEFT JOIN FETCH tablea.tablebs " ).uniqueResult(); assertEquals( new Integer( 1 ), aTable.getFirstId() ); assertEquals( 1, aTable.getTablebs().size() ); tableB = aTable.getTablebs().get( 0 ); assertSame( aTable, tableB.getTablea() ); assertEquals( new Integer( 1 ), tableB.getId().getFirstId() ); assertEquals( "a", tableB.getId().getSecondId() ); assertEquals( "b", tableB.getId().getThirdId() ); + s.close(); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { TableBId.class, TableB.class, TableA.class, ATable.class }; } }
true
true
public void test() { Session s = openSession(); s.getTransaction().begin(); ATable aTable = new ATable( 1 ); TableB tableB = new TableB( new TableBId( 1, "a", "b" ) ); aTable.getTablebs().add( tableB ); tableB.setTablea( aTable ); s.save( aTable ); s.getTransaction().commit(); s.close(); s = openSession(); aTable = (ATable) s.createQuery( "select distinct tablea from ATable tablea LEFT JOIN FETCH tablea.tablebs " ).uniqueResult(); assertEquals( new Integer( 1 ), aTable.getFirstId() ); assertEquals( 1, aTable.getTablebs().size() ); tableB = aTable.getTablebs().get( 0 ); assertSame( aTable, tableB.getTablea() ); assertEquals( new Integer( 1 ), tableB.getId().getFirstId() ); assertEquals( "a", tableB.getId().getSecondId() ); assertEquals( "b", tableB.getId().getThirdId() ); }
public void test() { Session s = openSession(); s.getTransaction().begin(); ATable aTable = new ATable( 1 ); TableB tableB = new TableB( new TableBId( 1, "a", "b" ) ); aTable.getTablebs().add( tableB ); tableB.setTablea( aTable ); s.save( aTable ); s.getTransaction().commit(); s.close(); s = openSession(); aTable = (ATable) s.createQuery( "select distinct tablea from ATable tablea LEFT JOIN FETCH tablea.tablebs " ).uniqueResult(); assertEquals( new Integer( 1 ), aTable.getFirstId() ); assertEquals( 1, aTable.getTablebs().size() ); tableB = aTable.getTablebs().get( 0 ); assertSame( aTable, tableB.getTablea() ); assertEquals( new Integer( 1 ), tableB.getId().getFirstId() ); assertEquals( "a", tableB.getId().getSecondId() ); assertEquals( "b", tableB.getId().getThirdId() ); s.close(); }
diff --git a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java index 52329b8c4..b60000996 100644 --- a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java @@ -1,1147 +1,1137 @@ package com.todoroo.astrid.adapter; import greendroid.widget.AsyncImageView; import greendroid.widget.QuickAction; import greendroid.widget.QuickActionBar; import greendroid.widget.QuickActionWidget; import greendroid.widget.QuickActionWidget.OnQuickActionClickListener; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; import org.json.JSONException; import org.json.JSONObject; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.Html; import android.text.Html.ImageGetter; import android.text.Html.TagHandler; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.CheckBox; import android.widget.CursorAdapter; import android.widget.Filterable; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.timsu.astrid.R; import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.Pair; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.activity.TaskListActivity; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.TaskAction; import com.todoroo.astrid.api.TaskDecoration; import com.todoroo.astrid.api.TaskDecorationExposer; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.helper.TaskAdapterAddOnManager; import com.todoroo.astrid.notes.NotesDecorationExposer; import com.todoroo.astrid.service.StatisticsConstants; import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.timers.TimerDecorationExposer; import com.todoroo.astrid.utility.Constants; /** * Adapter for displaying a user's tasks as a list * * @author Tim Su <[email protected]> * */ public class TaskAdapter extends CursorAdapter implements Filterable { public interface OnCompletedTaskListener { public void onCompletedTask(Task item, boolean newState); } public static final String DETAIL_SEPARATOR = " | "; //$NON-NLS-1$ public static final String BROADCAST_EXTRA_TASK = "model"; //$NON-NLS-1$ // --- other constants /** Properties that need to be read from the action item */ public static final Property<?>[] PROPERTIES = new Property<?>[] { Task.ID, Task.TITLE, Task.FLAGS, Task.IMPORTANCE, Task.DUE_DATE, Task.COMPLETION_DATE, Task.MODIFICATION_DATE, Task.HIDE_UNTIL, Task.DELETION_DATE, Task.DETAILS, Task.ELAPSED_SECONDS, Task.TIMER_START, Task.RECURRENCE, Task.NOTES, Task.USER_ID, Task.USER }; public static int[] IMPORTANCE_RESOURCES = new int[] { R.drawable.importance_check_1, //task_indicator_0, R.drawable.importance_check_2, //task_indicator_1, R.drawable.importance_check_3, //task_indicator_2, R.drawable.importance_check_4, //task_indicator_3, }; public static int[] IMPORTANCE_REPEAT_RESOURCES = new int[] { R.drawable.importance_check_repeat_1, //task_indicator_0, R.drawable.importance_check_repeat_2, //task_indicator_1, R.drawable.importance_check_repeat_3, //task_indicator_2, R.drawable.importance_check_repeat_4, //task_indicator_3, }; // --- instance variables @Autowired private ExceptionService exceptionService; @Autowired private TaskService taskService; protected final TaskListActivity fragment; protected final HashMap<Long, Boolean> completedItems = new HashMap<Long, Boolean>(0); protected OnCompletedTaskListener onCompletedTaskListener = null; public boolean isFling = false; private final int resource; private final LayoutInflater inflater; private DetailLoaderThread detailLoader; private int fontSize; protected boolean applyListenersToRowBody = false; private long mostRecentlyMade = -1; private final ScaleAnimation scaleAnimation; private final AtomicReference<String> query; // quick action bar private QuickActionWidget mBar; private final QuickActionListener mBarListener = new QuickActionListener(); // measure utilities protected final Paint paint; protected final DisplayMetrics displayMetrics; // --- task detail and decoration soft caches public final DecorationManager decorationManager; public final TaskActionManager taskActionManager; /** * Constructor * * @param fragment * @param resource * layout resource to inflate * @param c * database cursor * @param autoRequery * whether cursor is automatically re-queried on changes * @param onCompletedTaskListener * task listener. can be null */ public TaskAdapter(TaskListActivity fragment, int resource, Cursor c, AtomicReference<String> query, boolean autoRequery, OnCompletedTaskListener onCompletedTaskListener) { super(ContextManager.getContext(), c, autoRequery); DependencyInjectionService.getInstance().inject(this); inflater = (LayoutInflater) fragment.getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE); this.query = query; this.resource = resource; this.fragment = fragment; this.onCompletedTaskListener = onCompletedTaskListener; fontSize = Preferences.getIntegerFromString(R.string.p_fontSize, 20); paint = new Paint(); displayMetrics = new DisplayMetrics(); fragment.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); if (Preferences.getBoolean(R.string.p_default_showdetails_key, false)) { detailLoader = new DetailLoaderThread(); detailLoader.start(); } decorationManager = new DecorationManager(); taskActionManager = new TaskActionManager(); scaleAnimation = new ScaleAnimation(1.4f, 1.0f, 1.4f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(100); } /* ====================================================================== * =========================================================== filterable * ====================================================================== */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); } // perform query TodorooCursor<Task> newCursor = taskService.fetchFiltered( query.get(), constraint, TaskAdapter.PROPERTIES); fragment.getActivity().startManagingCursor(newCursor); return newCursor; } /* ====================================================================== * =========================================================== view setup * ====================================================================== */ /** Creates a new view for use in the list view */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { ViewGroup view = (ViewGroup)inflater.inflate(resource, parent, false); // create view holder ViewHolder viewHolder = new ViewHolder(); viewHolder.task = new Task(); viewHolder.view = view; viewHolder.rowBody = (ViewGroup)view.findViewById(R.id.rowBody); viewHolder.nameView = (TextView)view.findViewById(R.id.title); viewHolder.picture = (AsyncImageView)view.findViewById(R.id.picture); viewHolder.completeBox = (CheckBox)view.findViewById(R.id.completeBox); viewHolder.dueDate = (TextView)view.findViewById(R.id.dueDate); viewHolder.details1 = (TextView)view.findViewById(R.id.details1); viewHolder.details2 = (TextView)view.findViewById(R.id.details2); viewHolder.taskRow = (LinearLayout)view.findViewById(R.id.task_row); view.setTag(viewHolder); for(int i = 0; i < view.getChildCount(); i++) view.getChildAt(i).setTag(viewHolder); if(viewHolder.details1 != null) viewHolder.details1.setTag(viewHolder); // add UI component listeners addListeners(view); return view; } /** Populates a view with content */ @Override public void bindView(View view, Context context, Cursor c) { TodorooCursor<Task> cursor = (TodorooCursor<Task>)c; ViewHolder viewHolder = ((ViewHolder)view.getTag()); Task task = viewHolder.task; task.clear(); task.readFromCursor(cursor); setFieldContentsAndVisibility(view); setTaskAppearance(viewHolder, task); } /** Helper method to set the visibility based on if there's stuff inside */ private static void setVisibility(TextView v) { if(v.getText().length() > 0) v.setVisibility(View.VISIBLE); else v.setVisibility(View.GONE); } /** * View Holder saves a lot of findViewById lookups. * * @author Tim Su <[email protected]> * */ public static class ViewHolder { public Task task; public ViewGroup view; public ViewGroup rowBody; public TextView nameView; public CheckBox completeBox; public AsyncImageView picture; public TextView dueDate; public TextView details1, details2; public LinearLayout taskRow; public View[] decorations; } /** Helper method to set the contents and visibility of each field */ public synchronized void setFieldContentsAndVisibility(View view) { Resources r = fragment.getResources(); ViewHolder viewHolder = (ViewHolder)view.getTag(); Task task = viewHolder.task; // name final TextView nameView = viewHolder.nameView; { String nameValue = task.getValue(Task.TITLE); long hiddenUntil = task.getValue(Task.HIDE_UNTIL); if(task.getValue(Task.DELETION_DATE) > 0) nameValue = r.getString(R.string.TAd_deletedFormat, nameValue); if(hiddenUntil > DateUtilities.now()) nameValue = r.getString(R.string.TAd_hiddenFormat, nameValue); nameView.setText(nameValue); } // due date / completion date float dueDateTextWidth = 0; final TextView dueDateView = viewHolder.dueDate; { if(!task.isCompleted() && task.hasDueDate()) { long dueDate = task.getValue(Task.DUE_DATE); if(dueDate > DateUtilities.now()) dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate); else dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Overdue); String dateValue = formatDate(dueDate); dueDateView.setText(dateValue); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else if(task.isCompleted()) { String dateValue = formatDate(task.getValue(Task.COMPLETION_DATE)); dueDateView.setText(r.getString(R.string.TAd_completed, dateValue)); dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Completed); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else { dueDateView.setVisibility(View.GONE); } } // complete box final CheckBox completeBox = viewHolder.completeBox; { // show item as completed if it was recently checked if(completedItems.get(task.getId()) != null) { task.setValue(Task.COMPLETION_DATE, completedItems.get(task.getId()) ? DateUtilities.now() : 0); } completeBox.setChecked(task.isCompleted()); // disable checkbox if task is readonly completeBox.setEnabled(!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)); } // image view final AsyncImageView pictureView = viewHolder.picture; { if(task.getValue(Task.USER_ID) == 0) { pictureView.setVisibility(View.GONE); } else { pictureView.setVisibility(View.VISIBLE); pictureView.setUrl(null); try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { Log.w("astrid", "task-adapter-image", e); //$NON-NLS-1$ //$NON-NLS-2$ } } } // importance bar final CheckBox checkBoxView = viewHolder.completeBox; { int value = task.getValue(Task.IMPORTANCE); - if(value < IMPORTANCE_RESOURCES.length) - { - if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) - { - checkBoxView.setButtonDrawable(IMPORTANCE_REPEAT_RESOURCES[value]); - pictureView.setBackgroundResource(IMPORTANCE_REPEAT_RESOURCES[value]); - } - else - { - checkBoxView.setButtonDrawable(IMPORTANCE_RESOURCES[value]); - pictureView.setBackgroundResource(IMPORTANCE_RESOURCES[value]); - } - } - else - { - checkBoxView.setBackgroundResource(R.drawable.btn_check); + if (value >= IMPORTANCE_RESOURCES.length) + value = IMPORTANCE_RESOURCES.length - 1; + if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { + checkBoxView.setButtonDrawable(IMPORTANCE_REPEAT_RESOURCES[value]); + pictureView.setBackgroundResource(IMPORTANCE_REPEAT_RESOURCES[value]); + } else { + checkBoxView.setButtonDrawable(IMPORTANCE_RESOURCES[value]); + pictureView.setBackgroundResource(IMPORTANCE_RESOURCES[value]); } - if (pictureView.getVisibility() == View.VISIBLE){ + if (pictureView.getVisibility() == View.VISIBLE) { checkBoxView.setVisibility(View.INVISIBLE); - } - else - { + } else { checkBoxView.setVisibility(View.VISIBLE); } } String details; if(viewHolder.details1 != null) { if(taskDetailLoader.containsKey(task.getId())) details = taskDetailLoader.get(task.getId()).toString(); else details = task.getValue(Task.DETAILS); if(TextUtils.isEmpty(details) || DETAIL_SEPARATOR.equals(details) || task.isCompleted()) { viewHolder.details1.setVisibility(View.GONE); viewHolder.details2.setVisibility(View.GONE); } else if (Preferences.getBoolean(R.string.p_default_showdetails_key, false)) { viewHolder.details1.setVisibility(View.VISIBLE); if (details.startsWith(DETAIL_SEPARATOR)) { StringBuffer buffer = new StringBuffer(details); int length = DETAIL_SEPARATOR.length(); while(buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0) buffer.delete(0, length); details = buffer.toString(); //details.substring(DETAIL_SEPARATOR.length()); } drawDetails(viewHolder, details, dueDateTextWidth); } } if(Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L) mostRecentlyMade = task.getId(); // // details and decorations, expanded if (Preferences.getBoolean(R.string.p_default_showdecorations_key, false)) { decorationManager.request(viewHolder); } } @SuppressWarnings("nls") private void drawDetails(ViewHolder viewHolder, String details, float rightWidth) { SpannableStringBuilder prospective = new SpannableStringBuilder(); SpannableStringBuilder actual = new SpannableStringBuilder(); details = details.trim().replace("\n", "<br>"); String[] splitDetails = details.split("\\|"); viewHolder.completeBox.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); rightWidth = rightWidth + viewHolder.dueDate.getPaddingRight(); float left = viewHolder.completeBox.getMeasuredWidth() + ((MarginLayoutParams)viewHolder.completeBox.getLayoutParams()).leftMargin; int availableWidth = (int) (displayMetrics.widthPixels - left - (rightWidth + 16) * displayMetrics.density); int i = 0; for(; i < splitDetails.length; i++) { Spanned spanned = convertToHtml(splitDetails[i] + " ", detailImageGetter, null); prospective.insert(prospective.length(), spanned); viewHolder.details1.setText(prospective); viewHolder.details1.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); if(rightWidth > 0 && viewHolder.details1.getMeasuredWidth() > availableWidth) break; actual.insert(actual.length(), spanned); } viewHolder.details1.setText(actual); actual.clear(); if(i >= splitDetails.length) { viewHolder.details2.setVisibility(View.GONE); return; } else { viewHolder.details2.setVisibility(View.VISIBLE); } for(; i < splitDetails.length; i++) actual.insert(actual.length(), convertToHtml(splitDetails[i] + " ", detailImageGetter, null)); viewHolder.details2.setText(actual); } protected TaskRowListener listener = new TaskRowListener(); private Pair<Float, Float> lastTouchYRawY = new Pair<Float, Float>(0f, 0f); /** * Set listeners for this view. This is called once per view when it is * created. */ protected void addListeners(final View container) { final ViewHolder viewHolder = (ViewHolder)container.getTag(); // check box listener OnTouchListener otl = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { lastTouchYRawY = new Pair<Float, Float>(event.getY(), event.getRawY()); return false; } }; viewHolder.completeBox.setOnTouchListener(otl); viewHolder.completeBox.setOnClickListener(completeBoxListener); if(applyListenersToRowBody) { viewHolder.rowBody.setOnCreateContextMenuListener(listener); viewHolder.rowBody.setOnClickListener(listener); } else { container.setOnCreateContextMenuListener(listener); container.setOnClickListener(listener); } } /* ====================================================================== * ============================================================== details * ====================================================================== */ private final HashMap<String, Spanned> htmlCache = new HashMap<String, Spanned>(8); private Spanned convertToHtml(String string, ImageGetter imageGetter, TagHandler tagHandler) { if(!htmlCache.containsKey(string)) { Spanned html; try { html = Html.fromHtml(string, imageGetter, tagHandler); } catch (RuntimeException e) { html = Spannable.Factory.getInstance().newSpannable(string); } htmlCache.put(string, html); return html; } return htmlCache.get(string); } private final HashMap<Long, String> dateCache = new HashMap<Long, String>(8); private String formatDate(long date) { if(dateCache.containsKey(date)) return dateCache.get(date); String string = DateUtilities.getRelativeDay(fragment.getActivity(), date); if(Task.hasDueTime(date)) string = String.format("%s\n%s", string, //$NON-NLS-1$ DateUtilities.getTimeString(fragment.getActivity(), new Date(date))); dateCache.put(date, string); return string; } // implementation note: this map is really costly if users have // a large number of tasks to load, since it all goes into memory. // it's best to do this, though, in order to append details to each other private final Map<Long, StringBuilder> taskDetailLoader = Collections.synchronizedMap(new HashMap<Long, StringBuilder>(0)); public class DetailLoaderThread extends Thread { @Override public void run() { // for all of the tasks returned by our cursor, verify details AndroidUtilities.sleepDeep(500L); TodorooCursor<Task> fetchCursor = taskService.fetchFiltered( query.get(), null, Task.ID, Task.DETAILS, Task.DETAILS_DATE, Task.MODIFICATION_DATE, Task.COMPLETION_DATE); try { Random random = new Random(); Task task = new Task(); for(fetchCursor.moveToFirst(); !fetchCursor.isAfterLast(); fetchCursor.moveToNext()) { task.clear(); task.readFromCursor(fetchCursor); if(task.isCompleted()) continue; if(detailsAreRecentAndUpToDate(task)) { // even if we are up to date, randomly load a fraction if(random.nextFloat() < 0.1) { taskDetailLoader.put(task.getId(), new StringBuilder(task.getValue(Task.DETAILS))); requestNewDetails(task); if(Constants.DEBUG) System.err.println("Refreshing details: " + task.getId()); //$NON-NLS-1$ } continue; } else if(Constants.DEBUG) { System.err.println("Forced loading of details: " + task.getId() + //$NON-NLS-1$ "\n details: " + new Date(task.getValue(Task.DETAILS_DATE)) + //$NON-NLS-1$ "\n modified: " + new Date(task.getValue(Task.MODIFICATION_DATE))); //$NON-NLS-1$ } addTaskToLoadingArray(task); task.setValue(Task.DETAILS, DETAIL_SEPARATOR); task.setValue(Task.DETAILS_DATE, DateUtilities.now()); taskService.save(task); requestNewDetails(task); } if(taskDetailLoader.size() > 0) { fragment.getActivity().runOnUiThread(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } catch (Exception e) { // suppress silently } finally { fetchCursor.close(); } } private boolean detailsAreRecentAndUpToDate(Task task) { return task.getValue(Task.DETAILS_DATE) >= task.getValue(Task.MODIFICATION_DATE) && !TextUtils.isEmpty(task.getValue(Task.DETAILS)); } private void addTaskToLoadingArray(Task task) { StringBuilder detailStringBuilder = new StringBuilder(); taskDetailLoader.put(task.getId(), detailStringBuilder); } private void requestNewDetails(Task task) { Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_DETAILS); broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId()); fragment.getActivity().sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ); } } /** * Add detail to a task * * @param id * @param detail */ public void addDetails(long id, String detail) { final StringBuilder details = taskDetailLoader.get(id); if(details == null) return; synchronized(details) { if(details.toString().contains(detail)) return; if(details.length() > 0) details.append(DETAIL_SEPARATOR); details.append(detail); Task task = new Task(); task.setId(id); task.setValue(Task.DETAILS, details.toString()); task.setValue(Task.DETAILS_DATE, DateUtilities.now()); taskService.save(task); } fragment.getActivity().runOnUiThread(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } private final ImageGetter detailImageGetter = new ImageGetter() { private final HashMap<Integer, Drawable> cache = new HashMap<Integer, Drawable>(3); @SuppressWarnings("nls") public Drawable getDrawable(String source) { Resources r = fragment.getResources(); if(source.equals("silk_clock")) source = "details_alarm"; else if(source.equals("silk_tag_pink")) source = "details_tag"; else if(source.equals("silk_date")) source = "details_repeat"; else if(source.equals("silk_note")) source = "details_note"; int drawable = r.getIdentifier("drawable/" + source, null, Constants.PACKAGE); if(drawable == 0) return null; Drawable d; if(!cache.containsKey(drawable)) { d = r.getDrawable(drawable); d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight()); cache.put(drawable, d); } else d = cache.get(drawable); return d; } }; /* ====================================================================== * ============================================================== add-ons * ====================================================================== */ /** * Called to tell the cache to be cleared */ public void flushCaches() { completedItems.clear(); decorationManager.clearCache(); taskActionManager.clearCache(); taskDetailLoader.clear(); detailLoader = new DetailLoaderThread(); detailLoader.start(); } /** * Called to tell the cache to be cleared */ public void flushSpecific(long taskId) { completedItems.put(taskId, null); decorationManager.clearCache(taskId); taskActionManager.clearCache(taskId); taskDetailLoader.remove(taskId); } /** * AddOnManager for TaskDecorations * * @author Tim Su <[email protected]> * */ public class DecorationManager extends TaskAdapterAddOnManager<TaskDecoration> { public DecorationManager() { super(fragment); } private final TaskDecorationExposer[] exposers = new TaskDecorationExposer[] { new TimerDecorationExposer(), new NotesDecorationExposer() }; /** * Request add-ons for the given task * @return true if cache miss, false if cache hit */ @Override public boolean request(ViewHolder viewHolder) { long taskId = viewHolder.task.getId(); Collection<TaskDecoration> list = initialize(taskId); if(list != null) { draw(viewHolder, taskId, list); return false; } // request details draw(viewHolder, taskId, get(taskId)); for(TaskDecorationExposer exposer : exposers) { TaskDecoration deco = exposer.expose(viewHolder.task); if(deco != null) { addNew(viewHolder.task.getId(), exposer.getAddon(), deco, viewHolder); } } return true; } @Override protected void draw(ViewHolder viewHolder, long taskId, Collection<TaskDecoration> decorations) { if(decorations == null || viewHolder.task.getId() != taskId) return; reset(viewHolder, taskId); if(decorations.size() == 0) return; int i = 0; boolean colorSet = false; if(viewHolder.decorations == null || viewHolder.decorations.length != decorations.size()) viewHolder.decorations = new View[decorations.size()]; for(TaskDecoration decoration : decorations) { if(decoration.color != 0 && !colorSet) { colorSet = true; viewHolder.view.setBackgroundColor(decoration.color); } if(decoration.decoration != null) { View view = decoration.decoration.apply(fragment.getActivity(), viewHolder.taskRow); viewHolder.decorations[i] = view; switch(decoration.position) { case TaskDecoration.POSITION_LEFT: { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.BELOW, R.id.completeBox); view.setLayoutParams(params); viewHolder.rowBody.addView(view); break; } case TaskDecoration.POSITION_RIGHT: viewHolder.taskRow.addView(view, viewHolder.taskRow.getChildCount()); } } i++; } } @Override protected void reset(ViewHolder viewHolder, long taskId) { if(viewHolder.decorations != null) { for(View view : viewHolder.decorations) { viewHolder.rowBody.removeView(view); viewHolder.taskRow.removeView(view); } viewHolder.decorations = null; } if(viewHolder.task.getId() == mostRecentlyMade) viewHolder.view.setBackgroundColor(Color.argb(30, 150, 150, 150)); else viewHolder.view.setBackgroundResource(android.R.drawable.list_selector_background); } @Override protected Intent createBroadcastIntent(Task task) { return null; } } /** * AddOnManager for TaskActions * * @author Tim Su <[email protected]> * */ public class TaskActionManager extends TaskAdapterAddOnManager<TaskAction> { private final Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_ACTIONS); public TaskActionManager() { super(fragment); } @Override protected Intent createBroadcastIntent(Task task) { broadcastIntent.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId()); return broadcastIntent; } @Override public synchronized void addNew(long taskId, String addOn, final TaskAction item, ViewHolder thisViewHolder) { addIfNotExists(taskId, addOn, item); if(mBar != null) { ListView listView = fragment.getListView(); ViewHolder myHolder = null; // update view if it is visible int length = listView.getChildCount(); for(int i = 0; i < length; i++) { ViewHolder viewHolder = (ViewHolder) listView.getChildAt(i).getTag(); if(viewHolder == null || viewHolder.task.getId() != taskId) continue; myHolder = viewHolder; break; } if(myHolder != null) { final ViewHolder viewHolder = myHolder; fragment.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mBarListener.addWithAction(item); if (!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) mBar.show(viewHolder.view); } }); } } } @Override public Collection<TaskAction> get(long taskId) { return super.get(taskId); } @Override protected void draw(final ViewHolder viewHolder, final long taskId, Collection<TaskAction> actions) { // do not draw } @Override protected void reset(ViewHolder viewHolder, long taskId) { // do not draw } } /* ====================================================================== * ======================================================= event handlers * ====================================================================== */ @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); fontSize = Preferences.getIntegerFromString(R.string.p_fontSize, 20); } protected final View.OnClickListener completeBoxListener = new View.OnClickListener() { public void onClick(View v) { int[] location = new int[2]; v.getLocationOnScreen(location); ViewHolder viewHolder = getTagFromCheckBox(v); if(Math.abs(location[1] + lastTouchYRawY.getLeft() - lastTouchYRawY.getRight()) > 10) { viewHolder.completeBox.setChecked(!viewHolder.completeBox.isChecked()); return; } Task task = viewHolder.task; completeTask(task, viewHolder.completeBox.isChecked()); // set check box to actual action item state setTaskAppearance(viewHolder, task); viewHolder.completeBox.startAnimation(scaleAnimation); } }; protected ViewHolder getTagFromCheckBox(View v) { return (ViewHolder)((View)v.getParent()).getTag(); } private final class QuickActionListener implements OnQuickActionClickListener { private final HashMap<Integer, TaskAction> positionActionMap = new HashMap<Integer, TaskAction>(2); private long taskId; private int itemCount = 0; private int iconWidth; public void initialize(long newTaskId) { this.taskId = newTaskId; itemCount = 0; positionActionMap.clear(); mBar.setOnQuickActionClickListener(this); iconWidth = fragment.getResources().getDrawable(R.drawable.ic_qbar_edit).getIntrinsicHeight(); } public void addWithAction(TaskAction item) { Drawable drawable; if(item.drawable > 0) drawable = fragment.getResources().getDrawable(item.drawable); else { Bitmap scaledBitmap = Bitmap.createScaledBitmap(item.icon, iconWidth, iconWidth, true); drawable = new BitmapDrawable(fragment.getResources(), scaledBitmap); } addWithAction(new QuickAction(drawable, item.text), item); } public void addWithAction(QuickAction quickAction, TaskAction taskAction) { positionActionMap.put(itemCount++, taskAction); mBar.addQuickAction(quickAction); } public void onQuickActionClicked(QuickActionWidget widget, int position){ if(mBar != null) mBar.dismiss(); mBar = null; if(position == 0) { editTask(taskId); } else { flushSpecific(taskId); try { TaskAction taskAction = positionActionMap.get(position); if(taskAction != null) { taskAction.intent.send(); } } catch (Exception e) { exceptionService.displayAndReportError(fragment.getActivity(), "Error launching action", e); //$NON-NLS-1$ } } notifyDataSetChanged(); } } private class TaskRowListener implements OnCreateContextMenuListener, OnClickListener { // prepare quick action bar private void prepareQuickActionBar(ViewHolder viewHolder, Collection<TaskAction> collection){ mBar = new QuickActionBar(viewHolder.view.getContext()); QuickAction editAction = new QuickAction(fragment.getActivity(), R.drawable.ic_qbar_edit, fragment.getString(R.string.TAd_actionEditTask)); mBarListener.initialize(viewHolder.task.getId()); mBarListener.addWithAction(editAction, null); if(collection != null) { for(TaskAction item : collection) { mBarListener.addWithAction(item); } } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // this is all a big sham. it's actually handled in Task List // Activity. however, we need this to be here. } @Override public void onClick(View v) { // expand view (unless deleted) final ViewHolder viewHolder = (ViewHolder)v.getTag(); if(viewHolder.task.isDeleted()) return; long taskId = viewHolder.task.getId(); Collection<TaskAction> actions = taskActionManager.get(taskId); prepareQuickActionBar(viewHolder, actions); //mBarAnchor = v; if(actions != null && !viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) { if (actions.size() > 0) mBar.show(v); else { editTask(taskId); } } else if (!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)) { // Register a temporary receiver in case we clicked a task with no actions forthcoming and should start IntentFilter filter = new IntentFilter(AstridApiConstants.BROADCAST_REQUEST_ACTIONS); filter.setPriority(-1); fragment.getActivity().registerReceiver(new TaskActionsFinishedReceiver(), filter); } taskActionManager.request(viewHolder); notifyDataSetChanged(); } } private class TaskActionsFinishedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AndroidUtilities.sleepDeep(10L); // Allow preemption for send_actions to be delivered long taskId = intent.getLongExtra(AstridApiConstants.EXTRAS_TASK_ID, -1); if (taskId != -1) { Collection<TaskAction> actions = taskActionManager.get(taskId); if (actions != null && actions.size() == 0) { editTask(taskId); } } try { fragment.getActivity().unregisterReceiver(this); } catch (IllegalArgumentException e) { // ignore } } } private void editTask(long taskId) { fragment.onTaskListItemClicked(taskId); } /** * Call me when the parent presses trackpad */ public void onTrackpadPressed(View container) { if(container == null) return; final CheckBox completeBox = ((CheckBox)container.findViewById(R.id.completeBox)); completeBox.performClick(); } /** Helper method to adjust a tasks' appearance if the task is completed or * uncompleted. * * @param actionItem * @param name * @param progress */ void setTaskAppearance(ViewHolder viewHolder, Task task) { boolean state = task.isCompleted(); viewHolder.completeBox.setChecked(state); viewHolder.completeBox.setEnabled(!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)); TextView name = viewHolder.nameView; if(state) { name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); name.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemTitle_Completed); } else { name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); name.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemTitle); } name.setTextSize(fontSize); float detailTextSize = Math.max(10, fontSize * 12 / 20); if(viewHolder.details1 != null) viewHolder.details1.setTextSize(detailTextSize); if(viewHolder.details2 != null) viewHolder.details2.setTextSize(detailTextSize); if(viewHolder.dueDate != null) viewHolder.dueDate.setTextSize(detailTextSize); paint.setTextSize(detailTextSize); } /** * This method is called when user completes a task via check box or other * means * * @param container * container for the action item * @param newState * state that this task should be set to * @param completeBox * the box that was clicked. can be null */ protected void completeTask(final Task task, final boolean newState) { if(task == null) return; if (newState != task.isCompleted()) { completedItems.put(task.getId(), newState); taskService.setComplete(task, newState); if(onCompletedTaskListener != null) onCompletedTaskListener.onCompletedTask(task, newState); if(newState) StatisticsService.reportEvent(StatisticsConstants.TASK_COMPLETED_V2); } } /** * Add a new listener * @param newListener */ public void addOnCompletedTaskListener(final OnCompletedTaskListener newListener) { if(this.onCompletedTaskListener == null) this.onCompletedTaskListener = newListener; else { final OnCompletedTaskListener old = this.onCompletedTaskListener; this.onCompletedTaskListener = new OnCompletedTaskListener() { @Override public void onCompletedTask(Task item, boolean newState) { old.onCompletedTask(item, newState); newListener.onCompletedTask(item, newState); } }; } } }
false
true
public synchronized void setFieldContentsAndVisibility(View view) { Resources r = fragment.getResources(); ViewHolder viewHolder = (ViewHolder)view.getTag(); Task task = viewHolder.task; // name final TextView nameView = viewHolder.nameView; { String nameValue = task.getValue(Task.TITLE); long hiddenUntil = task.getValue(Task.HIDE_UNTIL); if(task.getValue(Task.DELETION_DATE) > 0) nameValue = r.getString(R.string.TAd_deletedFormat, nameValue); if(hiddenUntil > DateUtilities.now()) nameValue = r.getString(R.string.TAd_hiddenFormat, nameValue); nameView.setText(nameValue); } // due date / completion date float dueDateTextWidth = 0; final TextView dueDateView = viewHolder.dueDate; { if(!task.isCompleted() && task.hasDueDate()) { long dueDate = task.getValue(Task.DUE_DATE); if(dueDate > DateUtilities.now()) dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate); else dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Overdue); String dateValue = formatDate(dueDate); dueDateView.setText(dateValue); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else if(task.isCompleted()) { String dateValue = formatDate(task.getValue(Task.COMPLETION_DATE)); dueDateView.setText(r.getString(R.string.TAd_completed, dateValue)); dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Completed); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else { dueDateView.setVisibility(View.GONE); } } // complete box final CheckBox completeBox = viewHolder.completeBox; { // show item as completed if it was recently checked if(completedItems.get(task.getId()) != null) { task.setValue(Task.COMPLETION_DATE, completedItems.get(task.getId()) ? DateUtilities.now() : 0); } completeBox.setChecked(task.isCompleted()); // disable checkbox if task is readonly completeBox.setEnabled(!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)); } // image view final AsyncImageView pictureView = viewHolder.picture; { if(task.getValue(Task.USER_ID) == 0) { pictureView.setVisibility(View.GONE); } else { pictureView.setVisibility(View.VISIBLE); pictureView.setUrl(null); try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { Log.w("astrid", "task-adapter-image", e); //$NON-NLS-1$ //$NON-NLS-2$ } } } // importance bar final CheckBox checkBoxView = viewHolder.completeBox; { int value = task.getValue(Task.IMPORTANCE); if(value < IMPORTANCE_RESOURCES.length) { if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { checkBoxView.setButtonDrawable(IMPORTANCE_REPEAT_RESOURCES[value]); pictureView.setBackgroundResource(IMPORTANCE_REPEAT_RESOURCES[value]); } else { checkBoxView.setButtonDrawable(IMPORTANCE_RESOURCES[value]); pictureView.setBackgroundResource(IMPORTANCE_RESOURCES[value]); } } else { checkBoxView.setBackgroundResource(R.drawable.btn_check); } if (pictureView.getVisibility() == View.VISIBLE){ checkBoxView.setVisibility(View.INVISIBLE); } else { checkBoxView.setVisibility(View.VISIBLE); } } String details; if(viewHolder.details1 != null) { if(taskDetailLoader.containsKey(task.getId())) details = taskDetailLoader.get(task.getId()).toString(); else details = task.getValue(Task.DETAILS); if(TextUtils.isEmpty(details) || DETAIL_SEPARATOR.equals(details) || task.isCompleted()) { viewHolder.details1.setVisibility(View.GONE); viewHolder.details2.setVisibility(View.GONE); } else if (Preferences.getBoolean(R.string.p_default_showdetails_key, false)) { viewHolder.details1.setVisibility(View.VISIBLE); if (details.startsWith(DETAIL_SEPARATOR)) { StringBuffer buffer = new StringBuffer(details); int length = DETAIL_SEPARATOR.length(); while(buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0) buffer.delete(0, length); details = buffer.toString(); //details.substring(DETAIL_SEPARATOR.length()); } drawDetails(viewHolder, details, dueDateTextWidth); } } if(Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L) mostRecentlyMade = task.getId(); // // details and decorations, expanded if (Preferences.getBoolean(R.string.p_default_showdecorations_key, false)) { decorationManager.request(viewHolder); } }
public synchronized void setFieldContentsAndVisibility(View view) { Resources r = fragment.getResources(); ViewHolder viewHolder = (ViewHolder)view.getTag(); Task task = viewHolder.task; // name final TextView nameView = viewHolder.nameView; { String nameValue = task.getValue(Task.TITLE); long hiddenUntil = task.getValue(Task.HIDE_UNTIL); if(task.getValue(Task.DELETION_DATE) > 0) nameValue = r.getString(R.string.TAd_deletedFormat, nameValue); if(hiddenUntil > DateUtilities.now()) nameValue = r.getString(R.string.TAd_hiddenFormat, nameValue); nameView.setText(nameValue); } // due date / completion date float dueDateTextWidth = 0; final TextView dueDateView = viewHolder.dueDate; { if(!task.isCompleted() && task.hasDueDate()) { long dueDate = task.getValue(Task.DUE_DATE); if(dueDate > DateUtilities.now()) dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate); else dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Overdue); String dateValue = formatDate(dueDate); dueDateView.setText(dateValue); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else if(task.isCompleted()) { String dateValue = formatDate(task.getValue(Task.COMPLETION_DATE)); dueDateView.setText(r.getString(R.string.TAd_completed, dateValue)); dueDateView.setTextAppearance(fragment.getActivity(), R.style.TextAppearance_TAd_ItemDueDate_Completed); dueDateTextWidth = paint.measureText(dateValue); setVisibility(dueDateView); } else { dueDateView.setVisibility(View.GONE); } } // complete box final CheckBox completeBox = viewHolder.completeBox; { // show item as completed if it was recently checked if(completedItems.get(task.getId()) != null) { task.setValue(Task.COMPLETION_DATE, completedItems.get(task.getId()) ? DateUtilities.now() : 0); } completeBox.setChecked(task.isCompleted()); // disable checkbox if task is readonly completeBox.setEnabled(!viewHolder.task.getFlag(Task.FLAGS, Task.FLAG_IS_READONLY)); } // image view final AsyncImageView pictureView = viewHolder.picture; { if(task.getValue(Task.USER_ID) == 0) { pictureView.setVisibility(View.GONE); } else { pictureView.setVisibility(View.VISIBLE); pictureView.setUrl(null); try { JSONObject user = new JSONObject(task.getValue(Task.USER)); pictureView.setUrl(user.optString("picture")); //$NON-NLS-1$ } catch (JSONException e) { Log.w("astrid", "task-adapter-image", e); //$NON-NLS-1$ //$NON-NLS-2$ } } } // importance bar final CheckBox checkBoxView = viewHolder.completeBox; { int value = task.getValue(Task.IMPORTANCE); if (value >= IMPORTANCE_RESOURCES.length) value = IMPORTANCE_RESOURCES.length - 1; if (!TextUtils.isEmpty(task.getValue(Task.RECURRENCE))) { checkBoxView.setButtonDrawable(IMPORTANCE_REPEAT_RESOURCES[value]); pictureView.setBackgroundResource(IMPORTANCE_REPEAT_RESOURCES[value]); } else { checkBoxView.setButtonDrawable(IMPORTANCE_RESOURCES[value]); pictureView.setBackgroundResource(IMPORTANCE_RESOURCES[value]); } if (pictureView.getVisibility() == View.VISIBLE) { checkBoxView.setVisibility(View.INVISIBLE); } else { checkBoxView.setVisibility(View.VISIBLE); } } String details; if(viewHolder.details1 != null) { if(taskDetailLoader.containsKey(task.getId())) details = taskDetailLoader.get(task.getId()).toString(); else details = task.getValue(Task.DETAILS); if(TextUtils.isEmpty(details) || DETAIL_SEPARATOR.equals(details) || task.isCompleted()) { viewHolder.details1.setVisibility(View.GONE); viewHolder.details2.setVisibility(View.GONE); } else if (Preferences.getBoolean(R.string.p_default_showdetails_key, false)) { viewHolder.details1.setVisibility(View.VISIBLE); if (details.startsWith(DETAIL_SEPARATOR)) { StringBuffer buffer = new StringBuffer(details); int length = DETAIL_SEPARATOR.length(); while(buffer.lastIndexOf(DETAIL_SEPARATOR, length) == 0) buffer.delete(0, length); details = buffer.toString(); //details.substring(DETAIL_SEPARATOR.length()); } drawDetails(viewHolder, details, dueDateTextWidth); } } if(Math.abs(DateUtilities.now() - task.getValue(Task.MODIFICATION_DATE)) < 2000L) mostRecentlyMade = task.getId(); // // details and decorations, expanded if (Preferences.getBoolean(R.string.p_default_showdecorations_key, false)) { decorationManager.request(viewHolder); } }
diff --git a/src/main/java/org/biojava3/structure/align/symm/order/RotationOrderDetector.java b/src/main/java/org/biojava3/structure/align/symm/order/RotationOrderDetector.java index 53fdbe69..a1df9431 100644 --- a/src/main/java/org/biojava3/structure/align/symm/order/RotationOrderDetector.java +++ b/src/main/java/org/biojava3/structure/align/symm/order/RotationOrderDetector.java @@ -1,172 +1,172 @@ package org.biojava3.structure.align.symm.order; import java.io.IOException; import java.util.Arrays; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.Calc; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureException; import org.biojava.bio.structure.StructureTools; import org.biojava.bio.structure.align.model.AFPChain; import org.biojava.bio.structure.align.util.RotationAxis; import org.biojava3.structure.align.symm.CeSymm; /** * Detects order by rotating the structure by angles that correspond to orders. * This one could be smart. * TODO Needs lots of work * @author dmyersturnbull */ public class RotationOrderDetector implements OrderDetector { private int maxOrder = 8; private final double minScore; public RotationOrderDetector(double minTmScore) { super(); this.minScore = minTmScore; } public RotationOrderDetector(int maxOrder, double minTmScore) { super(); this.maxOrder = maxOrder; this.minScore = minTmScore; } @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws OrderDetectionFailedException { try { RotationAxis axis = new RotationAxis(afpChain); //AFPChain clone = (AFPChain) afpChain.clone(); Atom[] ca2 = null; double bestScore = minScore; int argmax = 1; for (int order = 1; order <= maxOrder; order++) { ca2 = StructureTools.cloneCAArray(ca); // reset rotation for new order double angle = 2*Math.PI / order; // will apply repeatedly /* * If C6, we should be able to rotate 6 times and still get a decent superposition */ double lowestScore = Double.POSITIVE_INFINITY; for (int j = 1; j < order; j++) { axis.rotate(ca2, angle); // rotate repeatedly //double score = AFPChainScorer.getTMScore(clone, ca, ca2); double score = superpositionDistance(ca, ca2); if (score < lowestScore) { lowestScore = score; } } if (lowestScore > bestScore) { bestScore = lowestScore; argmax = order; } } return argmax; } catch (Exception e) { throw new OrderDetectionFailedException(e); } } /** * Provide a rough alignment-free metric for the similarity between two * superimposed structures. * * The average distance from each atom to the closest atom in the other * is used. * @param ca1 * @param ca2 * @return * @throws StructureException */ public static double superpositionDistance(Atom[] ca1, Atom[] ca2) throws StructureException { // Store the closest distance yet found double[] bestDist1 = new double[ca1.length]; double[] bestDist2 = new double[ca2.length]; Arrays.fill(bestDist1, Double.POSITIVE_INFINITY); Arrays.fill(bestDist2, Double.POSITIVE_INFINITY); for(int i=0;i<ca1.length;i++) { for(int j=0;j<ca2.length;j++) { double dist = Calc.getDistanceFast(ca1[i], ca2[j]); if( dist < bestDist1[i]) { bestDist1[i] = dist; } if( dist < bestDist2[j]) { bestDist2[j] = dist; } } } double total = 0; for(int i=0;i<ca1.length;i++) { total += Math.sqrt(bestDist1[i]); } for(int j=0;j<ca2.length;j++) { total += Math.sqrt(bestDist2[j]); } double dist = total/(ca1.length+ca2.length); return dist; } public static void main(String[] args) { String name; name = "d1ijqa1"; // name = "1G6S"; // name = "1MER"; name = "1TIM.A"; name = "d1h70a_"; try { Atom[] ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); Structure s2 = StructureTools.getStructure(name); Atom[] ca2 = StructureTools.getAtomCAArray(s2); CeSymm ce = new CeSymm(); AFPChain alignment = ce.align(ca1, ca2); RotationAxis axis = new RotationAxis(alignment); System.out.println("Order\tRotations\tDistance"); int maxOrder = 8; for (int order = 1; order <= maxOrder; order++) { ca2 = StructureTools.cloneCAArray(ca1); // reset rotation for new order double angle = 2*Math.PI / order; // will apply repeatedly for (int j = 1; j < order; j++) { axis.rotate(ca2, angle); - double score = CeSymm.superpositionDistance(ca1, ca2); + double score = superpositionDistance(ca1, ca2); System.out.format("%d\t%d\t%f%n", order,j,score); } //new StructureAlignmentJmol(alignment, ca1, ca2); } } catch (IOException e) { e.printStackTrace(); } catch (StructureException e) { e.printStackTrace(); } } }
true
true
public static void main(String[] args) { String name; name = "d1ijqa1"; // name = "1G6S"; // name = "1MER"; name = "1TIM.A"; name = "d1h70a_"; try { Atom[] ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); Structure s2 = StructureTools.getStructure(name); Atom[] ca2 = StructureTools.getAtomCAArray(s2); CeSymm ce = new CeSymm(); AFPChain alignment = ce.align(ca1, ca2); RotationAxis axis = new RotationAxis(alignment); System.out.println("Order\tRotations\tDistance"); int maxOrder = 8; for (int order = 1; order <= maxOrder; order++) { ca2 = StructureTools.cloneCAArray(ca1); // reset rotation for new order double angle = 2*Math.PI / order; // will apply repeatedly for (int j = 1; j < order; j++) { axis.rotate(ca2, angle); double score = CeSymm.superpositionDistance(ca1, ca2); System.out.format("%d\t%d\t%f%n", order,j,score); } //new StructureAlignmentJmol(alignment, ca1, ca2); } } catch (IOException e) { e.printStackTrace(); } catch (StructureException e) { e.printStackTrace(); } }
public static void main(String[] args) { String name; name = "d1ijqa1"; // name = "1G6S"; // name = "1MER"; name = "1TIM.A"; name = "d1h70a_"; try { Atom[] ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); Structure s2 = StructureTools.getStructure(name); Atom[] ca2 = StructureTools.getAtomCAArray(s2); CeSymm ce = new CeSymm(); AFPChain alignment = ce.align(ca1, ca2); RotationAxis axis = new RotationAxis(alignment); System.out.println("Order\tRotations\tDistance"); int maxOrder = 8; for (int order = 1; order <= maxOrder; order++) { ca2 = StructureTools.cloneCAArray(ca1); // reset rotation for new order double angle = 2*Math.PI / order; // will apply repeatedly for (int j = 1; j < order; j++) { axis.rotate(ca2, angle); double score = superpositionDistance(ca1, ca2); System.out.format("%d\t%d\t%f%n", order,j,score); } //new StructureAlignmentJmol(alignment, ca1, ca2); } } catch (IOException e) { e.printStackTrace(); } catch (StructureException e) { e.printStackTrace(); } }
diff --git a/plugins/org.eclipse.recommenders.completion.rcp.calls/src/org/eclipse/recommenders/internal/completion/rcp/calls/store2/models/ModelArchiveDownloadService.java b/plugins/org.eclipse.recommenders.completion.rcp.calls/src/org/eclipse/recommenders/internal/completion/rcp/calls/store2/models/ModelArchiveDownloadService.java index f1e42389d..efabefc51 100644 --- a/plugins/org.eclipse.recommenders.completion.rcp.calls/src/org/eclipse/recommenders/internal/completion/rcp/calls/store2/models/ModelArchiveDownloadService.java +++ b/plugins/org.eclipse.recommenders.completion.rcp.calls/src/org/eclipse/recommenders/internal/completion/rcp/calls/store2/models/ModelArchiveDownloadService.java @@ -1,113 +1,111 @@ /** * Copyright (c) 2010, 2011 Darmstadt University of Technology. * 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: * Marcel Bruch - initial API and implementation. */ package org.eclipse.recommenders.internal.completion.rcp.calls.store2.models; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import javax.ws.rs.core.MediaType; import org.apache.commons.io.IOUtils; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.recommenders.commons.udc.Manifest; import org.eclipse.recommenders.internal.completion.rcp.calls.store2.Events.ModelArchiveDownloadFinished; import org.eclipse.recommenders.internal.completion.rcp.calls.store2.Events.ModelArchiveDownloadRequested; import org.eclipse.recommenders.internal.completion.rcp.calls.wiring.CallsCompletionPlugin; import org.eclipse.recommenders.rcp.RecommendersPlugin; import org.eclipse.recommenders.webclient.ClientConfiguration; import org.eclipse.recommenders.webclient.WebServiceClient; import org.eclipse.ui.internal.misc.StatusUtil; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; public class ModelArchiveDownloadService { private final ExecutorService pool = org.eclipse.recommenders.utils.Executors.coreThreadsTimoutExecutor(5, Thread.MIN_PRIORITY, "Recommenders-Model-Downloader-"); private final WebServiceClient client; private final EventBus bus; public ModelArchiveDownloadService(final ClientConfiguration webserviceConfig, final EventBus bus) { this.bus = bus; client = new WebServiceClient(webserviceConfig); client.enableGzipCompression(true); } @Subscribe public void onEvent(final ModelArchiveDownloadRequested e) { pool.execute(new Runnable() { @Override public void run() { try { final File archive = downloadModel(e.manifest); fireModelArchiveDownloaded(archive, e); } catch (final IOException e1) { RecommendersPlugin.logError(e1, "Exception occurred during model download for %s", e); } } }); } private void fireModelArchiveDownloaded(final File archive, final ModelArchiveDownloadRequested e) { final ModelArchiveDownloadFinished event = new ModelArchiveDownloadFinished(); event.archive = archive; bus.post(event); } protected File downloadModel(final Manifest manifest) throws IOException { // this is not exactly sexy but produces a nice output in Eclipse's // progress view: final File temp = File.createTempFile("download.", ".zip"); final WorkspaceJob job = new WorkspaceJob("Downloading recommendation model") { @SuppressWarnings("restriction") @Override public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException { monitor.beginTask("call completion for " + manifest.getIdentifier(), 1); try { final String url = "model/" + WebServiceClient.encode(manifest.getIdentifier()); - final InputStream is = - client.createRequestBuilder(url) - .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .get(InputStream.class); + final InputStream is = client.createRequestBuilder(url) + .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).get(InputStream.class); final FileOutputStream fos = new FileOutputStream(temp); IOUtils.copy(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); return Status.OK_STATUS; - } catch (final IOException e) { + } catch (final Exception e) { return StatusUtil.newStatus(CallsCompletionPlugin.PLUGIN_ID, e); } finally { monitor.done(); } } }; job.schedule(); try { job.join(); } catch (final InterruptedException e) { // don't report. user cancel or workspace shutdown } return temp; } }
false
true
protected File downloadModel(final Manifest manifest) throws IOException { // this is not exactly sexy but produces a nice output in Eclipse's // progress view: final File temp = File.createTempFile("download.", ".zip"); final WorkspaceJob job = new WorkspaceJob("Downloading recommendation model") { @SuppressWarnings("restriction") @Override public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException { monitor.beginTask("call completion for " + manifest.getIdentifier(), 1); try { final String url = "model/" + WebServiceClient.encode(manifest.getIdentifier()); final InputStream is = client.createRequestBuilder(url) .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE) .get(InputStream.class); final FileOutputStream fos = new FileOutputStream(temp); IOUtils.copy(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); return Status.OK_STATUS; } catch (final IOException e) { return StatusUtil.newStatus(CallsCompletionPlugin.PLUGIN_ID, e); } finally { monitor.done(); } } }; job.schedule(); try { job.join(); } catch (final InterruptedException e) { // don't report. user cancel or workspace shutdown } return temp; }
protected File downloadModel(final Manifest manifest) throws IOException { // this is not exactly sexy but produces a nice output in Eclipse's // progress view: final File temp = File.createTempFile("download.", ".zip"); final WorkspaceJob job = new WorkspaceJob("Downloading recommendation model") { @SuppressWarnings("restriction") @Override public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException { monitor.beginTask("call completion for " + manifest.getIdentifier(), 1); try { final String url = "model/" + WebServiceClient.encode(manifest.getIdentifier()); final InputStream is = client.createRequestBuilder(url) .accept(MediaType.APPLICATION_OCTET_STREAM_TYPE).get(InputStream.class); final FileOutputStream fos = new FileOutputStream(temp); IOUtils.copy(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); return Status.OK_STATUS; } catch (final Exception e) { return StatusUtil.newStatus(CallsCompletionPlugin.PLUGIN_ID, e); } finally { monitor.done(); } } }; job.schedule(); try { job.join(); } catch (final InterruptedException e) { // don't report. user cancel or workspace shutdown } return temp; }
diff --git a/src/com/ezhang/pop/ui/FuelStateMachine.java b/src/com/ezhang/pop/ui/FuelStateMachine.java index 9f93379..0396898 100644 --- a/src/com/ezhang/pop/ui/FuelStateMachine.java +++ b/src/com/ezhang/pop/ui/FuelStateMachine.java @@ -1,484 +1,484 @@ package com.ezhang.pop.ui; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Observable; import java.util.Timer; import java.util.TimerTask; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.ezhang.pop.core.StateMachine; import com.ezhang.pop.core.StateMachine.EventAction; import com.ezhang.pop.model.DestinationList; import com.ezhang.pop.model.DistanceMatrix; import com.ezhang.pop.model.DistanceMatrixItem; import com.ezhang.pop.model.FuelDistanceItem; import com.ezhang.pop.model.FuelInfo; import com.ezhang.pop.rest.PopRequestFactory; import com.ezhang.pop.rest.PopRequestManager; import com.ezhang.pop.settings.AppSettings; import com.foxykeep.datadroid.requestmanager.Request; import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener; public class FuelStateMachine extends Observable implements RequestListener { private static class TimerHandler extends Handler { FuelStateMachine m_fuelStateMachine = null; public TimerHandler(FuelStateMachine fuelStateMachine) { m_fuelStateMachine = fuelStateMachine; } @Override public void handleMessage(Message msg) { m_fuelStateMachine.m_stateMachine .HandleEvent(EmEvent.Timeout, null); } } enum EmState { Start, GeoLocationRecieved, SuburbRecieved, FuelInfoRecieved, DistanceRecieved, Timeout } enum EmEvent { Invalid, GeoLocationEvent, SuburbEvent, FuelInfoEvent, DistanceEvent, Refresh, Timeout, RecalculatePrice } StateMachine<EmState, EmEvent> m_stateMachine = new StateMachine<EmState, EmEvent>( EmState.Start); public ArrayList<FuelDistanceItem> m_fuelDistanceItems = new ArrayList<FuelDistanceItem>(); private List<FuelInfo> m_fuelInfoList = null; private PopRequestManager m_restReqManager; private LocationManager m_locationManager; public Location m_location = null; public String m_suburb = null; public String m_address = null; private String m_provider = null; public EmEvent m_timeoutEvent = EmEvent.Invalid; Timer m_timer = null; TimerTask m_timerTask = null; Handler m_timeoutHandler = new TimerHandler(this); AppSettings m_settings = null; public FuelStateMachine(PopRequestManager reqManager, LocationManager locationManager, AppSettings settings) { m_restReqManager = reqManager; m_locationManager = locationManager; m_settings = settings; InitStateMachineTransitions(); m_provider = GetBestProvider(); if (m_provider != null) { m_locationManager.requestLocationUpdates(m_provider, 60 * 1000L, 20.0f, this.m_locationListener); } this.m_location = this.m_locationManager .getLastKnownLocation(m_provider); Refresh(); } public void Refresh() { this.m_stateMachine.HandleEvent(EmEvent.Refresh, null); } private void StartTimer(int millSeconds) { StopTimer(); if (m_timer == null) { m_timer = new Timer(); } if (m_timerTask == null) { m_timerTask = new TimerTask() { public void run() { m_timeoutHandler.sendMessage(new Message()); } }; } if (m_timer != null && m_timerTask != null) { m_timer.schedule(m_timerTask, millSeconds); } } private void StopTimer() { if (m_timer != null) { m_timer.cancel(); m_timer = null; } if (m_timerTask != null) { m_timerTask.cancel(); m_timerTask = null; } } private void InitStateMachineTransitions() { m_stateMachine.AddTransition(EmState.Start, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.GeoLocationEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.Timeout, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.SuburbRecieved, EmEvent.SuburbEvent, new EventAction() { public void PerformAction(Bundle param) { m_suburb = param .getString(PopRequestFactory.BUNDLE_CUR_SUBURB_DATA); m_address = param .getString(PopRequestFactory.BUNDLE_CUR_ADDRESS_DATA); if (m_suburb == "") { m_stateMachine .SetState(EmState.GeoLocationRecieved); RequestSuburb(); return; } RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { - m_timeoutEvent = EmEvent.SuburbEvent; + m_timeoutEvent = EmEvent.GeoLocationEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.GeoLocationRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { if (m_suburb == null) { RequestSuburb(); } else { m_stateMachine.SetState(EmState.SuburbRecieved); RequestFuelInfo(); } Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.FuelInfoRecieved, EmEvent.FuelInfoEvent, new EventAction() { public void PerformAction(Bundle param) { m_fuelInfoList = param .getParcelableArrayList(PopRequestFactory.BUNDLE_FUEL_DATA); RequestDistanceMatrix(m_fuelInfoList); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.FuelInfoEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.DistanceRecieved, EmEvent.DistanceEvent, new EventAction() { public void PerformAction(Bundle param) { StopTimer(); DistanceMatrix distanceMatrix = param .getParcelable(PopRequestFactory.BUNDLE_DISTANCE_MATRIX_DATA); OnDistanceMatrixRecieved(distanceMatrix); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.DistanceEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.DistanceRecieved, EmEvent.RecalculatePrice, new EventAction() { public void PerformAction(Bundle param) { OnRecalculatePrice(); Notify(); } }); } private void OnRecalculatePrice() { for (FuelDistanceItem item : this.m_fuelDistanceItems) { if (item.voucherType != null && item.voucherType != "") { if (item.voucherType == "wws") { if (m_settings.m_wwsDiscount != item.voucher) { item.price += item.voucher - m_settings.m_wwsDiscount; item.voucher = m_settings.m_wwsDiscount; } } if (item.voucherType == "coles") { if (m_settings.m_colesDiscount != item.voucher) { item.price += item.voucher - m_settings.m_colesDiscount; item.voucher = m_settings.m_colesDiscount; } } } } } private void OnDistanceMatrixRecieved(DistanceMatrix distanceMatrix) { m_fuelDistanceItems.clear(); int i = 0; for (DistanceMatrixItem distanceItem : distanceMatrix .GetDistanceItems()) { FuelDistanceItem item = new FuelDistanceItem(); item.distance = distanceItem.distance; item.distanceValue = distanceItem.distanceValue; item.duration = distanceItem.duration; FuelInfo fuelInfo = this.m_fuelInfoList.get(i); item.tradingName = fuelInfo.tradingName; item.price = fuelInfo.price; String lowTradingName = item.tradingName .toLowerCase(Locale.ENGLISH); if (lowTradingName.contains("woolworths") && m_settings.m_wwsDiscount > 0) { item.price -= m_settings.m_wwsDiscount; item.voucher = m_settings.m_wwsDiscount; item.voucherType = "wws"; } else if (lowTradingName.contains("coles") && m_settings.m_colesDiscount > 0) { item.price -= m_settings.m_colesDiscount; item.voucher = m_settings.m_colesDiscount; item.voucherType = "coles"; } else { item.voucherType = ""; } item.latitude = fuelInfo.latitude; item.longitude = fuelInfo.longitude; item.destinationAddr = fuelInfo.address; m_fuelDistanceItems.add(item); i++; } Notify(); } @Override public void onRequestFinished(Request request, Bundle resultData) { if (request.getRequestType() == PopRequestFactory.REQ_TYPE_DISTANCE_MATRIX) { this.m_stateMachine.HandleEvent(EmEvent.DistanceEvent, resultData); } if (request.getRequestType() == PopRequestFactory.REQ_TYPE_GET_CUR_SUBURB) { this.m_stateMachine.HandleEvent(EmEvent.SuburbEvent, resultData); } if (request.getRequestType() == PopRequestFactory.REQ_TYPE_FUEL) { this.m_stateMachine.HandleEvent(EmEvent.FuelInfoEvent, resultData); } } @Override public void onRequestConnectionError(Request request, int statusCode) { } @Override public void onRequestDataError(Request request) { } @Override public void onRequestCustomError(Request request, Bundle resultData) { } private void RequestSuburb() { StartTimer(5000); Request req = PopRequestFactory.GetCurrentSuburbRequest(m_location); m_restReqManager.execute(req, this); } private void RequestFuelInfo() { StartTimer(5000); Request req = PopRequestFactory.GetFuelInfoRequest(m_suburb, m_settings.IncludeSurroundings(), m_settings.GetFuelType()); m_restReqManager.execute(req, this); } private void RequestDistanceMatrix(List<FuelInfo> fuelInfoList) { if (m_location == null) { m_location = this.m_locationManager .getLastKnownLocation(m_provider); } if (m_location != null) { DestinationList dests = new DestinationList(); for (FuelInfo item : fuelInfoList) { dests.AddDestination(item.latitude, item.longitude); } String src = String.format("%s,%s", this.m_location.getLatitude(), this.m_location.getLongitude()); StartTimer(5000); Request req = PopRequestFactory .GetDistanceMatrixRequest(src, dests); m_restReqManager.execute(req, this); } else { // TODO: Still waiting location data. } } private String GetBestProvider() { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = m_locationManager.getBestProvider(criteria, true); return provider; } private final LocationListener m_locationListener = new LocationListener() { public void onLocationChanged(Location location) { // ������ı�ʱ�����˺��������Provider������ͬ�����꣬���Ͳ��ᱻ���� // log it when the location changes if (location != null) { if (m_location == null || !location.equals(m_location)) { m_location = location; m_suburb = null; m_fuelInfoList = null; m_fuelDistanceItems.clear(); m_stateMachine.HandleEvent(EmEvent.GeoLocationEvent, null); } } } public void onProviderDisabled(String provider) { // Provider��disableʱ�����˺���������GPS���ر� } public void onProviderEnabled(String provider) { // Provider��enableʱ�����˺���������GPS���� } public void onStatusChanged(String provider, int status, Bundle extras) { // Provider��ת̬�ڿ��á���ʱ�����ú��޷�������״ֱ̬���л�ʱ�����˺��� } }; public EmState GetCurState() { // TODO Auto-generated method stub return this.m_stateMachine.GetState(); } private void Notify() { setChanged(); notifyObservers(); } private void Start() { if (m_location == null) { StartTimer(3 * 60 * 1000); Notify(); return; } if (m_suburb == null) { m_stateMachine.SetState(EmState.GeoLocationRecieved); RequestSuburb(); } else { m_stateMachine.SetState(EmState.SuburbRecieved); RequestFuelInfo(); } Notify(); } public void ReCalculatePrice() { this.m_stateMachine.HandleEvent(EmEvent.RecalculatePrice, null); } }
true
true
private void InitStateMachineTransitions() { m_stateMachine.AddTransition(EmState.Start, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.GeoLocationEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.Timeout, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.SuburbRecieved, EmEvent.SuburbEvent, new EventAction() { public void PerformAction(Bundle param) { m_suburb = param .getString(PopRequestFactory.BUNDLE_CUR_SUBURB_DATA); m_address = param .getString(PopRequestFactory.BUNDLE_CUR_ADDRESS_DATA); if (m_suburb == "") { m_stateMachine .SetState(EmState.GeoLocationRecieved); RequestSuburb(); return; } RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.SuburbEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.GeoLocationRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { if (m_suburb == null) { RequestSuburb(); } else { m_stateMachine.SetState(EmState.SuburbRecieved); RequestFuelInfo(); } Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.FuelInfoRecieved, EmEvent.FuelInfoEvent, new EventAction() { public void PerformAction(Bundle param) { m_fuelInfoList = param .getParcelableArrayList(PopRequestFactory.BUNDLE_FUEL_DATA); RequestDistanceMatrix(m_fuelInfoList); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.FuelInfoEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.DistanceRecieved, EmEvent.DistanceEvent, new EventAction() { public void PerformAction(Bundle param) { StopTimer(); DistanceMatrix distanceMatrix = param .getParcelable(PopRequestFactory.BUNDLE_DISTANCE_MATRIX_DATA); OnDistanceMatrixRecieved(distanceMatrix); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.DistanceEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.DistanceRecieved, EmEvent.RecalculatePrice, new EventAction() { public void PerformAction(Bundle param) { OnRecalculatePrice(); Notify(); } }); }
private void InitStateMachineTransitions() { m_stateMachine.AddTransition(EmState.Start, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.Start, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.GeoLocationEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.Timeout, EmState.Start, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { Start(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.SuburbRecieved, EmEvent.SuburbEvent, new EventAction() { public void PerformAction(Bundle param) { m_suburb = param .getString(PopRequestFactory.BUNDLE_CUR_SUBURB_DATA); m_address = param .getString(PopRequestFactory.BUNDLE_CUR_ADDRESS_DATA); if (m_suburb == "") { m_stateMachine .SetState(EmState.GeoLocationRecieved); RequestSuburb(); return; } RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.GeoLocationEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.GeoLocationRecieved, EmState.GeoLocationRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { if (m_suburb == null) { RequestSuburb(); } else { m_stateMachine.SetState(EmState.SuburbRecieved); RequestFuelInfo(); } Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.FuelInfoRecieved, EmEvent.FuelInfoEvent, new EventAction() { public void PerformAction(Bundle param) { m_fuelInfoList = param .getParcelableArrayList(PopRequestFactory.BUNDLE_FUEL_DATA); RequestDistanceMatrix(m_fuelInfoList); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.SuburbRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.FuelInfoEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.DistanceRecieved, EmEvent.DistanceEvent, new EventAction() { public void PerformAction(Bundle param) { StopTimer(); DistanceMatrix distanceMatrix = param .getParcelable(PopRequestFactory.BUNDLE_DISTANCE_MATRIX_DATA); OnDistanceMatrixRecieved(distanceMatrix); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.FuelInfoRecieved, EmState.Timeout, EmEvent.Timeout, new EventAction() { public void PerformAction(Bundle param) { m_timeoutEvent = EmEvent.DistanceEvent; Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.GeoLocationRecieved, EmEvent.GeoLocationEvent, new EventAction() { public void PerformAction(Bundle param) { RequestSuburb(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.SuburbRecieved, EmEvent.Refresh, new EventAction() { public void PerformAction(Bundle param) { RequestFuelInfo(); Notify(); } }); m_stateMachine.AddTransition(EmState.DistanceRecieved, EmState.DistanceRecieved, EmEvent.RecalculatePrice, new EventAction() { public void PerformAction(Bundle param) { OnRecalculatePrice(); Notify(); } }); }
diff --git a/src/com/leafdigital/browserstats/agents/IdentifyResults.java b/src/com/leafdigital/browserstats/agents/IdentifyResults.java index 25dc240..7690837 100644 --- a/src/com/leafdigital/browserstats/agents/IdentifyResults.java +++ b/src/com/leafdigital/browserstats/agents/IdentifyResults.java @@ -1,148 +1,152 @@ /* This file is part of leafdigital browserstats. browserstats 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. browserstats 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 browserstats. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Samuel Marshall. */ package com.leafdigital.browserstats.agents; import java.io.*; import java.util.*; /** Tracks data found in the identify process so that it can be written out. */ class IdentifyResults { private String[] categories; private TreeMap<Agent, Counts> agents = new TreeMap<Agent, Counts>(); private Counts unmatched; private int totalCount; private int[] totalCategoryCounts; IdentifyResults(String[] categories) { this.categories = categories; this.unmatched = new Counts(); this.totalCategoryCounts = new int[categories.length]; } /** Counts for a specific agent */ private class Counts { private int count; private int[] categoryCounts = new int[categories.length]; /** * Add counts for this agent. * @param count Total count of requests * @param categoryCounts Requests in each category */ void add(int count, int[] categoryCounts) { this.count += count; for(int i=0; i<categoryCounts.length; i++) { this.categoryCounts[i] += categoryCounts[i]; } } void write(Writer w) throws IOException { w.write("count='" + count +"'"); for(int i=0; i<categories.length; i++) { w.write(" " + categories[i] + "='" + categoryCounts[i] + "'"); } w.write("/>\n"); } } /** * Adds counts to the list. * @param agent Identified user-agent (null = unknown) * @param count Total count of requests * @param categoryCounts Requests in each category */ public void addCounts(Agent agent, int count, int[] categoryCounts) { totalCount += count; for(int i=0; i<categoryCounts.length; i++) { totalCategoryCounts[i] += categoryCounts[i]; } Counts counts = agent==null ? unmatched : agents.get(agent); if(counts==null) { counts = new Counts(); agents.put(agent, counts); } counts.add(count, categoryCounts); } /** * Writes out results. * @param f Target file (null = stdout) * @throws IOException Any error when writing */ void write(File f) throws IOException { Writer w; if(f==null) { w = new OutputStreamWriter(System.out, "UTF-8"); } else { w = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(f), "UTF-8")); } String categoryAttributes = ""; if(categories.length > 0) { for(String name : categories) { if(categoryAttributes.length()>0) { categoryAttributes += ","; } categoryAttributes += name; } categoryAttributes = " categories='" + categoryAttributes + "'"; for(int i=0; i<categories.length; i++) { categoryAttributes += " total" + categories[i] + "='" + totalCategoryCounts[i] + "'"; } } w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<knownagents totalcount='" + totalCount + "'" + categoryAttributes + ">\n"); w.write("<agent type='unknown' "); unmatched.write(w); for(Map.Entry<Agent, Counts> entry : agents.entrySet()) { entry.getKey().writeAgentTagStart(w); entry.getValue().write(w); } w.write("</knownagents>\n"); if(f!=null) { w.close(); } + else + { + w.flush(); + } } }
true
true
void write(File f) throws IOException { Writer w; if(f==null) { w = new OutputStreamWriter(System.out, "UTF-8"); } else { w = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(f), "UTF-8")); } String categoryAttributes = ""; if(categories.length > 0) { for(String name : categories) { if(categoryAttributes.length()>0) { categoryAttributes += ","; } categoryAttributes += name; } categoryAttributes = " categories='" + categoryAttributes + "'"; for(int i=0; i<categories.length; i++) { categoryAttributes += " total" + categories[i] + "='" + totalCategoryCounts[i] + "'"; } } w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<knownagents totalcount='" + totalCount + "'" + categoryAttributes + ">\n"); w.write("<agent type='unknown' "); unmatched.write(w); for(Map.Entry<Agent, Counts> entry : agents.entrySet()) { entry.getKey().writeAgentTagStart(w); entry.getValue().write(w); } w.write("</knownagents>\n"); if(f!=null) { w.close(); } }
void write(File f) throws IOException { Writer w; if(f==null) { w = new OutputStreamWriter(System.out, "UTF-8"); } else { w = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(f), "UTF-8")); } String categoryAttributes = ""; if(categories.length > 0) { for(String name : categories) { if(categoryAttributes.length()>0) { categoryAttributes += ","; } categoryAttributes += name; } categoryAttributes = " categories='" + categoryAttributes + "'"; for(int i=0; i<categories.length; i++) { categoryAttributes += " total" + categories[i] + "='" + totalCategoryCounts[i] + "'"; } } w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<knownagents totalcount='" + totalCount + "'" + categoryAttributes + ">\n"); w.write("<agent type='unknown' "); unmatched.write(w); for(Map.Entry<Agent, Counts> entry : agents.entrySet()) { entry.getKey().writeAgentTagStart(w); entry.getValue().write(w); } w.write("</knownagents>\n"); if(f!=null) { w.close(); } else { w.flush(); } }
diff --git a/plexus-quartz/src/test/java/org/codehaus/plexus/scheduler/SchedulerTest.java b/plexus-quartz/src/test/java/org/codehaus/plexus/scheduler/SchedulerTest.java index 1d0b044f..3626dc2d 100644 --- a/plexus-quartz/src/test/java/org/codehaus/plexus/scheduler/SchedulerTest.java +++ b/plexus-quartz/src/test/java/org/codehaus/plexus/scheduler/SchedulerTest.java @@ -1,63 +1,66 @@ package org.codehaus.plexus.scheduler; import org.codehaus.plexus.PlexusTestCase; import org.quartz.JobDetail; import org.quartz.Trigger; import org.quartz.SimpleTrigger; import org.quartz.TriggerListener; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; public class SchedulerTest extends PlexusTestCase implements TriggerListener { private boolean triggerFired; public void testCreation() throws Exception { - Scheduler scheduler = (Scheduler) lookup( Scheduler.ROLE ); + Scheduler scheduler = (Scheduler) lookup( Scheduler.ROLE, "test" ); assertNotNull( scheduler ); JobDataMap dataMap = new JobDataMap(); dataMap.put( "project", "continuum" ); JobDetail jobDetail = new JobDetail( "job", "group", JobOne.class ); jobDetail.setJobDataMap( dataMap ); Trigger trigger = new SimpleTrigger( "trigger", "group" ); scheduler.addGlobalTriggerListener( this ); scheduler.scheduleJob( jobDetail, trigger ); while ( ! triggerFired ) { + //System.out.println("! triggerFired"); + Thread.sleep( 10 ); } + System.out.println("ok triggerFired"); } public void triggerComplete( Trigger trigger, JobExecutionContext context, int triggerInstructionCode ) { } public boolean vetoJobExecution( Trigger trigger, JobExecutionContext context ) { return false; } public void triggerFired( Trigger trigger, JobExecutionContext context ) { System.out.println( "Trigger fired!" ); triggerFired = true; } public void triggerMisfired( Trigger trigger ) { } }
false
true
public void testCreation() throws Exception { Scheduler scheduler = (Scheduler) lookup( Scheduler.ROLE ); assertNotNull( scheduler ); JobDataMap dataMap = new JobDataMap(); dataMap.put( "project", "continuum" ); JobDetail jobDetail = new JobDetail( "job", "group", JobOne.class ); jobDetail.setJobDataMap( dataMap ); Trigger trigger = new SimpleTrigger( "trigger", "group" ); scheduler.addGlobalTriggerListener( this ); scheduler.scheduleJob( jobDetail, trigger ); while ( ! triggerFired ) { } }
public void testCreation() throws Exception { Scheduler scheduler = (Scheduler) lookup( Scheduler.ROLE, "test" ); assertNotNull( scheduler ); JobDataMap dataMap = new JobDataMap(); dataMap.put( "project", "continuum" ); JobDetail jobDetail = new JobDetail( "job", "group", JobOne.class ); jobDetail.setJobDataMap( dataMap ); Trigger trigger = new SimpleTrigger( "trigger", "group" ); scheduler.addGlobalTriggerListener( this ); scheduler.scheduleJob( jobDetail, trigger ); while ( ! triggerFired ) { //System.out.println("! triggerFired"); Thread.sleep( 10 ); } System.out.println("ok triggerFired"); }
diff --git a/maven-scm-api/src/main/java/org/apache/maven/scm/command/changelog/ChangeLogSet.java b/maven-scm-api/src/main/java/org/apache/maven/scm/command/changelog/ChangeLogSet.java index 631bb64d..fb1dd8ef 100644 --- a/maven-scm-api/src/main/java/org/apache/maven/scm/command/changelog/ChangeLogSet.java +++ b/maven-scm-api/src/main/java/org/apache/maven/scm/command/changelog/ChangeLogSet.java @@ -1,137 +1,137 @@ package org.apache.maven.scm.command.changelog; /* * Copyright 2001-2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.scm.ChangeSet; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; /** * @author <a href="mailto:[email protected]">Emmanuel Venisse</a> * @version $Id$ */ public class ChangeLogSet { private List entries; private Date startDate; private Date endDate; /** * Initializes a new instance of this class. * * @param startDate the start date/tag for this set. * @param endDate the end date/tag for this set, or <code>null</code> if this set goes to the present time. */ public ChangeLogSet( Date startDate, Date endDate ) { this.startDate = startDate; this.endDate = endDate; } /** * Initializes a new instance of this class. * * @param entries collection of {@link org.apache.maven.scm.ChangeSet} objects for this set. * @param startDate the start date/tag for this set. * @param endDate the end date/tag for this set, or <code>null</code> if this set goes to the present time. */ public ChangeLogSet( List entries, Date startDate, Date endDate ) { this.entries = entries; this.startDate = startDate; this.endDate = endDate; } /** * Returns the start date. * * @return the start date. */ public Date getStartDate() { return startDate; } /** * Returns the end date for this set. * * @return the end date for this set, or <code>null</code> if this set goes to the present time. */ public Date getEndDate() { return endDate; } /** * Returns the collection of changeSet. * * @return the collection of {@link org.apache.maven.scm.ChangeSet} objects for this set. */ public List getChangeSets() { return entries; } public void setChangeSets( List changeSets ) { this.entries = changeSets; } /** * Creates an XML representation of this change log set. */ public String toXML() { StringBuffer buffer = new StringBuffer(); String pattern = "yyyyMMdd HH:mm:ss z"; SimpleDateFormat formatter = new SimpleDateFormat( pattern ); buffer.append( "<changeset datePattern=\"" ) .append( pattern ) .append( "\"" ); if ( startDate != null ) { buffer.append( " start=\"" ) .append( formatter.format( startDate ) ) .append( "\"" ); } if ( endDate != null ) { buffer.append( " end=\"" ) .append( formatter.format( endDate ) ) - .append( "\">" ); + .append( "\"" ); } - buffer.append( "\n" ); + buffer.append( ">\n" ); // Write out the entries for ( Iterator i = getChangeSets().iterator(); i.hasNext(); ) { buffer.append( ( (ChangeSet) i.next() ).toXML() ); } buffer.append( "</changeset>\n" ); return buffer.toString(); } }
false
true
public String toXML() { StringBuffer buffer = new StringBuffer(); String pattern = "yyyyMMdd HH:mm:ss z"; SimpleDateFormat formatter = new SimpleDateFormat( pattern ); buffer.append( "<changeset datePattern=\"" ) .append( pattern ) .append( "\"" ); if ( startDate != null ) { buffer.append( " start=\"" ) .append( formatter.format( startDate ) ) .append( "\"" ); } if ( endDate != null ) { buffer.append( " end=\"" ) .append( formatter.format( endDate ) ) .append( "\">" ); } buffer.append( "\n" ); // Write out the entries for ( Iterator i = getChangeSets().iterator(); i.hasNext(); ) { buffer.append( ( (ChangeSet) i.next() ).toXML() ); } buffer.append( "</changeset>\n" ); return buffer.toString(); }
public String toXML() { StringBuffer buffer = new StringBuffer(); String pattern = "yyyyMMdd HH:mm:ss z"; SimpleDateFormat formatter = new SimpleDateFormat( pattern ); buffer.append( "<changeset datePattern=\"" ) .append( pattern ) .append( "\"" ); if ( startDate != null ) { buffer.append( " start=\"" ) .append( formatter.format( startDate ) ) .append( "\"" ); } if ( endDate != null ) { buffer.append( " end=\"" ) .append( formatter.format( endDate ) ) .append( "\"" ); } buffer.append( ">\n" ); // Write out the entries for ( Iterator i = getChangeSets().iterator(); i.hasNext(); ) { buffer.append( ( (ChangeSet) i.next() ).toXML() ); } buffer.append( "</changeset>\n" ); return buffer.toString(); }
diff --git a/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java b/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java index c5a87cbf..eeedb42e 100644 --- a/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java +++ b/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java @@ -1,671 +1,671 @@ /** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.spark.ui.rooms; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.OrFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.StreamError; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.MessageEventManager; import org.jivesoftware.smackx.packet.MessageEvent; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomButton; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.ui.FromJIDFilter; import org.jivesoftware.spark.ui.MessageEventListener; import org.jivesoftware.spark.ui.RosterDialog; import org.jivesoftware.spark.ui.VCardPanel; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscript; import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscripts; import org.jivesoftware.sparkimpl.plugin.transcripts.HistoryMessage; import org.jivesoftware.sparkimpl.profile.VCardManager; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import javax.swing.Icon; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimerTask; /** * This is the Person to Person implementation of <code>ChatRoom</code> * This room only allows for 1 to 1 conversations. */ public class ChatRoomImpl extends ChatRoom { private List messageEventListeners = new ArrayList(); private String roomname; private Icon tabIcon; private String roomTitle; private String tabTitle; private String participantJID; private String participantNickname; boolean isOnline = true; private Presence presence; private boolean offlineSent; private Roster roster; private long lastTypedCharTime; private boolean sendNotification; private TimerTask typingTimerTask; private boolean sendTypingNotification; private String threadID; private long lastActivity; /** * Constructs a 1-to-1 ChatRoom. * * @param jid the participants jid to chat with. * @param participantNickname the nickname of the participant. * @param title the title of the room. */ - public ChatRoomImpl(String jid, String participantNickname, String title) { + public ChatRoomImpl(final String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners - PacketFilter fromFilter = new FromJIDFilter(participantJID); + PacketFilter fromFilter = new FromJIDFilter(jid); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); - RosterEntry entry = roster.getEntry(participantJID); + RosterEntry entry = roster.getEntry(jid); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); - rosterDialog.setDefaultJID(participantJID); + rosterDialog.setDefaultJID(jid); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); - vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer()); + vcard.viewProfile(jid, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); } public void closeChatRoom() { super.closeChatRoom(); // Send a cancel notification event on closing if listening. if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } SparkManager.getChatManager().removeChat(this); SparkManager.getConnection().removePacketListener(this); typingTimerTask.cancel(); } public void sendMessage() { String text = getChatInputEditor().getText(); sendMessage(text); } public void sendMessage(String text) { final Message message = new Message(); if (threadID == null) { threadID = StringUtils.randomString(6); } message.setThread(threadID); // Set the body of the message using typedMessage message.setBody(text); // IF there is no body, just return and do nothing if (!ModelUtil.hasLength(text)) { return; } // Fire Message Filters SparkManager.getChatManager().filterOutgoingMessage(this, message); // Fire Global Filters SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message); sendMessage(message); sendNotification = true; } /** * Sends a message to the appropriate jid. The message is automatically added to the transcript. * * @param message the message to send. */ public void sendMessage(Message message) { lastActivity = System.currentTimeMillis(); try { getTranscriptWindow().insertMessage(getNickname(), message, ChatManager.TO_COLOR); getChatInputEditor().selectAll(); getTranscriptWindow().validate(); getTranscriptWindow().repaint(); getChatInputEditor().clear(); } catch (Exception ex) { Log.error("Error sending message", ex); } // Before sending message, let's add our full jid for full verification message.setType(Message.Type.chat); message.setTo(participantJID); message.setFrom(SparkManager.getSessionManager().getJID()); // Notify users that message has been sent fireMessageSent(message); addToTranscript(message, false); getChatInputEditor().setCaretPosition(0); getChatInputEditor().requestFocusInWindow(); scrollToBottom(); // No need to request displayed or delivered as we aren't doing anything with this // information. MessageEventManager.addNotificationsRequests(message, true, false, false, true); // Send the message that contains the notifications request try { fireOutgoingMessageSending(message); SparkManager.getConnection().sendPacket(message); } catch (Exception ex) { Log.error("Error sending message", ex); } } public String getRoomname() { return roomname; } public Icon getTabIcon() { return tabIcon; } public void setTabIcon(Icon icon) { this.tabIcon = icon; } public String getTabTitle() { return tabTitle; } public void setTabTitle(String tabTitle) { this.tabTitle = tabTitle; } public void setRoomTitle(String roomTitle) { this.roomTitle = roomTitle; } public String getRoomTitle() { return roomTitle; } public Message.Type getChatType() { return Message.Type.chat; } public void leaveChatRoom() { // There really is no such thing in Agent to Agent } public boolean isActive() { return true; } public String getParticipantJID() { return participantJID; } /** * Returns the users full jid (ex. [email protected]/spark). * * @return the users Full JID. */ public String getJID() { presence = PresenceManager.getPresence(getParticipantJID()); return presence.getFrom(); } /** * Process incoming packets. * * @param packet - the packet to process */ public void processPacket(final Packet packet) { final Runnable runnable = new Runnable() { public void run() { if (packet instanceof Presence) { presence = (Presence)packet; final Presence presence = (Presence)packet; ContactList list = SparkManager.getWorkspace().getContactList(); ContactItem contactItem = list.getContactItemByJID(getParticipantJID()); final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); String time = formatter.format(new Date()); if (presence.getType() == Presence.Type.unavailable && contactItem != null) { if (isOnline) { getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.went.offline", participantNickname, time), ChatManager.NOTIFICATION_COLOR); } isOnline = false; } else if (presence.getType() == Presence.Type.available) { if (!isOnline) { getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.came.online", participantNickname, time), ChatManager.NOTIFICATION_COLOR); } isOnline = true; } } else if (packet instanceof Message) { lastActivity = System.currentTimeMillis(); // Do something with the incoming packet here. final Message message = (Message)packet; if (message.getError() != null) { if (message.getError().getCode() == 404) { // Check to see if the user is online to recieve this message. RosterEntry entry = roster.getEntry(participantJID); if (!presence.isAvailable() && !offlineSent && entry != null) { getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline.error"), ChatManager.ERROR_COLOR); offlineSent = true; } } return; } // Check to see if the user is online to recieve this message. RosterEntry entry = roster.getEntry(participantJID); if (!presence.isAvailable() && !offlineSent && entry != null) { getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline"), ChatManager.ERROR_COLOR); offlineSent = true; } if (threadID == null) { threadID = message.getThread(); if (threadID == null) { threadID = StringUtils.randomString(6); } } boolean broadcast = message.getProperty("broadcast") != null; // If this is a group chat message, discard if (message.getType() == Message.Type.groupchat || broadcast) { return; } // Do not accept Administrative messages. final String host = SparkManager.getSessionManager().getServerAddress(); if (host.equals(message.getFrom())) { return; } // If the message is not from the current agent. Append to chat. if (message.getBody() != null) { participantJID = message.getFrom(); insertMessage(message); showTyping(false); } } } }; SwingUtilities.invokeLater(runnable); } /** * Returns the nickname of the user chatting with. * * @return the nickname of the chatting user. */ public String getParticipantNickname() { return participantNickname; } /** * The current SendField has been updated somehow. * * @param e - the DocumentEvent to respond to. */ public void insertUpdate(DocumentEvent e) { checkForText(e); if (!sendTypingNotification) { return; } lastTypedCharTime = System.currentTimeMillis(); // If the user pauses for more than two seconds, send out a new notice. if (sendNotification) { try { SparkManager.getMessageEventManager().sendComposingNotification(getParticipantJID(), threadID); sendNotification = false; } catch (Exception exception) { Log.error("Error updating", exception); } } } public void insertMessage(Message message) { // Debug info super.insertMessage(message); MessageEvent messageEvent = (MessageEvent)message.getExtension("x", "jabber:x:event"); if (messageEvent != null) { checkEvents(message.getFrom(), message.getPacketID(), messageEvent); } getTranscriptWindow().insertMessage(participantNickname, message, ChatManager.FROM_COLOR); // Set the participant jid to their full JID. participantJID = message.getFrom(); } private void checkEvents(String from, String packetID, MessageEvent messageEvent) { if (messageEvent.isDelivered() || messageEvent.isDisplayed()) { // Create the message to send Message msg = new Message(from); // Create a MessageEvent Package and add it to the message MessageEvent event = new MessageEvent(); if (messageEvent.isDelivered()) { event.setDelivered(true); } if (messageEvent.isDisplayed()) { event.setDisplayed(true); } event.setPacketID(packetID); msg.addExtension(event); // Send the packet SparkManager.getConnection().sendPacket(msg); } } public void addMessageEventListener(MessageEventListener listener) { messageEventListeners.add(listener); } public void removeMessageEventListener(MessageEventListener listener) { messageEventListeners.remove(listener); } public Collection getMessageEventListeners() { return messageEventListeners; } public void fireOutgoingMessageSending(Message message) { Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator(); while (messageEventListeners.hasNext()) { ((MessageEventListener)messageEventListeners.next()).sendingMessage(message); } } public void fireReceivingIncomingMessage(Message message) { Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator(); while (messageEventListeners.hasNext()) { ((MessageEventListener)messageEventListeners.next()).receivingMessage(message); } } /** * Show the typing notification. * * @param typing true if the typing notification should show, otherwise hide it. */ public void showTyping(boolean typing) { if (typing) { String isTypingText = Res.getString("message.is.typing.a.message", participantNickname); getNotificationLabel().setText(isTypingText); getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE)); } else { // Remove is typing text. getNotificationLabel().setText(""); getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.BLANK_IMAGE)); } } /** * The last time this chat room sent or received a message. * * @return the last time this chat room sent or receieved a message. */ public long getLastActivity() { return lastActivity; } /** * Returns the current presence of the client this room was created for. * * @return the presence */ public Presence getPresence() { return presence; } public void setSendTypingNotification(boolean isSendTypingNotification) { this.sendTypingNotification = isSendTypingNotification; } public void connectionClosed() { handleDisconnect(); String message = Res.getString("message.disconnected.error"); getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR); } public void connectionClosedOnError(Exception ex) { handleDisconnect(); String message = Res.getString("message.disconnected.error"); if (ex instanceof XMPPException) { XMPPException xmppEx = (XMPPException)ex; StreamError error = xmppEx.getStreamError(); String reason = error.getCode(); if ("conflict".equals(reason)) { message = Res.getString("message.disconnected.conflict.error"); } } getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR); } public void reconnectionSuccessful() { Presence usersPresence = PresenceManager.getPresence(getParticipantJID()); if (usersPresence.isAvailable()) { presence = usersPresence; } SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this); getChatInputEditor().setEnabled(true); getSendButton().setEnabled(true); } private void handleDisconnect() { presence = new Presence(Presence.Type.unavailable); getChatInputEditor().setEnabled(false); getSendButton().setEnabled(false); SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this); } private void loadHistory() { // Add VCard Panel final VCardPanel vcardPanel = new VCardPanel(participantJID); getToolBar().add(vcardPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 2), 0, 0)); final LocalPreferences localPreferences = SettingsManager.getLocalPreferences(); if (!localPreferences.isChatHistoryEnabled()) { return; } final String bareJID = StringUtils.parseBareAddress(getParticipantJID()); final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID); final String personalNickname = SparkManager.getUserManager().getNickname(); for (HistoryMessage message : chatTranscript.getMessages()) { String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String messageBody = message.getBody(); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) { messageBody = messageBody.replaceAll("/me", nickname); } final Date messageDate = message.getDate(); getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate); } } }
false
true
public ChatRoomImpl(String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners PacketFilter fromFilter = new FromJIDFilter(participantJID); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); RosterEntry entry = roster.getEntry(participantJID); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); rosterDialog.setDefaultJID(participantJID); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); }
public ChatRoomImpl(final String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners PacketFilter fromFilter = new FromJIDFilter(jid); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); RosterEntry entry = roster.getEntry(jid); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); rosterDialog.setDefaultJID(jid); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); vcard.viewProfile(jid, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); }
diff --git a/org.iucn.sis.client.shared/src/org/iucn/sis/shared/api/schemes/ClassificationSchemeRowEditorWindow.java b/org.iucn.sis.client.shared/src/org/iucn/sis/shared/api/schemes/ClassificationSchemeRowEditorWindow.java index a39dd186..55d03c32 100644 --- a/org.iucn.sis.client.shared/src/org/iucn/sis/shared/api/schemes/ClassificationSchemeRowEditorWindow.java +++ b/org.iucn.sis.client.shared/src/org/iucn/sis/shared/api/schemes/ClassificationSchemeRowEditorWindow.java @@ -1,249 +1,249 @@ package org.iucn.sis.shared.api.schemes; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.iucn.sis.shared.api.data.TreeData; import org.iucn.sis.shared.api.data.TreeDataRow; import com.extjs.gxt.ui.client.Style.HorizontalAlignment; import com.extjs.gxt.ui.client.Style.LayoutRegion; import com.extjs.gxt.ui.client.Style.Scroll; import com.extjs.gxt.ui.client.data.BaseModelData; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.Window; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.ComboBox; import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction; import com.extjs.gxt.ui.client.widget.layout.BorderLayout; import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; import com.extjs.gxt.ui.client.widget.layout.FillLayout; import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem; import com.extjs.gxt.ui.client.widget.toolbar.ToolBar; import com.solertium.util.events.ComplexListener; import com.solertium.util.events.SimpleListener; import com.solertium.util.extjs.client.WindowUtils; import com.solertium.util.gwt.ui.DrawsLazily; public class ClassificationSchemeRowEditorWindow extends Window implements DrawsLazily { public enum EditMode { NEW, EXISTING } protected final String description; protected final TreeData treeData; protected final ClassificationSchemeViewer parent; protected final EditMode mode; protected final boolean isViewOnly; protected String saveButtonText = "Save Selection"; protected ClassificationSchemeRowEditor editor; protected ComplexListener<ClassificationSchemeModelData> saveListener; protected SimpleListener cancelListener; public ClassificationSchemeRowEditorWindow(ClassificationSchemeViewer parent, TreeData treeData, String description, ClassificationSchemeModelData model, EditMode mode, boolean isViewOnly) { super(); this.parent = parent; this.description = description; this.treeData = treeData; this.mode = mode; this.isViewOnly = isViewOnly; setModel(model); setLayout(new FillLayout()); setLayoutOnChange(true); setModal(true); setClosable(false); setSize(800, 600); setScrollMode(Scroll.AUTO); setHeading((EditMode.NEW.equals(mode) ? "New " : "Edit ") + description); setButtonAlign(HorizontalAlignment.CENTER); } public void setSaveListener(ComplexListener<ClassificationSchemeModelData> saveListener) { this.saveListener = saveListener; } public void setCancelListener(SimpleListener cancelListener) { this.cancelListener = cancelListener; } public void show() { draw(new DrawsLazily.DoneDrawingWithNothingToDoCallback() { public void isDrawn() { open(); } }); } protected void drawButtons(final ComboBox<CodingOption> box, final ClassificationSchemeModelData model) { addButton(new Button(isEditing() ? "Done" : "Save Selection", new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { if (EditMode.NEW.equals(mode)) { if (box.getValue() == null) { WindowUtils.errorAlert("Please select a coding option from the drop-down."); return; } if (parent.containsRow(box.getValue().getRow())) { WindowUtils.errorAlert("A row with this coding option has already been selected."); return; } model.setSelectedRow(box.getValue().getRow()); } saveSelection(model); } })); if (!isEditing()) addButton(new Button("Cancel", new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { cancel(model); } })); } @Override public void draw(final DoneDrawingCallback callback) { removeAll(); getButtonBar().removeAll(); final ClassificationSchemeModelData model = getModel(); editor = createRowEditor(model, isViewOnly); editor.setModel(model); editor.draw(new DrawsLazily.DoneDrawingCallback() { public void isDrawn() { final ComboBox<CodingOption> box = createClassificationOptions(model.getSelectedRow()); box.setEnabled(EditMode.NEW.equals(mode)); final ToolBar top = new ToolBar(); top.add(new LabelToolItem(description+":")); top.add(box); final LayoutContainer container = new LayoutContainer(new BorderLayout()); container.add(top, new BorderLayoutData(LayoutRegion.NORTH, 25, 25, 25)); container.add(editor, new BorderLayoutData(LayoutRegion.CENTER)); add(container); if (isViewOnly) { addButton(new Button("Close", new SelectionListener<ButtonEvent>() { public void componentSelected(ButtonEvent ce) { hide(); } })); } else { drawButtons(box, model); } callback.isDrawn(); } }); } private void open() { super.show(); } protected ClassificationSchemeRowEditor createRowEditor(ClassificationSchemeModelData model, boolean isViewOnly) { return new ClassificationSchemeRowEditor(isViewOnly); } protected void saveSelection(ClassificationSchemeModelData model) { if (saveListener != null) saveListener.handleEvent(model); hide(); } protected void cancel(ClassificationSchemeModelData model) { if (cancelListener != null) cancelListener.handleEvent(); hide(); } protected boolean isEditing() { return EditMode.EXISTING.equals(mode); } protected ComboBox<CodingOption> createClassificationOptions(TreeDataRow selected) { /* * Flatten the tree into a list... */ final List<TreeDataRow> list = new ArrayList<TreeDataRow>(treeData.flattenTree().values()); Collections.sort(list, new BasicClassificationSchemeViewer.TreeDataRowComparator()); final ListStore<CodingOption> store = new ListStore<CodingOption>(); CodingOption selectedOption = null; for (TreeDataRow row : list) { /* * Weed out legacy data */ - if (row.getRowNumber().indexOf('.') < 0) { + if ("100".equals(row.getRowNumber()) || row.getRowNumber().indexOf('.') > 0) { try { if (Integer.parseInt(row.getRowNumber()) >= 100) continue; } catch (NumberFormatException e) { - continue; + //Not a number, doesn't apply to deprecation format } } if ("true".equals(row.getCodeable())) { final CodingOption option = new CodingOption(row); store.add(option); if (row.equals(selected)) selectedOption = option; } } final ComboBox<CodingOption> box = new ComboBox<CodingOption>(); box.setStore(store); box.setForceSelection(true); box.setTriggerAction(TriggerAction.ALL); box.setWidth(575); if (selectedOption != null) box.setValue(selectedOption); return box; } protected static class CodingOption extends BaseModelData { private static final long serialVersionUID = 1L; private final TreeDataRow row; public CodingOption(TreeDataRow row) { super(); this.row = row; set("text", row.getFullLineage()); set("value", row.getDisplayId()); } public String getValue() { return get("value"); } public TreeDataRow getRow() { return row; } public boolean isCodeable() { return "true".equals(row.getCodeable()); } } }
false
true
protected ComboBox<CodingOption> createClassificationOptions(TreeDataRow selected) { /* * Flatten the tree into a list... */ final List<TreeDataRow> list = new ArrayList<TreeDataRow>(treeData.flattenTree().values()); Collections.sort(list, new BasicClassificationSchemeViewer.TreeDataRowComparator()); final ListStore<CodingOption> store = new ListStore<CodingOption>(); CodingOption selectedOption = null; for (TreeDataRow row : list) { /* * Weed out legacy data */ if (row.getRowNumber().indexOf('.') < 0) { try { if (Integer.parseInt(row.getRowNumber()) >= 100) continue; } catch (NumberFormatException e) { continue; } } if ("true".equals(row.getCodeable())) { final CodingOption option = new CodingOption(row); store.add(option); if (row.equals(selected)) selectedOption = option; } } final ComboBox<CodingOption> box = new ComboBox<CodingOption>(); box.setStore(store); box.setForceSelection(true); box.setTriggerAction(TriggerAction.ALL); box.setWidth(575); if (selectedOption != null) box.setValue(selectedOption); return box; }
protected ComboBox<CodingOption> createClassificationOptions(TreeDataRow selected) { /* * Flatten the tree into a list... */ final List<TreeDataRow> list = new ArrayList<TreeDataRow>(treeData.flattenTree().values()); Collections.sort(list, new BasicClassificationSchemeViewer.TreeDataRowComparator()); final ListStore<CodingOption> store = new ListStore<CodingOption>(); CodingOption selectedOption = null; for (TreeDataRow row : list) { /* * Weed out legacy data */ if ("100".equals(row.getRowNumber()) || row.getRowNumber().indexOf('.') > 0) { try { if (Integer.parseInt(row.getRowNumber()) >= 100) continue; } catch (NumberFormatException e) { //Not a number, doesn't apply to deprecation format } } if ("true".equals(row.getCodeable())) { final CodingOption option = new CodingOption(row); store.add(option); if (row.equals(selected)) selectedOption = option; } } final ComboBox<CodingOption> box = new ComboBox<CodingOption>(); box.setStore(store); box.setForceSelection(true); box.setTriggerAction(TriggerAction.ALL); box.setWidth(575); if (selectedOption != null) box.setValue(selectedOption); return box; }
diff --git a/src/org/apache/xml/utils/DOMBuilder.java b/src/org/apache/xml/utils/DOMBuilder.java index e0f76457..72c6049e 100644 --- a/src/org/apache/xml/utils/DOMBuilder.java +++ b/src/org/apache/xml/utils/DOMBuilder.java @@ -1,756 +1,758 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xml.utils; import org.apache.xalan.res.XSLMessages; import org.apache.xpath.res.XPATHErrorResources; import org.apache.xml.utils.NodeVector; import java.util.Stack; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.Attributes; import org.w3c.dom.*; // we pretty much use everything in the DOM here. /** * <meta name="usage" content="general"/> * This class takes SAX events (in addition to some extra events * that SAX doesn't handle yet) and adds the result to a document * or document fragment. */ public class DOMBuilder implements ContentHandler, LexicalHandler { /** Root document */ public Document m_doc; /** Current node */ protected Node m_currentNode = null; /** First node of document fragment or null if not a DocumentFragment */ public DocumentFragment m_docFrag = null; /** Vector of element nodes */ protected Stack m_elemStack = new Stack(); /** * DOMBuilder instance constructor... it will add the DOM nodes * to the document fragment. * * @param doc Root document * @param node Current node */ public DOMBuilder(Document doc, Node node) { m_doc = doc; m_currentNode = node; } /** * DOMBuilder instance constructor... it will add the DOM nodes * to the document fragment. * * @param doc Root document * @param docFrag Document fragment */ public DOMBuilder(Document doc, DocumentFragment docFrag) { m_doc = doc; m_docFrag = docFrag; } /** * DOMBuilder instance constructor... it will add the DOM nodes * to the document. * * @param doc Root document */ public DOMBuilder(Document doc) { m_doc = doc; } /** * Get the root node of the DOM being created. This * is either a Document or a DocumentFragment. * * @return The root document or document fragment if not null */ public Node getRootNode() { return (null != m_docFrag) ? (Node) m_docFrag : (Node) m_doc; } /** * Get the node currently being processed. * * @return the current node being processed */ public Node getCurrentNode() { return m_currentNode; } /** * Return null since there is no Writer for this class. * * @return null */ public java.io.Writer getWriter() { return null; } /** * Append a node to the current container. * * @param newNode New node to append */ protected void append(Node newNode) throws org.xml.sax.SAXException { Node currentNode = m_currentNode; if (null != currentNode) { currentNode.appendChild(newNode); // System.out.println(newNode.getNodeName()); } else if (null != m_docFrag) { m_docFrag.appendChild(newNode); } else { boolean ok = true; short type = newNode.getNodeType(); if (type == Node.TEXT_NODE) { String data = newNode.getNodeValue(); if ((null != data) && (data.trim().length() > 0)) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC, null)); //"Warning: can't output text before document element! Ignoring..."); } ok = false; } else if (type == Node.ELEMENT_NODE) { if (m_doc.getDocumentElement() != null) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT, null)); //"Can't have more than one root on a DOM!"); } } if (ok) m_doc.appendChild(newNode); } } /** * Receive an object for locating the origin of SAX document events. * * <p>SAX parsers are strongly encouraged (though not absolutely * required) to supply a locator: if it does so, it must supply * the locator to the application by invoking this method before * invoking any of the other methods in the ContentHandler * interface.</p> * * <p>The locator allows the application to determine the end * position of any document-related event, even if the parser is * not reporting an error. Typically, the application will * use this information for reporting its own errors (such as * character content that does not match an application's * business rules). The information returned by the locator * is probably not sufficient for use with a search engine.</p> * * <p>Note that the locator will return correct information only * during the invocation of the events in this interface. The * application should not attempt to use it at any other time.</p> * * @param locator An object that can return the location of * any SAX document event. * @see org.xml.sax.Locator */ public void setDocumentLocator(Locator locator) { // No action for the moment. } /** * Receive notification of the beginning of a document. * * <p>The SAX parser will invoke this method only once, before any * other methods in this interface or in DTDHandler (except for * setDocumentLocator).</p> */ public void startDocument() throws org.xml.sax.SAXException { // No action for the moment. } /** * Receive notification of the end of a document. * * <p>The SAX parser will invoke this method only once, and it will * be the last method invoked during the parse. The parser shall * not invoke this method until it has either abandoned parsing * (because of an unrecoverable error) or reached the end of * input.</p> */ public void endDocument() throws org.xml.sax.SAXException { // No action for the moment. } /** * Receive notification of the beginning of an element. * * <p>The Parser will invoke this method at the beginning of every * element in the XML document; there will be a corresponding * endElement() event for every startElement() event (even when the * element is empty). All of the element's content will be * reported, in order, before the corresponding endElement() * event.</p> * * <p>If the element name has a namespace prefix, the prefix will * still be attached. Note that the attribute list provided will * contain only attributes with explicit values (specified or * defaulted): #IMPLIED attributes will be omitted.</p> * * * @param ns The namespace of the node * @param localName The local part of the qualified name * @param name The element name. * @param atts The attributes attached to the element, if any. * @see #endElement * @see org.xml.sax.Attributes */ public void startElement( String ns, String localName, String name, Attributes atts) throws org.xml.sax.SAXException { Element elem; + // Note that the namespace-aware call must be used to correctly + // construct a Level 2 DOM, even for non-namespaced nodes. if ((null == ns) || (ns.length() == 0)) - elem = m_doc.createElement(name); + elem = m_doc.createElementNS(null,name); else elem = m_doc.createElementNS(ns, name); append(elem); try { int nAtts = atts.getLength(); if (0 != nAtts) { for (int i = 0; i < nAtts; i++) { //System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) ); // First handle a possible ID attribute if (atts.getType(i).equalsIgnoreCase("ID")) setIDAttribute(atts.getValue(i), elem); String attrNS = atts.getURI(i); if(attrNS == null) attrNS = ""; // defensive, shouldn't have to do this. // System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i) // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i)); // Crimson won't let us set an xmlns: attribute on the DOM. String attrQName = atts.getQName(i); if ((attrNS.length() == 0) /* || attrQName.startsWith("xmlns:") || attrQName.equals("xmlns") */) elem.setAttribute(attrQName, atts.getValue(i)); else { // elem.setAttributeNS(atts.getURI(i), atts.getLocalName(i), atts.getValue(i)); elem.setAttributeNS(attrNS, attrQName, atts.getValue(i)); } } } // append(elem); m_elemStack.push(elem); m_currentNode = elem; // append(elem); } catch(java.lang.Exception de) { // de.printStackTrace(); throw new org.xml.sax.SAXException(de); } } /** * Receive notification of the end of an element. * * <p>The SAX parser will invoke this method at the end of every * element in the XML document; there will be a corresponding * startElement() event for every endElement() event (even when the * element is empty).</p> * * <p>If the element name has a namespace prefix, the prefix will * still be attached to the name.</p> * * * @param ns the namespace of the element * @param localName The local part of the qualified name of the element * @param name The element name */ public void endElement(String ns, String localName, String name) throws org.xml.sax.SAXException { m_elemStack.pop(); m_currentNode = m_elemStack.isEmpty() ? null : (Node)m_elemStack.peek(); } /** * Set an ID string to node association in the ID table. * * @param id The ID string. * @param elem The associated ID. */ public void setIDAttribute(String id, Element elem) { // Do nothing. This method is meant to be overiden. } /** * Receive notification of character data. * * <p>The Parser will call this method to report each chunk of * character data. SAX parsers may return all contiguous character * data in a single chunk, or they may split it into several * chunks; however, all of the characters in any single event * must come from the same external entity, so that the Locator * provides useful information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Note that some parsers will report whitespace using the * ignorableWhitespace() method rather than this one (validating * parsers must do so).</p> * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @see #ignorableWhitespace * @see org.xml.sax.Locator */ public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException { if(isOutsideDocElem() && org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length)) return; // avoid DOM006 Hierarchy request error if (m_inCData) { cdata(ch, start, length); return; } String s = new String(ch, start, length); Text text = m_doc.createTextNode(s); append(text); } /** * If available, when the disable-output-escaping attribute is used, * output raw text without escaping. A PI will be inserted in front * of the node with the name "lotusxsl-next-is-raw" and a value of * "formatter-to-dom". * * @param ch Array containing the characters * @param start Index to start of characters in the array * @param length Number of characters in the array */ public void charactersRaw(char ch[], int start, int length) throws org.xml.sax.SAXException { if(isOutsideDocElem() && org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length)) return; // avoid DOM006 Hierarchy request error String s = new String(ch, start, length); append(m_doc.createProcessingInstruction("xslt-next-is-raw", "formatter-to-dom")); append(m_doc.createTextNode(s)); } /** * Report the beginning of an entity. * * The start and end of the document entity are not reported. * The start and end of the external DTD subset are reported * using the pseudo-name "[dtd]". All other events must be * properly nested within start/end entity events. * * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%'. * @see #endEntity * @see org.xml.sax.ext.DeclHandler#internalEntityDecl * @see org.xml.sax.ext.DeclHandler#externalEntityDecl */ public void startEntity(String name) throws org.xml.sax.SAXException { // Almost certainly the wrong behavior... // entityReference(name); } /** * Report the end of an entity. * * @param name The name of the entity that is ending. * @see #startEntity */ public void endEntity(String name) throws org.xml.sax.SAXException{} /** * Receive notivication of a entityReference. * * @param name name of the entity reference */ public void entityReference(String name) throws org.xml.sax.SAXException { append(m_doc.createEntityReference(name)); } /** * Receive notification of ignorable whitespace in element content. * * <p>Validating Parsers must use this method to report each chunk * of ignorable whitespace (see the W3C XML 1.0 recommendation, * section 2.10): non-validating parsers may also use this method * if they are capable of parsing and using content models.</p> * * <p>SAX parsers may return all contiguous whitespace in a single * chunk, or they may split it into several chunks; however, all of * the characters in any single event must come from the same * external entity, so that the Locator provides useful * information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @see #characters */ public void ignorableWhitespace(char ch[], int start, int length) throws org.xml.sax.SAXException { if(isOutsideDocElem()) return; // avoid DOM006 Hierarchy request error String s = new String(ch, start, length); append(m_doc.createTextNode(s)); } /** * Tell if the current node is outside the document element. * * @return true if the current node is outside the document element. */ private boolean isOutsideDocElem() { return (null == m_docFrag) && m_elemStack.size() == 0 && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE); } /** * Receive notification of a processing instruction. * * <p>The Parser will invoke this method once for each processing * instruction found: note that processing instructions may occur * before or after the main document element.</p> * * <p>A SAX parser should never report an XML declaration (XML 1.0, * section 2.8) or a text declaration (XML 1.0, section 4.3.1) * using this method.</p> * * @param target The processing instruction target. * @param data The processing instruction data, or null if * none was supplied. */ public void processingInstruction(String target, String data) throws org.xml.sax.SAXException { append(m_doc.createProcessingInstruction(target, data)); } /** * Report an XML comment anywhere in the document. * * This callback will be used for comments inside or outside the * document element, including comments in the external DTD * subset (if read). * * @param ch An array holding the characters in the comment. * @param start The starting position in the array. * @param length The number of characters to use from the array. */ public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException { append(m_doc.createComment(new String(ch, start, length))); } /** Flag indicating that we are processing a CData section */ protected boolean m_inCData = false; /** * Report the start of a CDATA section. * * @see #endCDATA */ public void startCDATA() throws org.xml.sax.SAXException { m_inCData = true; } /** * Report the end of a CDATA section. * * @see #startCDATA */ public void endCDATA() throws org.xml.sax.SAXException { m_inCData = false; } /** * Receive notification of cdata. * * <p>The Parser will call this method to report each chunk of * character data. SAX parsers may return all contiguous character * data in a single chunk, or they may split it into several * chunks; however, all of the characters in any single event * must come from the same external entity, so that the Locator * provides useful information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Note that some parsers will report whitespace using the * ignorableWhitespace() method rather than this one (validating * parsers must do so).</p> * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @see #ignorableWhitespace * @see org.xml.sax.Locator */ public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException { if(isOutsideDocElem() && org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length)) return; // avoid DOM006 Hierarchy request error String s = new String(ch, start, length); append(m_doc.createCDATASection(s)); } /** * Report the start of DTD declarations, if any. * * Any declarations are assumed to be in the internal subset * unless otherwise indicated. * * @param name The document type name. * @param publicId The declared public identifier for the * external DTD subset, or null if none was declared. * @param systemId The declared system identifier for the * external DTD subset, or null if none was declared. * @see #endDTD * @see #startEntity */ public void startDTD(String name, String publicId, String systemId) throws org.xml.sax.SAXException { // Do nothing for now. } /** * Report the end of DTD declarations. * * @see #startDTD */ public void endDTD() throws org.xml.sax.SAXException { // Do nothing for now. } /** * Begin the scope of a prefix-URI Namespace mapping. * * <p>The information from this event is not necessary for * normal Namespace processing: the SAX XML reader will * automatically replace prefixes for element and attribute * names when the http://xml.org/sax/features/namespaces * feature is true (the default).</p> * * <p>There are cases, however, when applications need to * use prefixes in character data or in attribute values, * where they cannot safely be expanded automatically; the * start/endPrefixMapping event supplies the information * to the application to expand prefixes in those contexts * itself, if necessary.</p> * * <p>Note that start/endPrefixMapping events are not * guaranteed to be properly nested relative to each-other: * all startPrefixMapping events will occur before the * corresponding startElement event, and all endPrefixMapping * events will occur after the corresponding endElement event, * but their order is not guaranteed.</p> * * @param prefix The Namespace prefix being declared. * @param uri The Namespace URI the prefix is mapped to. * @see #endPrefixMapping * @see #startElement */ public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { /* // Not sure if this is needed or wanted // Also, it fails in the stree. if((null != m_currentNode) && (m_currentNode.getNodeType() == Node.ELEMENT_NODE)) { String qname; if(((null != prefix) && (prefix.length() == 0)) || (null == prefix)) qname = "xmlns"; else qname = "xmlns:"+prefix; Element elem = (Element)m_currentNode; String val = elem.getAttribute(qname); if(val == null) { elem.setAttributeNS("http://www.w3.org/XML/1998/namespace", qname, uri); } } */ } /** * End the scope of a prefix-URI mapping. * * <p>See startPrefixMapping for details. This event will * always occur after the corresponding endElement event, * but the order of endPrefixMapping events is not otherwise * guaranteed.</p> * * @param prefix The prefix that was being mapping. * @see #startPrefixMapping * @see #endElement */ public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException{} /** * Receive notification of a skipped entity. * * <p>The Parser will invoke this method once for each entity * skipped. Non-validating processors may skip entities if they * have not seen the declarations (because, for example, the * entity was declared in an external DTD subset). All processors * may skip external entities, depending on the values of the * http://xml.org/sax/features/external-general-entities and the * http://xml.org/sax/features/external-parameter-entities * properties.</p> * * @param name The name of the skipped entity. If it is a * parameter entity, the name will begin with '%'. */ public void skippedEntity(String name) throws org.xml.sax.SAXException{} }
false
true
public void startElement( String ns, String localName, String name, Attributes atts) throws org.xml.sax.SAXException { Element elem; if ((null == ns) || (ns.length() == 0)) elem = m_doc.createElement(name); else elem = m_doc.createElementNS(ns, name); append(elem); try { int nAtts = atts.getLength(); if (0 != nAtts) { for (int i = 0; i < nAtts; i++) { //System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) ); // First handle a possible ID attribute if (atts.getType(i).equalsIgnoreCase("ID")) setIDAttribute(atts.getValue(i), elem); String attrNS = atts.getURI(i); if(attrNS == null) attrNS = ""; // defensive, shouldn't have to do this. // System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i) // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i)); // Crimson won't let us set an xmlns: attribute on the DOM. String attrQName = atts.getQName(i); if ((attrNS.length() == 0) /* || attrQName.startsWith("xmlns:") || attrQName.equals("xmlns") */) elem.setAttribute(attrQName, atts.getValue(i)); else { // elem.setAttributeNS(atts.getURI(i), atts.getLocalName(i), atts.getValue(i)); elem.setAttributeNS(attrNS, attrQName, atts.getValue(i)); } } } // append(elem); m_elemStack.push(elem); m_currentNode = elem; // append(elem); } catch(java.lang.Exception de) { // de.printStackTrace(); throw new org.xml.sax.SAXException(de); } }
public void startElement( String ns, String localName, String name, Attributes atts) throws org.xml.sax.SAXException { Element elem; // Note that the namespace-aware call must be used to correctly // construct a Level 2 DOM, even for non-namespaced nodes. if ((null == ns) || (ns.length() == 0)) elem = m_doc.createElementNS(null,name); else elem = m_doc.createElementNS(ns, name); append(elem); try { int nAtts = atts.getLength(); if (0 != nAtts) { for (int i = 0; i < nAtts; i++) { //System.out.println("type " + atts.getType(i) + " name " + atts.getLocalName(i) ); // First handle a possible ID attribute if (atts.getType(i).equalsIgnoreCase("ID")) setIDAttribute(atts.getValue(i), elem); String attrNS = atts.getURI(i); if(attrNS == null) attrNS = ""; // defensive, shouldn't have to do this. // System.out.println("attrNS: "+attrNS+", localName: "+atts.getQName(i) // +", qname: "+atts.getQName(i)+", value: "+atts.getValue(i)); // Crimson won't let us set an xmlns: attribute on the DOM. String attrQName = atts.getQName(i); if ((attrNS.length() == 0) /* || attrQName.startsWith("xmlns:") || attrQName.equals("xmlns") */) elem.setAttribute(attrQName, atts.getValue(i)); else { // elem.setAttributeNS(atts.getURI(i), atts.getLocalName(i), atts.getValue(i)); elem.setAttributeNS(attrNS, attrQName, atts.getValue(i)); } } } // append(elem); m_elemStack.push(elem); m_currentNode = elem; // append(elem); } catch(java.lang.Exception de) { // de.printStackTrace(); throw new org.xml.sax.SAXException(de); } }
diff --git a/NacaTrans/src/parser/Cobol/elements/CBlocElement.java b/NacaTrans/src/parser/Cobol/elements/CBlocElement.java index 7ae98b3..0b3c7b0 100644 --- a/NacaTrans/src/parser/Cobol/elements/CBlocElement.java +++ b/NacaTrans/src/parser/Cobol/elements/CBlocElement.java @@ -1,699 +1,700 @@ /* * NacaRTTests - Naca Tests for NacaRT support. * * Copyright (c) 2005, 2006, 2007, 2008 Publicitas SA. * Licensed under GPL (GPL-LICENSE.txt) license. */ /* * Created on Jul 19, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package parser.Cobol.elements; import lexer.*; import lexer.Cobol.CCobolKeywordList; import parser.*; import parser.Cobol.CCobolElement; import parser.Cobol.elements.CICS.*; import parser.Cobol.elements.SQL.*; import parser.expression.CIdentifierTerminal; import parser.expression.CTerminal; import semantic.CBaseLanguageEntity; import semantic.CBaseEntityFactory; import semantic.CEntityBloc; import utils.CGlobalEntityCounter; import utils.Transcoder; /** * @author U930CV * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public abstract class CBlocElement extends CCommentContainer { /** * @param line */ public CBlocElement(int line) { super(line); } protected boolean DoParsing() { boolean bDone = false ; while (!bDone) { CBaseToken tokVerb = GetCurrentToken() ; if (tokVerb == null) { return true ; } if (tokVerb.GetType()==CTokenType.KEYWORD) { if (!ParseVerb()) { Transcoder.logError(getLine(), "Failure while parsing keyword '" + tokVerb.GetValue() + "'") ; } if (tokVerb == GetCurrentToken()) { // this keyword has not been parsed m_nEndLine = tokVerb.getLine()-1 ; bDone = true; } } else if (tokVerb.GetType() == CTokenType.SEMI_COLON) { GetNext(); } else { m_nEndLine = tokVerb.getLine()-1 ; bDone = true ; // this token can't be parsed by this function } } return true; } protected CCobolElement GetCICSVerb() { CCobolElement e = null ; CBaseToken tok = GetCurrentToken() ; if (tok.GetKeyword() == CCobolKeywordList.ADDRESS) { e = new CExecCICSAddress(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.LINK) { e = new CExecCICSLink(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.XCTL) { e = new CExecCICSXctl(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.IGNORE) { e = new CExecCICSIgnore(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.RETRIEVE) { e = new CExecCICSRetrieve(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.RECEIVE) { e = new CExecCICSReceive(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ASKTIME) { e = new CExecCICSAskTime(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.BIF) { e = new CExecCICSBif(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.READQ) { e = new CExecCICSReadQ(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.RETURN) { e = new CExecCICSReturn(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.HANDLE) { e = new CExecCICSHandle(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ENQ) { e = new CExecCICSEnq(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ASSIGN) { e = new CExecCICSAssign(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.SEND) { e = new CExecCICSSend(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.SYNCPOINT) { e = new CExecCICSSyncPoint(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.WRITE) { e = new CExecCICSWrite(tok.getLine()); } else if (tok.GetType() == CTokenType.IDENTIFIER && tok.GetValue().equals("ABEND")) { e = new CExecCICSAbend(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.DELETEQ) { e = new CExecCICSDeleteQ(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.WRITEQ) { e = new CExecCICSWriteQ(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.DEQ) { e = new CExecCICSDeQ(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.INQUIRE) { e = new CExecCICSInquire(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.READ) { e = new CExecCICSRead(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.START) { e = new CExecCICSStart(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.SET) { e = new CExecCICSSet(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.DELAY) { e = new CExecCICSDelay(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.REWRITE) { e = new CExecCICSReWrite(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.GETMAIN) { e = new CExecCICSGetMain(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.READNEXT) { e = new CExecCICSReadNext(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.STARTBR) { e = new CExecCICSStartBR(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ENDBR) { e = new CExecCICSEndBR(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.DELETE) { e = new CExecCICSDelete(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.UNLOCK) { e = new CExecCICSUnLock(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.READPREV) { e = new CExecCICSReadPrev(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ALLOCATE) { e = new CExecCICSAllocate(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.CONNECT) { e = new CExecCICSConnect(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.FREE) { e = new CExecCICSFree(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.CONVERSE) { e = new CExecCICSConverse(tok.getLine()); } else if (tok.GetKeyword() == CCobolKeywordList.ENABLE) { e = new CExecCICSEnable(tok.getLine()); } // else if (tok.GetKeyword() == CCobolKeywordList.ADDRESS) // { // } else { Transcoder.logError(tok.getLine(), "Unrecognized CICS command : " + tok.GetValue()); e = new CExecStatement(tok.getLine()) ; } CGlobalEntityCounter.GetInstance().CountCICSCommand(tok.GetValue()) ; return e ; } protected int m_nRewriteLine = 0; protected boolean ParseVerb() { CBaseToken tokVerb = GetCurrentToken() ; if (m_fCheckForNextSentence.ISSet()) { if (tokVerb.GetKeyword() == CCobolKeywordList.END_IF || tokVerb.GetKeyword() == CCobolKeywordList.ELSE || + tokVerb.GetKeyword() == CCobolKeywordList.WHEN || tokVerb.GetKeyword() == CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword() == CCobolKeywordList.END_EVALUATE || tokVerb.GetType() == CTokenType.DOT) { return true ; } else if (!isTopLevelBloc()) { Transcoder.logError(tokVerb.getLine(), "Unrecommanded usage of NEXT SENTENCE"); m_nRewriteLine = tokVerb.getLine() ; } } if (tokVerb.GetKeyword()==CCobolKeywordList.EXEC) { CBaseToken tokType = GetNext() ; CCobolElement eExec = null ; if (tokType.GetKeyword() == CCobolKeywordList.SQL) { eExec = new CExecSQL(tokVerb.getLine()) ; } else if (tokType.GetKeyword() == CCobolKeywordList.CICS) { GetNext(); eExec = GetCICSVerb(); if (eExec == null) { return true ; // ignore EXEC CICS that are not parsed } } else { eExec = new CExecStatement(tokVerb.getLine()) ; } AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MOVE) { CCobolElement eExec = new CMove(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EXIT) { CCobolElement eExec = new CExit(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EJECT) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SKIP3) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.START) { CCobolElement eExec = new CStart(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ON) { CCobolElement eExec = new COnElse(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DELETE) { CCobolElement eExec = new CDelete(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SEARCH) { CCobolElement eExec = new CSearch(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DISPLAY) { CCobolElement eExec = new CDisplay(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.WRITE) { CCobolElement eExec = new CWrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CLOSE) { CCobolElement eExec = new CClose(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.OPEN) { CCobolElement eExec = new COpen(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ACCEPT) { CCobolElement eExec = new CAccept(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.TRANSFORM) { CCobolElement eExec = new CTransform(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SORT) { CCobolElement eExec = new CSort(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RELEASE) { CCobolElement eExec = new CRelease(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RETURN) { CCobolElement eExec = new CReturn(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.READ) { CCobolElement eExec = new CRead(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.REWRITE) { CCobolElement eExec = new CRewrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STOP) { CCobolElement eExec = new CStop(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SUBTRACT) { CCobolElement eExec = new CSubtract(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MULTIPLY) { CCobolElement eExec = new CMultiply(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DIVIDE) { CCobolElement eExec = new CDivide(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STRING) { CCobolElement eExec = new CString(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.UNSTRING) { CCobolElement eExec = new CUnstring(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.INSPECT) { CCobolElement eExec = new CInspect(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.IF) { CCobolElement eIf = new CIfStatement(tokVerb.getLine()) ; AddChild(eIf) ; CFlag f = new CFlag() ; if (!Parse(eIf, f)) { return false ; } if (f.ISSet()) { m_fCheckForNextSentence.Set() ; } return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.PERFORM) { // PERFOM verb has many usages return ParsePerfom(); } else if (tokVerb.GetKeyword()==CCobolKeywordList.EVALUATE) { CCobolElement eVerb = new CEvaluate(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.CALL) { CCobolElement eVerb = new CCall(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.INITIALIZE) { CCobolElement eVerb = new CInitialize(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.COMPUTE) { CCobolElement eVerb = new CCompute(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOBACK) { CCobolElement eVerb = new CGoBack(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.NEXT) { CCobolElement eVerb = new CNextSentence(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb, m_fCheckForNextSentence) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CONTINUE) { CCobolElement eVerb = new CContinue(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ADD) { CCobolElement eVerb = new CAdd(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOTO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.SET) { CCobolElement eVerb = new CSet(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ELSE || tokVerb.GetKeyword()==CCobolKeywordList.END_IF || tokVerb.GetKeyword()==CCobolKeywordList.NOT || tokVerb.GetKeyword()==CCobolKeywordList.END_EVALUATE || tokVerb.GetKeyword()==CCobolKeywordList.END_RETURN || tokVerb.GetKeyword()==CCobolKeywordList.END_DIVIDE || tokVerb.GetKeyword()==CCobolKeywordList.END_STRING || tokVerb.GetKeyword()==CCobolKeywordList.END_WRITE || tokVerb.GetKeyword()==CCobolKeywordList.END_READ || tokVerb.GetKeyword()==CCobolKeywordList.END_UNSTRING || tokVerb.GetKeyword()==CCobolKeywordList.WHEN || tokVerb.GetType()==CTokenType.END_OF_BLOCK || tokVerb.GetKeyword()==CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword()==CCobolKeywordList.END_SEARCH || tokVerb.GetKeyword()==CCobolKeywordList.END_COMPUTE || tokVerb.GetKeyword()==CCobolKeywordList.END_CALL) { // this keyword is the end of bloc //m_Logger.info("INFO Line " +getLine()+ " : " + "Keyword is end-of-bloc : '" + tokVerb.GetValue() + "'") ; return true ; } else { Transcoder.logWarn(tokVerb.getLine(), "Keyword not parsed : '" + tokVerb.GetValue() + "'") ; CBaseToken tokDrop = GetNext(); while (!tokDrop.m_bIsNewLine) { Transcoder.logWarn(tokDrop.getLine(), "Keyword not parsed : '" + tokDrop.GetValue() + "'") ; tokDrop = GetNext(); } return true; } } /** * @return */ protected abstract boolean isTopLevelBloc() ; protected boolean ParsePerfom() { CBaseToken tokId = GetNext() ; CIdentifier identifier = null ; if (tokId.GetType() == CTokenType.IDENTIFIER) { identifier = ReadIdentifier(); } CIdentifier identifierThru = null ; CBaseToken tokKW = GetCurrentToken() ; if (tokKW.GetKeyword() == CCobolKeywordList.THRU) { CBaseToken tok = GetNext() ; identifierThru = ReadIdentifier(); tokKW = GetCurrentToken(); } // PERFORM usage depends on following keyword boolean bTestBefore = true ; // default value if (tokKW.GetKeyword() == CCobolKeywordList.WITH) { tokKW =GetNext(); } if (tokKW.GetKeyword() == CCobolKeywordList.TEST) { tokKW =GetNext(); if (tokKW.GetKeyword() == CCobolKeywordList.BEFORE) { tokKW = GetNext(); bTestBefore = true ; } else if (tokKW.GetKeyword() == CCobolKeywordList.AFTER) { tokKW = GetNext(); bTestBefore = false ; } else { Transcoder.logError(tokKW.getLine(), "Unexpecting token : " + tokKW.GetValue()); return false ; } } if (tokKW.GetKeyword() == CCobolKeywordList.UNTIL) { CCobolElement ePerform = new CPerformUntil(identifier, identifierThru, tokKW.getLine(), bTestBefore); AddChild(ePerform); return Parse(ePerform) ; } else if (tokKW.GetKeyword() == CCobolKeywordList.VARYING) { CCobolElement ePerform = new CPerformVarying(identifier, identifierThru, tokKW.getLine(), bTestBefore); AddChild(ePerform); return Parse(ePerform) ; } else if (tokKW.GetKeyword() == CCobolKeywordList.TIMES) { GetNext(); CTerminal term = new CIdentifierTerminal(identifier) ; CCobolElement ePerform = new CPerform(term, tokKW.getLine()); identifier = null; AddChild(ePerform); return Parse(ePerform) ; } else if (tokKW.GetType() == CTokenType.NUMBER) { CTerminal term = ReadTerminal(); CBaseToken tok = GetCurrentToken() ; if (tok.GetKeyword() == CCobolKeywordList.TIMES) { GetNext() ; CCobolElement eVerb = new CPerform(identifier, identifierThru, term, tokKW.getLine()); AddChild(eVerb) ; return Parse(eVerb) ; } else { Transcoder.logError(tokKW.getLine(), "Unexpecting situation in PERFORM") ; return false ; } } else if (identifier != null) { CCobolElement eVerb = new CPerform(identifier, identifierThru, tokId.getLine()) ; AddChild(eVerb) ; return Parse(eVerb) ; } else { Transcoder.logError(tokKW.getLine(), "Unexpecting situation in PERFORM") ; return false ; } } /* (non-Javadoc) * @see parser.CBaseElement#DoCustomSemanticAnalysis(semantic.CBaseSemanticEntity, semantic.CBaseSemanticEntityFactory) */ protected CBaseLanguageEntity DoCustomSemanticAnalysis(CBaseLanguageEntity parent, CBaseEntityFactory factory) { CEntityBloc eBloc = factory.NewEntityBloc(getLine()) ; eBloc.SetEndLine(m_nEndLine) ; eBloc.SetParent(parent); if (m_nRewriteLine != 0) { CGlobalEntityCounter.GetInstance().RegisterProgramToRewrite(parent.GetProgramName(), m_nRewriteLine, "NEXT SENTENCE") ; } // if (parent != null) // { // parent.AddChild(eBloc); // } return eBloc; } // public boolean Parse(CTokenList lstTokens) // { // return Parse(lstTokens, this); // } // protected boolean Parse(CLanguageElement e, CFlag f) // { // return e.Parse(m_lstTokens, m_con, f) ; // } protected CFlag m_fCheckForNextSentence = new CFlag(); protected int m_nEndLine = 0 ; public void SetEndLine(int n) { m_nEndLine = n ; } }
true
true
protected boolean ParseVerb() { CBaseToken tokVerb = GetCurrentToken() ; if (m_fCheckForNextSentence.ISSet()) { if (tokVerb.GetKeyword() == CCobolKeywordList.END_IF || tokVerb.GetKeyword() == CCobolKeywordList.ELSE || tokVerb.GetKeyword() == CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword() == CCobolKeywordList.END_EVALUATE || tokVerb.GetType() == CTokenType.DOT) { return true ; } else if (!isTopLevelBloc()) { Transcoder.logError(tokVerb.getLine(), "Unrecommanded usage of NEXT SENTENCE"); m_nRewriteLine = tokVerb.getLine() ; } } if (tokVerb.GetKeyword()==CCobolKeywordList.EXEC) { CBaseToken tokType = GetNext() ; CCobolElement eExec = null ; if (tokType.GetKeyword() == CCobolKeywordList.SQL) { eExec = new CExecSQL(tokVerb.getLine()) ; } else if (tokType.GetKeyword() == CCobolKeywordList.CICS) { GetNext(); eExec = GetCICSVerb(); if (eExec == null) { return true ; // ignore EXEC CICS that are not parsed } } else { eExec = new CExecStatement(tokVerb.getLine()) ; } AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MOVE) { CCobolElement eExec = new CMove(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EXIT) { CCobolElement eExec = new CExit(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EJECT) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SKIP3) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.START) { CCobolElement eExec = new CStart(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ON) { CCobolElement eExec = new COnElse(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DELETE) { CCobolElement eExec = new CDelete(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SEARCH) { CCobolElement eExec = new CSearch(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DISPLAY) { CCobolElement eExec = new CDisplay(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.WRITE) { CCobolElement eExec = new CWrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CLOSE) { CCobolElement eExec = new CClose(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.OPEN) { CCobolElement eExec = new COpen(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ACCEPT) { CCobolElement eExec = new CAccept(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.TRANSFORM) { CCobolElement eExec = new CTransform(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SORT) { CCobolElement eExec = new CSort(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RELEASE) { CCobolElement eExec = new CRelease(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RETURN) { CCobolElement eExec = new CReturn(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.READ) { CCobolElement eExec = new CRead(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.REWRITE) { CCobolElement eExec = new CRewrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STOP) { CCobolElement eExec = new CStop(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SUBTRACT) { CCobolElement eExec = new CSubtract(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MULTIPLY) { CCobolElement eExec = new CMultiply(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DIVIDE) { CCobolElement eExec = new CDivide(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STRING) { CCobolElement eExec = new CString(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.UNSTRING) { CCobolElement eExec = new CUnstring(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.INSPECT) { CCobolElement eExec = new CInspect(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.IF) { CCobolElement eIf = new CIfStatement(tokVerb.getLine()) ; AddChild(eIf) ; CFlag f = new CFlag() ; if (!Parse(eIf, f)) { return false ; } if (f.ISSet()) { m_fCheckForNextSentence.Set() ; } return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.PERFORM) { // PERFOM verb has many usages return ParsePerfom(); } else if (tokVerb.GetKeyword()==CCobolKeywordList.EVALUATE) { CCobolElement eVerb = new CEvaluate(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.CALL) { CCobolElement eVerb = new CCall(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.INITIALIZE) { CCobolElement eVerb = new CInitialize(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.COMPUTE) { CCobolElement eVerb = new CCompute(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOBACK) { CCobolElement eVerb = new CGoBack(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.NEXT) { CCobolElement eVerb = new CNextSentence(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb, m_fCheckForNextSentence) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CONTINUE) { CCobolElement eVerb = new CContinue(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ADD) { CCobolElement eVerb = new CAdd(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOTO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.SET) { CCobolElement eVerb = new CSet(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ELSE || tokVerb.GetKeyword()==CCobolKeywordList.END_IF || tokVerb.GetKeyword()==CCobolKeywordList.NOT || tokVerb.GetKeyword()==CCobolKeywordList.END_EVALUATE || tokVerb.GetKeyword()==CCobolKeywordList.END_RETURN || tokVerb.GetKeyword()==CCobolKeywordList.END_DIVIDE || tokVerb.GetKeyword()==CCobolKeywordList.END_STRING || tokVerb.GetKeyword()==CCobolKeywordList.END_WRITE || tokVerb.GetKeyword()==CCobolKeywordList.END_READ || tokVerb.GetKeyword()==CCobolKeywordList.END_UNSTRING || tokVerb.GetKeyword()==CCobolKeywordList.WHEN || tokVerb.GetType()==CTokenType.END_OF_BLOCK || tokVerb.GetKeyword()==CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword()==CCobolKeywordList.END_SEARCH || tokVerb.GetKeyword()==CCobolKeywordList.END_COMPUTE || tokVerb.GetKeyword()==CCobolKeywordList.END_CALL) { // this keyword is the end of bloc //m_Logger.info("INFO Line " +getLine()+ " : " + "Keyword is end-of-bloc : '" + tokVerb.GetValue() + "'") ; return true ; } else { Transcoder.logWarn(tokVerb.getLine(), "Keyword not parsed : '" + tokVerb.GetValue() + "'") ; CBaseToken tokDrop = GetNext(); while (!tokDrop.m_bIsNewLine) { Transcoder.logWarn(tokDrop.getLine(), "Keyword not parsed : '" + tokDrop.GetValue() + "'") ; tokDrop = GetNext(); } return true; } }
protected boolean ParseVerb() { CBaseToken tokVerb = GetCurrentToken() ; if (m_fCheckForNextSentence.ISSet()) { if (tokVerb.GetKeyword() == CCobolKeywordList.END_IF || tokVerb.GetKeyword() == CCobolKeywordList.ELSE || tokVerb.GetKeyword() == CCobolKeywordList.WHEN || tokVerb.GetKeyword() == CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword() == CCobolKeywordList.END_EVALUATE || tokVerb.GetType() == CTokenType.DOT) { return true ; } else if (!isTopLevelBloc()) { Transcoder.logError(tokVerb.getLine(), "Unrecommanded usage of NEXT SENTENCE"); m_nRewriteLine = tokVerb.getLine() ; } } if (tokVerb.GetKeyword()==CCobolKeywordList.EXEC) { CBaseToken tokType = GetNext() ; CCobolElement eExec = null ; if (tokType.GetKeyword() == CCobolKeywordList.SQL) { eExec = new CExecSQL(tokVerb.getLine()) ; } else if (tokType.GetKeyword() == CCobolKeywordList.CICS) { GetNext(); eExec = GetCICSVerb(); if (eExec == null) { return true ; // ignore EXEC CICS that are not parsed } } else { eExec = new CExecStatement(tokVerb.getLine()) ; } AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MOVE) { CCobolElement eExec = new CMove(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EXIT) { CCobolElement eExec = new CExit(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.EJECT) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SKIP3) { GetNext() ; return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.START) { CCobolElement eExec = new CStart(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ON) { CCobolElement eExec = new COnElse(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DELETE) { CCobolElement eExec = new CDelete(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SEARCH) { CCobolElement eExec = new CSearch(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DISPLAY) { CCobolElement eExec = new CDisplay(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.WRITE) { CCobolElement eExec = new CWrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CLOSE) { CCobolElement eExec = new CClose(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.OPEN) { CCobolElement eExec = new COpen(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.ACCEPT) { CCobolElement eExec = new CAccept(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.TRANSFORM) { CCobolElement eExec = new CTransform(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SORT) { CCobolElement eExec = new CSort(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RELEASE) { CCobolElement eExec = new CRelease(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.RETURN) { CCobolElement eExec = new CReturn(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.READ) { CCobolElement eExec = new CRead(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.REWRITE) { CCobolElement eExec = new CRewrite(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STOP) { CCobolElement eExec = new CStop(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.SUBTRACT) { CCobolElement eExec = new CSubtract(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.MULTIPLY) { CCobolElement eExec = new CMultiply(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.DIVIDE) { CCobolElement eExec = new CDivide(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.STRING) { CCobolElement eExec = new CString(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.UNSTRING) { CCobolElement eExec = new CUnstring(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.INSPECT) { CCobolElement eExec = new CInspect(tokVerb.getLine()) ; AddChild(eExec) ; return Parse(eExec) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.IF) { CCobolElement eIf = new CIfStatement(tokVerb.getLine()) ; AddChild(eIf) ; CFlag f = new CFlag() ; if (!Parse(eIf, f)) { return false ; } if (f.ISSet()) { m_fCheckForNextSentence.Set() ; } return true ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.PERFORM) { // PERFOM verb has many usages return ParsePerfom(); } else if (tokVerb.GetKeyword()==CCobolKeywordList.EVALUATE) { CCobolElement eVerb = new CEvaluate(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.CALL) { CCobolElement eVerb = new CCall(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.INITIALIZE) { CCobolElement eVerb = new CInitialize(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.COMPUTE) { CCobolElement eVerb = new CCompute(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOBACK) { CCobolElement eVerb = new CGoBack(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.NEXT) { CCobolElement eVerb = new CNextSentence(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb, m_fCheckForNextSentence) ; } else if (tokVerb.GetKeyword()==CCobolKeywordList.CONTINUE) { CCobolElement eVerb = new CContinue(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ADD) { CCobolElement eVerb = new CAdd(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GOTO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.SET) { CCobolElement eVerb = new CSet(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.GO) { CCobolElement eVerb = new CGoto(tokVerb.getLine()) ; AddChild(eVerb) ; return Parse(eVerb); } else if (tokVerb.GetKeyword()==CCobolKeywordList.ELSE || tokVerb.GetKeyword()==CCobolKeywordList.END_IF || tokVerb.GetKeyword()==CCobolKeywordList.NOT || tokVerb.GetKeyword()==CCobolKeywordList.END_EVALUATE || tokVerb.GetKeyword()==CCobolKeywordList.END_RETURN || tokVerb.GetKeyword()==CCobolKeywordList.END_DIVIDE || tokVerb.GetKeyword()==CCobolKeywordList.END_STRING || tokVerb.GetKeyword()==CCobolKeywordList.END_WRITE || tokVerb.GetKeyword()==CCobolKeywordList.END_READ || tokVerb.GetKeyword()==CCobolKeywordList.END_UNSTRING || tokVerb.GetKeyword()==CCobolKeywordList.WHEN || tokVerb.GetType()==CTokenType.END_OF_BLOCK || tokVerb.GetKeyword()==CCobolKeywordList.END_PERFORM || tokVerb.GetKeyword()==CCobolKeywordList.END_SEARCH || tokVerb.GetKeyword()==CCobolKeywordList.END_COMPUTE || tokVerb.GetKeyword()==CCobolKeywordList.END_CALL) { // this keyword is the end of bloc //m_Logger.info("INFO Line " +getLine()+ " : " + "Keyword is end-of-bloc : '" + tokVerb.GetValue() + "'") ; return true ; } else { Transcoder.logWarn(tokVerb.getLine(), "Keyword not parsed : '" + tokVerb.GetValue() + "'") ; CBaseToken tokDrop = GetNext(); while (!tokDrop.m_bIsNewLine) { Transcoder.logWarn(tokDrop.getLine(), "Keyword not parsed : '" + tokDrop.GetValue() + "'") ; tokDrop = GetNext(); } return true; } }
diff --git a/araqne-logstorage/src/main/java/org/araqne/logstorage/engine/LogStorageEngine.java b/araqne-logstorage/src/main/java/org/araqne/logstorage/engine/LogStorageEngine.java index 0ab547e3..67e0a438 100644 --- a/araqne-logstorage/src/main/java/org/araqne/logstorage/engine/LogStorageEngine.java +++ b/araqne-logstorage/src/main/java/org/araqne/logstorage/engine/LogStorageEngine.java @@ -1,1566 +1,1568 @@ /* * Copyright 2010 NCHOVY * * 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.araqne.logstorage.engine; import java.io.IOException; import java.io.SyncFailedException; import java.nio.BufferUnderflowException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Invalidate; import org.apache.felix.ipojo.annotations.Provides; import org.apache.felix.ipojo.annotations.Requires; import org.apache.felix.ipojo.annotations.Unbind; import org.apache.felix.ipojo.annotations.Validate; import org.araqne.api.PrimitiveConverter; import org.araqne.confdb.Config; import org.araqne.confdb.ConfigDatabase; import org.araqne.confdb.ConfigService; import org.araqne.confdb.Predicates; import org.araqne.log.api.LogParser; import org.araqne.log.api.LogParserBugException; import org.araqne.log.api.LogParserBuilder; import org.araqne.logstorage.CachedRandomSeeker; import org.araqne.logstorage.CallbackSet; import org.araqne.logstorage.DateUtil; import org.araqne.logstorage.LockKey; import org.araqne.logstorage.LockStatus; import org.araqne.logstorage.Log; import org.araqne.logstorage.LogCallback; import org.araqne.logstorage.LogCursor; import org.araqne.logstorage.LogFileService; import org.araqne.logstorage.LogFileServiceEventListener; import org.araqne.logstorage.LogFileServiceRegistry; import org.araqne.logstorage.LogMarshaler; import org.araqne.logstorage.LogRetentionPolicy; import org.araqne.logstorage.LogStorage; import org.araqne.logstorage.LogStorageEventListener; import org.araqne.logstorage.LogStorageStatus; import org.araqne.logstorage.LogTableRegistry; import org.araqne.logstorage.LogTraverseCallback; import org.araqne.logstorage.LogWriterStatus; import org.araqne.logstorage.ReplicaStorageConfig; import org.araqne.logstorage.ReplicationMode; import org.araqne.logstorage.SimpleLogTraverseCallback; import org.araqne.logstorage.TableEventListener; import org.araqne.logstorage.TableLock; import org.araqne.logstorage.TableNotFoundException; import org.araqne.logstorage.TableScanRequest; import org.araqne.logstorage.TableSchema; import org.araqne.logstorage.UnsupportedLogFileTypeException; import org.araqne.logstorage.WriteFallback; import org.araqne.logstorage.WriterPreparationException; import org.araqne.logstorage.file.DatapathUtil; import org.araqne.logstorage.file.LogFileReader; import org.araqne.logstorage.file.LogFileServiceV2; import org.araqne.logstorage.file.LogFileWriter; import org.araqne.logstorage.file.LogRecordCursor; import org.araqne.storage.api.FilePath; import org.araqne.storage.api.StorageManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(name = "logstorage-engine") @Provides public class LogStorageEngine implements LogStorage, TableEventListener, LogFileServiceEventListener { private static final String DEFAULT_LOGFILETYPE = "v2"; private final Logger logger = LoggerFactory.getLogger(LogStorageEngine.class.getName()); private static final int DEFAULT_LOG_CHECK_INTERVAL = 1000; private static final int DEFAULT_MAX_IDLE_TIME = 600000; // 10min private static final int DEFAULT_LOG_FLUSH_INTERVAL = 60000; // 60sec private LogStorageStatus status = LogStorageStatus.Closed; @Requires private LogTableRegistry tableRegistry; @Requires private ConfigService conf; @Requires private LogFileServiceRegistry lfsRegistry; @Requires private StorageManager storageManager; // online writers private ConcurrentMap<OnlineWriterKey, OnlineWriter> onlineWriters; private ConcurrentMap<OnlineWriterKey, AtomicLong> lastIds; private CopyOnWriteArraySet<LogCallback> callbacks; private CallbackSet callbackSet; private CallbackSet fallbackSet; // sweeping and flushing data private WriterSweeper writerSweeper; private Thread writerSweeperThread; private LogFileFetcher fetcher; private FilePath logDir; private ConcurrentHashMap<String, Integer> tableNameCache; // private CopyOnWriteArraySet<LogStorageEventListener> listeners; @Unbind public void unbind(LogFileServiceRegistry reg) { logger.info("log file service registry unbinded"); } public LogStorageEngine() { int checkInterval = getIntParameter(Constants.LogCheckInterval, DEFAULT_LOG_CHECK_INTERVAL); int maxIdleTime = getIntParameter(Constants.LogMaxIdleTime, DEFAULT_MAX_IDLE_TIME); int flushInterval = getIntParameter(Constants.LogFlushInterval, DEFAULT_LOG_FLUSH_INTERVAL); onlineWriters = new ConcurrentHashMap<OnlineWriterKey, OnlineWriter>(); lastIds = new ConcurrentHashMap<OnlineWriterKey, AtomicLong>(); writerSweeper = new WriterSweeper(checkInterval, maxIdleTime, flushInterval); callbacks = new CopyOnWriteArraySet<LogCallback>(); fallbackSet = new CallbackSet(); callbackSet = new CallbackSet(); tableNameCache = new ConcurrentHashMap<String, Integer>(); logDir = storageManager.resolveFilePath(System.getProperty("araqne.data.dir")).newFilePath("araqne-logstorage/log"); logDir = storageManager.resolveFilePath(getStringParameter(Constants.LogStorageDirectory, logDir.getAbsolutePath())); logDir.mkdirs(); DatapathUtil.setLogDir(logDir); // listeners = new CopyOnWriteArraySet<LogStorageEventListener>(); } @Override public FilePath getDirectory() { return logDir; } @Override public void setDirectory(FilePath f) { if (f == null) throw new IllegalArgumentException("storage path should be not null"); if (!f.isDirectory()) throw new IllegalArgumentException("storage path should be directory"); ConfigUtil.set(conf, Constants.LogStorageDirectory, f.getAbsolutePath()); logDir = f; DatapathUtil.setLogDir(logDir); } private String getStringParameter(Constants key, String defaultValue) { String value = ConfigUtil.get(conf, key); if (value != null) return value; return defaultValue; } private int getIntParameter(Constants key, int defaultValue) { String value = ConfigUtil.get(conf, key); if (value != null) return Integer.valueOf(value); return defaultValue; } @Override public LogStorageStatus getStatus() { return status; } @Validate @Override public void start() { FilePath sysArgLogDir = storageManager.resolveFilePath(System.getProperty("araqne.data.dir")).newFilePath( "araqne-logstorage/log"); logDir = storageManager .resolveFilePath(getStringParameter(Constants.LogStorageDirectory, sysArgLogDir.getAbsolutePath())); logDir.mkdirs(); DatapathUtil.setLogDir(logDir); if (status != LogStorageStatus.Closed) throw new IllegalStateException("log archive already started"); status = LogStorageStatus.Starting; fetcher = new LogFileFetcher(tableRegistry, lfsRegistry, storageManager); writerSweeperThread = new Thread(writerSweeper, "LogStorage LogWriter Sweeper"); writerSweeperThread.start(); // load table name cache tableNameCache.clear(); for (TableSchema schema : tableRegistry.getTableSchemas()) { tableNameCache.put(schema.getName(), schema.getId()); } tableRegistry.addListener(this); lfsRegistry.addListener(this); status = LogStorageStatus.Open; } @Invalidate @Override public void stop() { if (status != LogStorageStatus.Open) throw new IllegalStateException("log archive already stopped"); status = LogStorageStatus.Stopping; try { if (tableRegistry != null) { tableRegistry.removeListener(this); } } catch (IllegalStateException e) { if (!e.getMessage().contains("Cannot create the Nullable Object")) throw e; } writerSweeper.doStop = true; synchronized (writerSweeper) { writerSweeper.notifyAll(); } // wait writer sweeper stop try { for (int i = 0; i < 25; i++) { if (writerSweeper.isStopped) break; Thread.sleep(200); } } catch (InterruptedException e) { } // close all writers for (OnlineWriterKey key : onlineWriters.keySet()) { try { OnlineWriter writer = onlineWriters.get(key); if (writer != null) writer.close(); } catch (Throwable t) { logger.warn("exception caught", t); } } onlineWriters.clear(); lastIds.clear(); lfsRegistry.removeListener(this); status = LogStorageStatus.Closed; } @Override public void createTable(TableSchema schema) { tableRegistry.createTable(schema); } @Override public void ensureTable(TableSchema schema) { if (!tableRegistry.exists(schema.getName())) createTable(schema); } @Override public void alterTable(String tableName, TableSchema schema) { tableRegistry.alterTable(tableName, schema); } @Override public void dropTable(String tableName) { TableSchema schema = tableRegistry.getTableSchema(tableName, true); int tableId = schema.getId(); Collection<Date> dates = getLogDates(tableName); // drop retention policy ConfigDatabase db = conf.ensureDatabase("araqne-logstorage"); Config c = db.findOne(LogRetentionPolicy.class, Predicates.field("table_name", tableName)); if (c != null) c.remove(); Lock tLock = tableRegistry.getExclusiveTableLock(tableName, "engine", "dropTable"); try { tLock.lock(); // drop table metadata tableRegistry.dropTable(tableName); // evict online writers for (Date day : dates) { OnlineWriterKey key = new OnlineWriterKey(tableName, day, tableId); OnlineWriter writer = onlineWriters.get(key); if (writer != null) { writer.close(); if (logger.isTraceEnabled()) logger.trace("araqne logstorage: removing logger [{}] according to table drop", key); onlineWriters.remove(key); } } // purge existing files FilePath tableDir = getTableDirectory(schema); if (!tableDir.exists()) return; // delete all .idx, .dat, .key files for (FilePath f : tableDir.listFiles()) { String name = f.getName(); if (f.isFile() && (name.endsWith(".idx") || name.endsWith(".dat") || name.endsWith(".key"))) { ensureDelete(f); } } // delete directory if empty if (tableDir.listFiles().length == 0) { logger.info("araqne logstorage: deleted table {} directory", tableName); tableDir.delete(); } } finally { if (tLock != null) tLock.unlock(); } } @Override public LogRetentionPolicy getRetentionPolicy(String tableName) { ConfigDatabase db = conf.ensureDatabase("araqne-logstorage"); Config c = db.findOne(LogRetentionPolicy.class, Predicates.field("table_name", tableName)); if (c == null) return null; return c.getDocument(LogRetentionPolicy.class); } @Override public void setRetentionPolicy(LogRetentionPolicy policy) { if (policy == null) throw new IllegalArgumentException("policy should not be null"); ConfigDatabase db = conf.ensureDatabase("araqne-logstorage"); Config c = db.findOne(LogRetentionPolicy.class, Predicates.field("table_name", policy.getTableName())); if (c == null) { db.add(policy); } else { c.setDocument(PrimitiveConverter.serialize(policy)); c.update(); } } @Override public FilePath getTableDirectory(String tableName) { if (!tableRegistry.exists(tableName)) throw new IllegalArgumentException("table not exists: " + tableName); TableSchema schema = tableRegistry.getTableSchema(tableName, true); return getTableDirectory(schema); } private FilePath getTableDirectory(TableSchema schema) { FilePath baseDir = logDir; if (schema.getPrimaryStorage().getBasePath() != null) baseDir = storageManager.resolveFilePath(schema.getPrimaryStorage().getBasePath()); if (baseDir == null) return null; return baseDir.newFilePath(Integer.toString(schema.getId())); } @Override public Collection<Date> getLogDates(String tableName) { TableSchema schema = tableRegistry.getTableSchema(tableName, true); String storageType = schema.getPrimaryStorage().getType(); LogFileService lfs = lfsRegistry.getLogFileService(storageType); if (lfs == null) throw new UnsupportedLogFileTypeException(storageType); return lfs.getPartitions(tableName); } @Override public Collection<Date> getLogDates(String tableName, Date from, Date to) { List<Date> l = new ArrayList<Date>(); for (Date d : getLogDates(tableName)) { if (from != null && d.before(from)) continue; if (to != null && d.after(to)) continue; l.add(d); } Collections.sort(l, Collections.reverseOrder()); return l; } @Override public boolean tryWrite(Log log, long waitFor, TimeUnit tu) throws InterruptedException { // inlined verify() for fast-path performance if (status != LogStorageStatus.Open) throw new IllegalStateException("archive not opened"); // write data String tableName = log.getTableName(); int tryCnt = 0; int tryCntLimit = 2; for (; tryCnt < tryCntLimit; tryCnt++) { TableLock tl = tableRegistry.getSharedTableLock(tableName); BackOffLock bol = new BackOffLock(tl); try { do { boolean locked = bol.tryLock(); if (locked) { OnlineWriter writer = loadOnlineWriter(tableName, log.getDate()); writer.write(log); break; } else { if (callWriteFallback(Arrays.asList(log), tl)) return true; } } while (!bol.isDone()); if (!bol.hasLocked()) return false; else break; } catch (WriterPreparationException ex) { continue; } catch (TimeoutException ex) { throw new IllegalStateException(ex); } catch (IOException e) { if (e.getMessage().contains("closed")) { logger.info("closed online writer: trying one more time"); continue; } throw new IllegalStateException("cannot write log: " + tableName + ", " + log.getDate()); } finally { bol.unlock(); } } if (tryCnt == tryCntLimit) { throw new IllegalStateException("cannot write [1] logs to table [" + tableName + "]: retry count exceeded"); } if (log.getId() == 0) throw new IllegalStateException("cannot write log: " + tableName + ", " + log.getDate()); // invoke log callbacks List<Log> one = Arrays.asList(log); invokeLogCallbacks(log.getTableName(), one); return true; } private boolean callWriteFallback(List<Log> logs, TableLock tl) { for (WriteFallback fb : fallbackSet.get(WriteFallback.class)) { int handled = fb.onLockFailure(tl, logs); if (handled == logs.size()) return true; } return false; } @Override public boolean tryWrite(List<Log> logs, long waitFor, TimeUnit tu) throws InterruptedException { // inlined verify() for fast-path performance if (status != LogStorageStatus.Open) throw new IllegalStateException("archive not opened"); HashMap<OnlineWriterKey, List<Log>> keyLogs = new HashMap<OnlineWriterKey, List<Log>>(); for (Log log : logs) { Integer tableId = tableNameCache.get(log.getTableName()); if (tableId == null) throw new TableNotFoundException(log.getTableName()); OnlineWriterKey writerKey = new OnlineWriterKey(log.getTableName(), log.getDay(), tableId); List<Log> l = keyLogs.get(writerKey); if (l == null) { l = new ArrayList<Log>(); keyLogs.put(writerKey, l); } l.add(log); } HashMap<OnlineWriterKey, BackOffLock> locks = new HashMap<OnlineWriterKey, BackOffLock>(); try { for (OnlineWriterKey k : keyLogs.keySet()) { TableLock lock = tableRegistry.getSharedTableLock(k.getTableName()); BackOffLock bol = new BackOffLock(lock, waitFor, tu); do { boolean locked = bol.tryLock(); if (locked) { locks.put(k, bol); } else { if (callWriteFallback(keyLogs.get(k), lock)) break; } } while (!bol.isDone()); } // write data for (Entry<OnlineWriterKey, List<Log>> e : keyLogs.entrySet()) { OnlineWriterKey writerKey = e.getKey(); String tableName = writerKey.getTableName(); List<Log> l = e.getValue(); if (!locks.containsKey(writerKey)) continue; int tryCnt = 0; int tryCntLimit = 2; for (; tryCnt < tryCntLimit; tryCnt++) { try { OnlineWriter writer = loadOnlineWriter(writerKey.getTableName(), writerKey.getDay()); writer.write(l); break; } catch (WriterPreparationException ex) { logger.debug("WriterPreparationException", ex); // retry } catch (TimeoutException ex) { throw new IllegalStateException("cannot write [" + l.size() + "] logs to table [" + tableName + "]", ex); } catch (InterruptedException ex) { throw new IllegalStateException("cannot write [" + l.size() + "] logs to table [" + tableName + "]", ex); } catch (IOException ex) { if (ex.getMessage().contains("closed")) { logger.info("araqne logstorage: closed online writer, trying one more time"); continue; } throw new IllegalStateException("cannot write [" + l.size() + "] logs to table [" + tableName + "]", ex); } } if (tryCnt == tryCntLimit) { logger.info("tryCnt == tryCntLimit"); throw new IllegalStateException("cannot write [" + l.size() + "] logs to table [" + tableName + "]: retry count exceeded"); } invokeLogCallbacks(writerKey.getTableName(), l); } } catch (RuntimeException e) { logger.error("unexpected exception", e); throw e; } finally { for (BackOffLock l : locks.values()) { l.unlock(); } } return true; } private void invokeLogCallbacks(String tableName, List<Log> l) { // invoke log callbacks for (LogCallback callback : callbacks) { try { callback.onLogBatch(tableName, l); } catch (Exception ex) { logger.warn("araqne logstorage: log callback should not throw any exception", ex); } } } @Override public Collection<Log> getLogs(String tableName, Date from, Date to, int limit) { return getLogs(tableName, from, to, 0, limit); } @Override public Collection<Log> getLogs(String tableName, Date from, Date to, long offset, int limit) { final List<Log> ret = new ArrayList<Log>(limit); try { LogTraverseCallback.Sink listSink = new LogTraverseCallback.Sink(offset, limit) { @Override protected void processLogs(List<Log> logs) { ret.addAll(logs); } }; search(new TableScanRequest(tableName, from, to, null, new SimpleLogTraverseCallback(listSink))); } catch (InterruptedException e) { throw new RuntimeException("interrupted"); } return ret; } @Override public Date getPurgeBaseline(String tableName) { LogRetentionPolicy p = getRetentionPolicy(tableName); if (p == null || p.getRetentionDays() == 0) return null; Collection<Date> logDays = getLogDates(tableName); Date lastLogDay = getMaxDay(logDays.iterator()); if (lastLogDay == null) return null; Date now = new Date(); if (lastLogDay.after(now)) lastLogDay = now; return getBaseline(lastLogDay, p.getRetentionDays()); } private Date getBaseline(Date lastDay, int days) { Calendar c = Calendar.getInstance(); c.setTime(lastDay); c.add(Calendar.DAY_OF_MONTH, -days); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } private Date getMaxDay(Iterator<Date> days) { Date max = null; while (days.hasNext()) { Date day = days.next(); if (max == null) max = day; else if (max != null && day.after(max)) max = day; } return max; } @Override public void purge(String tableName, Date day) { purge(tableName, day, false); } @Override public void purge(String tableName, Date day, boolean skipArgCheck) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); TableSchema schema = tableRegistry.getTableSchema(tableName, true); FilePath dir = getTableDirectory(tableName); if (!skipArgCheck) { ReplicaStorageConfig config = ReplicaStorageConfig.parseTableSchema(schema); if (config != null && config.mode() != ReplicationMode.ACTIVE) throw new IllegalArgumentException("specified table has replica storage config and cannot purge non-active table"); } // evict online buffer and close OnlineWriter writer = onlineWriters.remove(new OnlineWriterKey(tableName, day, schema.getId())); if (writer != null) writer.close(); String fileName = dateFormat.format(day); FilePath idxFile = dir.newFilePath(fileName + ".idx"); FilePath datFile = dir.newFilePath(fileName + ".dat"); for (LogStorageEventListener listener : callbackSet.get(LogStorageEventListener.class)) { try { listener.onPurge(tableName, day); } catch (Throwable t) { logger.error("araqne logstorage: storage event listener should not throw any exception", t); } } logger.debug("araqne logstorage: try to purge log data of table [{}], day [{}]", tableName, fileName); ensureDelete(idxFile); ensureDelete(datFile); } @SuppressWarnings("unchecked") public static <T> CopyOnWriteArraySet<T> getCallbacks(ConcurrentMap<Class<?>, CopyOnWriteArraySet<?>> callbackSets, Class<T> class1) { CopyOnWriteArraySet<?> result = callbackSets.get(class1); if (result == null) { result = new CopyOnWriteArraySet<T>(); CopyOnWriteArraySet<?> concensus = callbackSets.putIfAbsent(class1, result); if (concensus != null) result = concensus; } return (CopyOnWriteArraySet<T>) result; } @Override public void purge(String tableName, Date fromDay, Date toDay) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String from = "unbound"; if (fromDay != null) from = dateFormat.format(fromDay); String to = "unbound"; if (toDay != null) to = dateFormat.format(toDay); logger.debug("araqne logstorage: try to purge log data of table [{}], range [{}~{}]", new Object[] { tableName, from, to }); List<Date> purgeDays = new ArrayList<Date>(); for (Date day : getLogDates(tableName)) { // check range if (fromDay != null && day.before(fromDay)) continue; if (toDay != null && day.after(toDay)) continue; purgeDays.add(day); } for (Date day : purgeDays) { purge(tableName, day); } } private boolean ensureDelete(FilePath f) { final int MAX_TIMEOUT = 30000; long begin = System.currentTimeMillis(); while (true) { if (!f.exists() || f.delete()) { if (logger.isTraceEnabled()) logger.trace("araqne logstorage: deleted log file [{}]", f.getAbsolutePath()); return true; } if (System.currentTimeMillis() - begin > MAX_TIMEOUT) { logger.error("araqne logstorage: delete timeout, cannot delete log file [{}]", f.getAbsolutePath()); return false; } } } @Override public CachedRandomSeeker openCachedRandomSeeker() { verify(); for (OnlineWriter writer : onlineWriters.values()) { try { writer.sync(); } catch (IOException e) { logger.error("araqne logstorage: cannot sync online writer", e); } } return new CachedRandomSeekerImpl(tableRegistry, fetcher, onlineWriters, logDir); } @Override public LogCursor openCursor(String tableName, Date day, boolean ascending) throws IOException { verify(); Integer tableId = tableNameCache.get(tableName); if (tableId == null) throw new TableNotFoundException(tableName); OnlineWriter onlineWriter = onlineWriters.get(new OnlineWriterKey(tableName, day, tableId)); ArrayList<Log> buffer = null; if (onlineWriter != null) buffer = (ArrayList<Log>) onlineWriter.getBuffer(); TableSchema schema = tableRegistry.getTableSchema(tableName, true); String basePathString = schema.getPrimaryStorage().getBasePath(); FilePath basePath = logDir; if (basePathString != null) basePath = storageManager.resolveFilePath(basePathString); FilePath indexPath = DatapathUtil.getIndexFile(tableId, day, basePath); FilePath dataPath = DatapathUtil.getDataFile(tableId, day, basePath); FilePath keyPath = DatapathUtil.getKeyFile(tableId, day, basePath); String logFileType = schema.getPrimaryStorage().getType(); LogFileServiceV2.Option options = new LogFileServiceV2.Option(schema.getPrimaryStorage(), schema.getMetadata(), tableName, basePath, indexPath, dataPath, keyPath); options.put("day", day); syncOnlineWriter(onlineWriter); LogFileReader reader = lfsRegistry.newReader(tableName, logFileType, options); return new LogCursorImpl(tableName, day, buffer, reader, ascending); } private OnlineWriter loadOnlineWriter(String tableName, Date date) throws TimeoutException, InterruptedException, WriterPreparationException { // check table existence Integer tableId = tableNameCache.get(tableName); if (tableId == null) throw new TableNotFoundException(tableName); Date day = DateUtil.getDay(date); OnlineWriterKey key = new OnlineWriterKey(tableName, day, tableId); OnlineWriter online = onlineWriters.get(key); if (online != null && !online.isClosed()) { if (online.isReady()) { return online; } else { online.awaitWriterPreparation(); return online; } } try { OnlineWriter oldWriter = onlineWriters.get(key); // @formatter:off /* * statuses of OnlineWriter * * writer closing writer.closed 1) null false false 2) !null false * false 3) !null true false 4) !null true true */ // @formatter:on if (oldWriter != null) { if (oldWriter.isCloseCompleted()) { while (onlineWriters.get(key) == oldWriter) Thread.yield(); return loadNewOnlineWriter(key, getLogFileType(tableName)); } else if (oldWriter.isClosed()) { synchronized (oldWriter) { while (!oldWriter.isCloseCompleted()) { oldWriter.wait(1000); } while (onlineWriters.get(key) == oldWriter) Thread.yield(); return loadNewOnlineWriter(key, getLogFileType(tableName)); } } else { return loadNewOnlineWriter(key, getLogFileType(tableName)); } } else { return loadNewOnlineWriter(key, getLogFileType(tableName)); } } catch (UnsupportedLogFileTypeException e) { throw new IllegalStateException("cannot open writer: " + tableName + ", date=" + day, e); } catch (IOException e) { throw new IllegalStateException("cannot open writer: " + tableName + ", date=" + day, e); } } private String getLogFileType(String tableName) { TableSchema schema = tableRegistry.getTableSchema(tableName, true); return schema.getPrimaryStorage().getType(); } private OnlineWriter loadNewOnlineWriter(OnlineWriterKey key, String logFileType) throws IOException, InterruptedException, TimeoutException, WriterPreparationException { OnlineWriter newWriter = newOnlineWriter(key.getTableName(), key.getDay(), logFileType); OnlineWriter consensus = onlineWriters.putIfAbsent(key, newWriter); if (consensus == null) { try { AtomicLong lastKey = getLastKey(key); newWriter.prepareWriter(storageManager, callbackSet, logDir, lastKey); return newWriter; } catch (IOException e) { logger.error("loadNewOnlineWriter failed: " + key, e); onlineWriters.remove(key, newWriter); throw e; } catch (RuntimeException e) { logger.error("loadNewOnlineWriter failed: " + key, e); onlineWriters.remove(key, newWriter); throw e; } } else { try { consensus.awaitWriterPreparation(); if (!consensus.isReady()) throw new IllegalStateException("log writer preparation failed - " + key); else { return consensus; } } finally { if (consensus != newWriter) newWriter.close(); } } } private OnlineWriter newOnlineWriter(String tableName, Date day, String logFileType) throws InterruptedException { if (logFileType == null) logFileType = DEFAULT_LOGFILETYPE; LogFileService lfs = lfsRegistry.getLogFileService(logFileType); if (lfs == null) { throw new UnsupportedLogFileTypeException(logFileType); } TableSchema schema = tableRegistry.getTableSchema(tableName, true); Lock tableLock = tableRegistry.getSharedTableLock(tableName); try { tableLock.lock(); return new OnlineWriter(lfs, schema, day); } finally { tableLock.unlock(); } } private AtomicLong getLastKey(OnlineWriterKey key) { if (!lastIds.containsKey(key)) lastIds.putIfAbsent(key, new AtomicLong(-1)); return lastIds.get(key); } @Override public void reload() { int flushInterval = getIntParameter(Constants.LogFlushInterval, DEFAULT_LOG_FLUSH_INTERVAL); int maxIdleTime = getIntParameter(Constants.LogMaxIdleTime, DEFAULT_MAX_IDLE_TIME); writerSweeper.setFlushInterval(flushInterval); writerSweeper.setMaxIdleTime(maxIdleTime); } @Override public void flush() { synchronized (writerSweeper) { writerSweeper.setFlushAll(true); writerSweeper.notifyAll(); } } @Override public void addLogListener(LogCallback callback) { callbacks.add(callback); } @Override public void removeLogListener(LogCallback callback) { callbacks.remove(callback); } private void verify() { if (status != LogStorageStatus.Open) throw new IllegalStateException("archive not opened"); } @Override public List<LogWriterStatus> getWriterStatuses() { List<LogWriterStatus> writers = new ArrayList<LogWriterStatus>(onlineWriters.size()); for (OnlineWriterKey key : onlineWriters.keySet()) { OnlineWriter writer = onlineWriters.get(key); LogWriterStatus s = new LogWriterStatus(); s.setTableName(key.getTableName()); s.setDay(key.getDay()); s.setLastWrite(writer.getLastAccess()); s.setBufferSize(writer.getBuffer().size()); writers.add(s); } return writers; } /** * @since 2.7.0 */ @Override public LogFileWriter getOnlineWriter(String tableName, Date day) { TableSchema schema = tableRegistry.getTableSchema(tableName, true); int tableId = schema.getId(); OnlineWriter online = onlineWriters.get(new OnlineWriterKey(tableName, day, tableId)); if (online == null) return null; return online.getWriter(); } @Override public void addEventListener(LogStorageEventListener listener) { callbackSet.get(LogStorageEventListener.class).add(listener); } @Override public void removeEventListener(LogStorageEventListener listener) { callbackSet.get(LogStorageEventListener.class).remove(listener); } @Override public <T> void addEventListener(Class<T> clazz, T listener) { callbackSet.get(clazz).add(listener); } @Override public <T> void removeEventListener(Class<T> clazz, T listener) { callbackSet.get(clazz).remove(listener); } @Override public <T> void addFallback(Class<T> clazz, T fallback) { fallbackSet.get(clazz).add(fallback); } @Override public <T> void removeFallback(Class<T> clazz, T fallback) { fallbackSet.get(clazz).remove(fallback); } private class WriterSweeper implements Runnable { private final Logger logger = LoggerFactory.getLogger(WriterSweeper.class.getName()); private volatile int checkInterval; private volatile int maxIdleTime; private volatile int flushInterval; private volatile boolean doStop = false; private volatile boolean isStopped = true; private volatile boolean flushAll = false; public WriterSweeper(int checkInterval, int maxIdleTime, int flushInterval) { this.checkInterval = checkInterval; this.maxIdleTime = maxIdleTime; this.flushInterval = flushInterval; } public void setFlushInterval(int flushInterval) { this.flushInterval = flushInterval; } public void setMaxIdleTime(int maxIdleTime) { this.maxIdleTime = maxIdleTime; } public void setFlushAll(boolean flushAll) { this.flushAll = flushAll; } @Override public void run() { try { isStopped = false; while (true) { try { if (doStop) break; synchronized (this) { this.wait(checkInterval); } sweep(); } catch (InterruptedException e) { logger.trace("araqne logstorage: sweeper interrupted"); } catch (Exception e) { logger.error("araqne logstorage: sweeper error", e); } } } finally { doStop = false; isStopped = true; } logger.info("araqne logstorage: writer sweeper stopped"); } private void sweep() { List<OnlineWriterKey> evicts = new ArrayList<OnlineWriterKey>(); long now = new Date().getTime(); try { // periodic log flush boolean flushAll = this.flushAll; this.flushAll = false; for (OnlineWriterKey key : onlineWriters.keySet()) { OnlineWriter writer = onlineWriters.get(key); if (writer == null || writer.isClosed() || !writer.isReady()) continue; boolean doFlush = writer.isCloseReserved() || ((now - writer.getLastFlush().getTime()) > flushInterval); doFlush = flushAll ? true : doFlush; if (doFlush) { try { if (logger.isTraceEnabled()) logger.trace("araqne logstorage: flushing writer [{}]", key); writer.flush(); } catch (IOException e) { logger.error("araqne logstorage: log flush failed", e); } } // close file if writer is in idle state int interval = (int) (now - writer.getLastAccess().getTime()); if (interval > maxIdleTime || writer.isCloseReserved()) evicts.add(key); } } catch (ConcurrentModificationException e) { } closeAndKickout(evicts); } private void closeAndKickout(List<OnlineWriterKey> evicts) { for (OnlineWriterKey key : evicts) { OnlineWriter evictee = onlineWriters.get(key); if (evictee != null) { evictee.close(); if (logger.isTraceEnabled()) logger.trace("araqne logstorage: evict logger [{}]", key); onlineWriters.remove(key); } } } } private static class LogCursorImpl implements LogCursor { private String tableName; private Date day; private ArrayList<Log> buffer; private LogFileReader reader; private LogRecordCursor cursor; private boolean ascending; private Log prefetch; private int bufferNext; private int bufferTotal; public LogCursorImpl(String tableName, Date day, ArrayList<Log> buffer, LogFileReader reader, boolean ascending) throws IOException { this.tableName = tableName; this.day = day; this.reader = reader; this.cursor = reader.getCursor(ascending); this.ascending = ascending; if (buffer != null) { this.buffer = buffer; this.bufferTotal = buffer.size(); this.bufferNext = ascending ? 0 : bufferTotal - 1; } } @Override public boolean hasNext() { if (prefetch != null) return true; if (ascending) { if (cursor.hasNext()) { prefetch = LogMarshaler.convert(tableName, cursor.next()); return true; } if (bufferNext < bufferTotal) { prefetch = buffer.get(bufferNext++); return true; } return false; } else { if (bufferNext < 0) { prefetch = buffer.get(bufferNext--); return true; } if (cursor.hasNext()) { prefetch = LogMarshaler.convert(tableName, cursor.next()); return true; } return false; } } @Override public Log next() { if (!hasNext()) throw new NoSuchElementException("end of log cursor"); Log log = prefetch; prefetch = null; return log; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public void close() { reader.close(); } @Override public String toString() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); return "log cursor for table " + tableName + ", day " + dateFormat.format(day); } } @Override public void onCreate(TableSchema schema) { tableNameCache.put(schema.getName(), schema.getId()); } @Override public void onAlter(TableSchema oldSchema, TableSchema newSchema) { } @Override public void onDrop(TableSchema schema) { tableNameCache.remove(schema.getName()); } public void purgeOnlineWriters() { List<OnlineWriterKey> keys = new ArrayList<OnlineWriterKey>(); for (Map.Entry<OnlineWriterKey, OnlineWriter> e : onlineWriters.entrySet()) { e.getValue().close(); keys.add(e.getKey()); } for (OnlineWriterKey key : keys) { onlineWriters.remove(key); } } @Override public void onUnloadingFileService(String engineName) { List<OnlineWriterKey> toRemove = new ArrayList<OnlineWriterKey>(); for (OnlineWriterKey key : onlineWriters.keySet()) { try { OnlineWriter writer = onlineWriters.get(key); if (writer != null && writer.getFileServiceType().equals(engineName)) toRemove.add(key); } catch (Throwable t) { logger.warn("exception caught", t); } } for (OnlineWriterKey key : toRemove) { try { OnlineWriter writer = onlineWriters.get(key); if (writer != null) { writer.close(); onlineWriters.remove(key); } } catch (Throwable t) { logger.warn("exception caught", t); } } } @Override public boolean search(TableScanRequest req) throws InterruptedException { verify(); String tableName = req.getTableName(); Collection<Date> days = getLogDates(tableName); List<Date> filtered = DateUtil.filt(days, req.getFrom(), req.getTo()); logger.trace("araqne logstorage: searching {} tablets of table [{}]", filtered.size(), tableName); if (req.isAsc()) Collections.sort(filtered); for (Date day : filtered) { if (logger.isTraceEnabled()) logger.trace("araqne logstorage: searching table {}, date={}", tableName, DateUtil.getDayText(day)); searchTablet(req, day); if (req.getTraverseCallback().isEof()) break; } return !req.getTraverseCallback().isEof(); } private void syncOnlineWriter(OnlineWriter onlineWriter) { if (onlineWriter != null) { try { onlineWriter.sync(); } catch (SyncFailedException e) { logger.debug("araqne logstorage: sync failed", e); } catch (IOException e) { logger.error("araqne logstorage: cannot sync online writer", e); } } } @Override public boolean searchTablet(TableScanRequest req, Date day) throws InterruptedException { String tableName = req.getTableName(); Date from = req.getFrom(); Date to = req.getTo(); long minId = req.getMinId(); long maxId = req.getMaxId(); LogParserBuilder builder = req.getParserBuilder(); LogTraverseCallback c = req.getTraverseCallback(); TableSchema schema = tableRegistry.getTableSchema(tableName, true); int tableId = schema.getId(); String basePathString = schema.getPrimaryStorage().getBasePath(); FilePath basePath = logDir; if (basePathString != null) basePath = storageManager.resolveFilePath(basePathString); FilePath indexPath = DatapathUtil.getIndexFile(tableId, day, basePath); FilePath dataPath = DatapathUtil.getDataFile(tableId, day, basePath); FilePath keyPath = DatapathUtil.getKeyFile(tableId, day, basePath); LogFileReader reader = null; long onlineMinId = -1; List<Log> logs = null; try { // do NOT use getOnlineWriter() here (it loads empty writer on cache // automatically if writer not found) OnlineWriter onlineWriter = onlineWriters.get(new OnlineWriterKey(tableName, day, tableId)); if (onlineWriter != null) { List<Log> buffer = onlineWriter.getBuffer(); syncOnlineWriter(onlineWriter); if (buffer != null && !buffer.isEmpty()) { LogParser parser = null; if (builder != null) parser = builder.build(); if (logger.isTraceEnabled()) logger.trace("araqne logstorage: {} logs in writer buffer.", buffer.size()); logs = new ArrayList<Log>(buffer.size()); if (req.isAsc()) { for (Log logData : buffer) { if (onlineMinId == -1) onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } else { ListIterator<Log> li = buffer.listIterator(buffer.size()); while (li.hasPrevious()) { Log logData = li.previous(); onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } if (c.isEof()) return false; } } if (logs != null && logger.isDebugEnabled()) logger.debug("#buffer flush bug# logs size: {}", logs.size()); String logFileType = schema.getPrimaryStorage().getType(); LogFileServiceV2.Option options = new LogFileServiceV2.Option(schema.getPrimaryStorage(), schema.getMetadata(), tableName, basePath, indexPath, dataPath, keyPath); options.put("day", day); syncOnlineWriter(onlineWriter); reader = lfsRegistry.newReader(tableName, logFileType, options); long flushedMaxId = (onlineMinId > 0) ? onlineMinId - 1 : maxId; long readerMaxId = maxId != -1 ? Math.min(flushedMaxId, maxId) : flushedMaxId; logger.debug("#buffer flush bug# minId: {}, readerMaxId: {}", minId, readerMaxId); logger.debug("#buffer flush bug# maxId: {}, onlineMinId: {}", maxId, flushedMaxId); - if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { - if (req.isAsc()) { + if (req.isAsc()) { + if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); - if (logs != null) - c.writeLogs(logs); - } else { - if (logs != null) - c.writeLogs(logs); + } + if (logs != null) + c.writeLogs(logs); + } else { + if (logs != null) + c.writeLogs(logs); + if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); } } } catch (InterruptedException e) { throw e; } catch (IllegalStateException e) { c.setFailure(e); Throwable cause = e.getCause(); if (cause instanceof BufferUnderflowException || cause instanceof IOException) c.setFailure(cause); if (e.getMessage().contains("license is locked")) logger.warn("araqne logstorage: search tablet failed. {}", e.getMessage()); else if (logger.isTraceEnabled()) logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (BufferUnderflowException e) { c.setFailure(e); logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (IOException e) { c.setFailure(e); logger.warn("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (Exception e) { c.setFailure(e); logger.error("araqne logstorage: search tablet failed", e); } finally { if (reader != null) reader.close(); } return !c.isEof(); } @Override public StorageManager getStorageManager() { return storageManager; } @Override public boolean lock(LockKey key, String purpose, long timeout, TimeUnit unit) throws InterruptedException { Lock lock = tableRegistry.getExclusiveTableLock(key.tableName, key.owner, purpose); if (lock.tryLock(timeout, unit)) { flush(key.tableName); return true; } else { return false; } } @Override public void unlock(LockKey storageLockKey, String purpose) { Lock lock = tableRegistry.getExclusiveTableLock(storageLockKey.tableName, storageLockKey.owner, purpose); lock.unlock(); } @Override public LockStatus lockStatus(LockKey storageLockKey) { return tableRegistry.getTableLockStatus(storageLockKey.tableName); } @Override public void flush(String tableName) { HashMap<OnlineWriterKey, CountDownLatch> monitors = new HashMap<OnlineWriterKey, CountDownLatch>(); for (OnlineWriterKey key : onlineWriters.keySet()) { if (key.getTableName().equals(tableName)) { OnlineWriter ow = onlineWriters.get(key); CountDownLatch monitor = ow.reserveClose(); monitors.put(key, monitor); } } synchronized (writerSweeper) { writerSweeper.notifyAll(); } for (Map.Entry<OnlineWriterKey, CountDownLatch> e : monitors.entrySet()) { waitForClose(e.getKey(), e.getValue()); } } @SuppressWarnings("serial") private static class SweeperThreadStoppedException extends RuntimeException { } private void waitForClose(OnlineWriterKey key, CountDownLatch monitor) { try { if (writerSweeperThread.isAlive()) { boolean closed = monitor.await(1, TimeUnit.MINUTES); if (!closed) { logger.info("wait for closing Table: {}", key.getTableName()); if (writerSweeperThread.isAlive()) monitor.await(); else throw new SweeperThreadStoppedException(); } } else { throw new SweeperThreadStoppedException(); } } catch (SweeperThreadStoppedException e) { OnlineWriter o = onlineWriters.get(key); if (o != null) o.close(); } catch (InterruptedException e) { logger.warn("wait for closing interrupted: {}", key.getTableName()); OnlineWriter o = onlineWriters.get(key); if (o != null) o.close(); } } @Override public boolean tryWrite(Log log) { try { return tryWrite(log, 0, TimeUnit.SECONDS); } catch (InterruptedException e) { return false; } } @Override public boolean tryWrite(List<Log> logs) { try { return tryWrite(logs, 0, TimeUnit.SECONDS); } catch (InterruptedException e) { return false; } } @Override public void write(Log log) throws InterruptedException { tryWrite(log, Long.MAX_VALUE, TimeUnit.SECONDS); } @Override public void write(List<Log> logs) throws InterruptedException { tryWrite(logs, Long.MAX_VALUE, TimeUnit.SECONDS); } }
false
true
public boolean searchTablet(TableScanRequest req, Date day) throws InterruptedException { String tableName = req.getTableName(); Date from = req.getFrom(); Date to = req.getTo(); long minId = req.getMinId(); long maxId = req.getMaxId(); LogParserBuilder builder = req.getParserBuilder(); LogTraverseCallback c = req.getTraverseCallback(); TableSchema schema = tableRegistry.getTableSchema(tableName, true); int tableId = schema.getId(); String basePathString = schema.getPrimaryStorage().getBasePath(); FilePath basePath = logDir; if (basePathString != null) basePath = storageManager.resolveFilePath(basePathString); FilePath indexPath = DatapathUtil.getIndexFile(tableId, day, basePath); FilePath dataPath = DatapathUtil.getDataFile(tableId, day, basePath); FilePath keyPath = DatapathUtil.getKeyFile(tableId, day, basePath); LogFileReader reader = null; long onlineMinId = -1; List<Log> logs = null; try { // do NOT use getOnlineWriter() here (it loads empty writer on cache // automatically if writer not found) OnlineWriter onlineWriter = onlineWriters.get(new OnlineWriterKey(tableName, day, tableId)); if (onlineWriter != null) { List<Log> buffer = onlineWriter.getBuffer(); syncOnlineWriter(onlineWriter); if (buffer != null && !buffer.isEmpty()) { LogParser parser = null; if (builder != null) parser = builder.build(); if (logger.isTraceEnabled()) logger.trace("araqne logstorage: {} logs in writer buffer.", buffer.size()); logs = new ArrayList<Log>(buffer.size()); if (req.isAsc()) { for (Log logData : buffer) { if (onlineMinId == -1) onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } else { ListIterator<Log> li = buffer.listIterator(buffer.size()); while (li.hasPrevious()) { Log logData = li.previous(); onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } if (c.isEof()) return false; } } if (logs != null && logger.isDebugEnabled()) logger.debug("#buffer flush bug# logs size: {}", logs.size()); String logFileType = schema.getPrimaryStorage().getType(); LogFileServiceV2.Option options = new LogFileServiceV2.Option(schema.getPrimaryStorage(), schema.getMetadata(), tableName, basePath, indexPath, dataPath, keyPath); options.put("day", day); syncOnlineWriter(onlineWriter); reader = lfsRegistry.newReader(tableName, logFileType, options); long flushedMaxId = (onlineMinId > 0) ? onlineMinId - 1 : maxId; long readerMaxId = maxId != -1 ? Math.min(flushedMaxId, maxId) : flushedMaxId; logger.debug("#buffer flush bug# minId: {}, readerMaxId: {}", minId, readerMaxId); logger.debug("#buffer flush bug# maxId: {}, onlineMinId: {}", maxId, flushedMaxId); if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { if (req.isAsc()) { TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); if (logs != null) c.writeLogs(logs); } else { if (logs != null) c.writeLogs(logs); TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); } } } catch (InterruptedException e) { throw e; } catch (IllegalStateException e) { c.setFailure(e); Throwable cause = e.getCause(); if (cause instanceof BufferUnderflowException || cause instanceof IOException) c.setFailure(cause); if (e.getMessage().contains("license is locked")) logger.warn("araqne logstorage: search tablet failed. {}", e.getMessage()); else if (logger.isTraceEnabled()) logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (BufferUnderflowException e) { c.setFailure(e); logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (IOException e) { c.setFailure(e); logger.warn("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (Exception e) { c.setFailure(e); logger.error("araqne logstorage: search tablet failed", e); } finally { if (reader != null) reader.close(); } return !c.isEof(); }
public boolean searchTablet(TableScanRequest req, Date day) throws InterruptedException { String tableName = req.getTableName(); Date from = req.getFrom(); Date to = req.getTo(); long minId = req.getMinId(); long maxId = req.getMaxId(); LogParserBuilder builder = req.getParserBuilder(); LogTraverseCallback c = req.getTraverseCallback(); TableSchema schema = tableRegistry.getTableSchema(tableName, true); int tableId = schema.getId(); String basePathString = schema.getPrimaryStorage().getBasePath(); FilePath basePath = logDir; if (basePathString != null) basePath = storageManager.resolveFilePath(basePathString); FilePath indexPath = DatapathUtil.getIndexFile(tableId, day, basePath); FilePath dataPath = DatapathUtil.getDataFile(tableId, day, basePath); FilePath keyPath = DatapathUtil.getKeyFile(tableId, day, basePath); LogFileReader reader = null; long onlineMinId = -1; List<Log> logs = null; try { // do NOT use getOnlineWriter() here (it loads empty writer on cache // automatically if writer not found) OnlineWriter onlineWriter = onlineWriters.get(new OnlineWriterKey(tableName, day, tableId)); if (onlineWriter != null) { List<Log> buffer = onlineWriter.getBuffer(); syncOnlineWriter(onlineWriter); if (buffer != null && !buffer.isEmpty()) { LogParser parser = null; if (builder != null) parser = builder.build(); if (logger.isTraceEnabled()) logger.trace("araqne logstorage: {} logs in writer buffer.", buffer.size()); logs = new ArrayList<Log>(buffer.size()); if (req.isAsc()) { for (Log logData : buffer) { if (onlineMinId == -1) onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } else { ListIterator<Log> li = buffer.listIterator(buffer.size()); while (li.hasPrevious()) { Log logData = li.previous(); onlineMinId = logData.getId(); if ((from == null || !logData.getDate().before(from)) && (to == null || logData.getDate().before(to)) && (minId < 0 || minId <= logData.getId()) && (maxId < 0 || maxId >= logData.getId())) { List<Log> result = null; try { result = LogFileReader.parse(tableName, parser, logData); } catch (LogParserBugException e) { result = Arrays.asList(new Log[] { new Log(e.tableName, e.date, e.id, e.logMap) }); c.setFailure(e); } logs.addAll(result); } } } if (c.isEof()) return false; } } if (logs != null && logger.isDebugEnabled()) logger.debug("#buffer flush bug# logs size: {}", logs.size()); String logFileType = schema.getPrimaryStorage().getType(); LogFileServiceV2.Option options = new LogFileServiceV2.Option(schema.getPrimaryStorage(), schema.getMetadata(), tableName, basePath, indexPath, dataPath, keyPath); options.put("day", day); syncOnlineWriter(onlineWriter); reader = lfsRegistry.newReader(tableName, logFileType, options); long flushedMaxId = (onlineMinId > 0) ? onlineMinId - 1 : maxId; long readerMaxId = maxId != -1 ? Math.min(flushedMaxId, maxId) : flushedMaxId; logger.debug("#buffer flush bug# minId: {}, readerMaxId: {}", minId, readerMaxId); logger.debug("#buffer flush bug# maxId: {}, onlineMinId: {}", maxId, flushedMaxId); if (req.isAsc()) { if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); } if (logs != null) c.writeLogs(logs); } else { if (logs != null) c.writeLogs(logs); if (minId < 0 || readerMaxId < 0 || readerMaxId >= minId) { TableScanRequest tabletReq = req.clone(); tabletReq.setMaxId(readerMaxId); reader.traverse(tabletReq); } } } catch (InterruptedException e) { throw e; } catch (IllegalStateException e) { c.setFailure(e); Throwable cause = e.getCause(); if (cause instanceof BufferUnderflowException || cause instanceof IOException) c.setFailure(cause); if (e.getMessage().contains("license is locked")) logger.warn("araqne logstorage: search tablet failed. {}", e.getMessage()); else if (logger.isTraceEnabled()) logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (BufferUnderflowException e) { c.setFailure(e); logger.trace("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (IOException e) { c.setFailure(e); logger.warn("araqne logstorage: search tablet failed. logfile may be not synced yet", e); } catch (Exception e) { c.setFailure(e); logger.error("araqne logstorage: search tablet failed", e); } finally { if (reader != null) reader.close(); } return !c.isEof(); }
diff --git a/src/main/java/net/vhati/modmanager/core/ModPatchThread.java b/src/main/java/net/vhati/modmanager/core/ModPatchThread.java index d5cf5b0..fe407e4 100644 --- a/src/main/java/net/vhati/modmanager/core/ModPatchThread.java +++ b/src/main/java/net/vhati/modmanager/core/ModPatchThread.java @@ -1,362 +1,362 @@ package net.vhati.modmanager.core; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import net.vhati.ftldat.FTLDat; import net.vhati.ftldat.FTLDat.AbstractPack; import net.vhati.ftldat.FTLDat.FTLPack; import net.vhati.modmanager.core.ModPatchObserver; import net.vhati.modmanager.core.ModUtilities; import org.jdom2.JDOMException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ModPatchThread extends Thread { private static final Logger log = LogManager.getLogger(ModPatchThread.class); // Other threads can check or set this. public volatile boolean keepRunning = true; private Thread shutdownHook = null; private List<File> modFiles = new ArrayList<File>(); private BackedUpDat dataDat = null; private BackedUpDat resDat = null; private ModPatchObserver observer = null; private final int progMax = 100; private final int progBackupMax = 25; private final int progClobberMax = 25; private final int progModsMax = 40; private final int progRepackMax = 5; private int progMilestone = 0; public ModPatchThread( List<File> modFiles, BackedUpDat dataDat, BackedUpDat resDat, ModPatchObserver observer ) { this.modFiles.addAll( modFiles ); this.dataDat = dataDat; this.resDat = resDat; this.observer = observer; } public void run() { boolean result; Exception exception = null; // When JVM tries to exit, stall until this thread ends on its own. shutdownHook = new Thread() { @Override public void run() { keepRunning = false; boolean interrupted = false; try { while ( ModPatchThread.this.isAlive() ) { try { ModPatchThread.this.join(); } catch ( InterruptedException e ) { interrupted = true; } } } finally { if ( interrupted ) Thread.currentThread().interrupt(); } } }; Runtime.getRuntime().addShutdownHook( shutdownHook ); try { result = patch(); } catch ( Exception e ) { log.error( "Patching failed.", e ); exception = e; result = false; } observer.patchingEnded( result, exception ); Runtime.getRuntime().removeShutdownHook( shutdownHook ); } private boolean patch() throws IOException, JDOMException { observer.patchingProgress( 0, progMax ); BackedUpDat[] allDats = new BackedUpDat[] {dataDat, resDat}; FTLPack dataP = null; FTLPack resP = null; try { int backupsCreated = 0; int datsClobbered = 0; int modsInstalled = 0; int datsRepacked = 0; // Create backup dats, if necessary. for ( BackedUpDat dat : allDats ) { if ( !dat.bakFile.exists() ) { log.info( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); FTLDat.copyFile( dat.datFile, dat.bakFile ); backupsCreated++; observer.patchingProgress( progMilestone + progBackupMax/allDats.length*backupsCreated, progMax ); if ( !keepRunning ) return false; } } progMilestone += progBackupMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingStatus( null ); if ( backupsCreated != allDats.length ) { // Clobber current dat files with their respective backups. // But don't bother if we made those backups just now. for ( BackedUpDat dat : allDats ) { log.info( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); FTLDat.copyFile( dat.bakFile, dat.datFile ); datsClobbered++; observer.patchingProgress( progMilestone + progClobberMax/allDats.length*datsClobbered, progMax ); if ( !keepRunning ) return false; } observer.patchingStatus( null ); } progMilestone += progClobberMax; observer.patchingProgress( progMilestone, progMax ); if ( modFiles.isEmpty() ) { // No mods. Nothing else to do. observer.patchingProgress( progMax, progMax ); return true; } dataP = new FTLPack( dataDat.datFile, false ); resP = new FTLPack( resDat.datFile, false ); Map<String,AbstractPack> topFolderMap = new HashMap<String,AbstractPack>(); topFolderMap.put( "data", dataP ); topFolderMap.put( "audio", resP ); topFolderMap.put( "fonts", resP ); topFolderMap.put( "img", resP ); // Track modified innerPaths in case they're clobbered. List<String> moddedItems = new ArrayList<String>(); List<String> knownPaths = new ArrayList<String>(); knownPaths.addAll( dataP.list() ); knownPaths.addAll( resP.list() ); List<String> knownPathsLower = new ArrayList<String>( knownPaths.size() ); for ( String innerPath : knownPaths ) { knownPathsLower.add( innerPath.toLowerCase() ); } // Group1: parentPath, Group2: topFolder, Group3: fileName Pattern pathPtn = Pattern.compile( "^(([^/]+)/(?:.*/)?)([^/]+)$" ); for ( File modFile : modFiles ) { if ( !keepRunning ) return false; ZipInputStream zis = null; try { log.info( "" ); log.info( String.format( "Installing mod: %s", modFile.getName() ) ); observer.patchingMod( modFile ); zis = new ZipInputStream( new FileInputStream( modFile ) ); ZipEntry item; while ( (item = zis.getNextEntry()) != null ) { if ( item.isDirectory() ) continue; String innerPath = item.getName(); innerPath = innerPath.replace( '\\', '/' ); // Non-standard zips. Matcher m = pathPtn.matcher( innerPath ); if ( !m.matches() ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } String parentPath = m.group(1); String topFolder = m.group(2); String fileName = m.group(3); AbstractPack ftlP = topFolderMap.get( topFolder ); if ( ftlP == null ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } if ( fileName.endsWith( ".xml.append" ) || fileName.endsWith( ".append.xml" ) ) { innerPath = parentPath + fileName.replaceAll( "[.](?:xml[.]append|append[.]xml)$", ".xml" ); innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !ftlP.contains( innerPath ) ) { log.warn( String.format( "Non-existent innerPath wasn't appended: %s", innerPath ) ); } else { InputStream mainStream = null; try { mainStream = ftlP.getInputStream(innerPath); InputStream mergedStream = ModUtilities.patchXMLFile( mainStream, zis, "windows-1252", ftlP.getName()+":"+innerPath, modFile.getName()+":"+parentPath+fileName ); mainStream.close(); ftlP.remove( innerPath ); ftlP.add( innerPath, mergedStream ); } finally { try {if ( mainStream != null ) mainStream.close();} catch ( IOException e ) {} } if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); } } - if ( fileName.endsWith( ".xml" ) ) { + else if ( fileName.endsWith( ".xml" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); InputStream fixedStream = ModUtilities.rebuildXMLFile( zis, "windows-1252", modFile.getName()+":"+parentPath+fileName ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else if ( fileName.endsWith( ".txt" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); // Normalize line endings for other text files to CR-LF. // decodeText() reads anything and returns an LF string. String fixedText = ModUtilities.decodeText( zis, modFile.getName()+":"+parentPath+fileName ).text; fixedText = Pattern.compile("\n").matcher( fixedText ).replaceAll( "\r\n" ); InputStream fixedStream = ModUtilities.encodeText( fixedText, "windows-1252", modFile.getName()+":"+parentPath+fileName+" (with new EOL)" ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, zis ); } zis.closeEntry(); } } finally { try {if (zis != null) zis.close();} catch ( Exception e ) {} System.gc(); } modsInstalled++; observer.patchingProgress( progMilestone + progModsMax/modFiles.size()*modsInstalled, progMax ); } progMilestone += progModsMax; observer.patchingProgress( progMilestone, progMax ); // Prune 'removed' files from dats. for ( AbstractPack ftlP : new AbstractPack[]{dataP,resP} ) { if ( ftlP instanceof FTLPack ) { observer.patchingStatus( String.format( "Repacking \"%s\"...", ftlP.getName() ) ); long bytesChanged = ((FTLPack)ftlP).repack().bytesChanged; log.info( String.format( "Repacked \"%s\" (%d bytes affected)", ftlP.getName(), bytesChanged ) ); datsRepacked++; observer.patchingProgress( progMilestone + progRepackMax/allDats.length*datsRepacked, progMax ); } } progMilestone += progRepackMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingProgress( 100, progMax ); return true; } finally { try {if (dataP != null) dataP.close();} catch( Exception e ) {} try {if (resP != null) resP.close();} catch( Exception e ) {} } } /** * Checks if an innerPath exists, ignoring letter case. * * If there is no collision, the innerPath is added to the known lists. * A warning will be logged if a path with differing case exists. * * @param knownPaths a list of innerPaths seen so far * @param knownPathsLower a copy of knownPaths, lower-cased * @return the existing path (if different), or innerPath */ private String checkCase( String innerPath, List<String> knownPaths, List<String> knownPathsLower ) { if ( knownPaths.contains( innerPath ) ) return innerPath; String lowerPath = innerPath.toLowerCase(); int lowerIndex = knownPathsLower.indexOf( lowerPath ); if ( lowerIndex != -1 ) { String knownPath = knownPaths.get( lowerIndex ); log.warn( String.format( "Modded file's case doesn't match existing path: \"%s\" vs \"%s\"", innerPath, knownPath ) ); return knownPath; } knownPaths.add( innerPath ); knownPathsLower.add( lowerPath ); return innerPath; } public static class BackedUpDat { public File datFile = null; public File bakFile = null; } }
true
true
private boolean patch() throws IOException, JDOMException { observer.patchingProgress( 0, progMax ); BackedUpDat[] allDats = new BackedUpDat[] {dataDat, resDat}; FTLPack dataP = null; FTLPack resP = null; try { int backupsCreated = 0; int datsClobbered = 0; int modsInstalled = 0; int datsRepacked = 0; // Create backup dats, if necessary. for ( BackedUpDat dat : allDats ) { if ( !dat.bakFile.exists() ) { log.info( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); FTLDat.copyFile( dat.datFile, dat.bakFile ); backupsCreated++; observer.patchingProgress( progMilestone + progBackupMax/allDats.length*backupsCreated, progMax ); if ( !keepRunning ) return false; } } progMilestone += progBackupMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingStatus( null ); if ( backupsCreated != allDats.length ) { // Clobber current dat files with their respective backups. // But don't bother if we made those backups just now. for ( BackedUpDat dat : allDats ) { log.info( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); FTLDat.copyFile( dat.bakFile, dat.datFile ); datsClobbered++; observer.patchingProgress( progMilestone + progClobberMax/allDats.length*datsClobbered, progMax ); if ( !keepRunning ) return false; } observer.patchingStatus( null ); } progMilestone += progClobberMax; observer.patchingProgress( progMilestone, progMax ); if ( modFiles.isEmpty() ) { // No mods. Nothing else to do. observer.patchingProgress( progMax, progMax ); return true; } dataP = new FTLPack( dataDat.datFile, false ); resP = new FTLPack( resDat.datFile, false ); Map<String,AbstractPack> topFolderMap = new HashMap<String,AbstractPack>(); topFolderMap.put( "data", dataP ); topFolderMap.put( "audio", resP ); topFolderMap.put( "fonts", resP ); topFolderMap.put( "img", resP ); // Track modified innerPaths in case they're clobbered. List<String> moddedItems = new ArrayList<String>(); List<String> knownPaths = new ArrayList<String>(); knownPaths.addAll( dataP.list() ); knownPaths.addAll( resP.list() ); List<String> knownPathsLower = new ArrayList<String>( knownPaths.size() ); for ( String innerPath : knownPaths ) { knownPathsLower.add( innerPath.toLowerCase() ); } // Group1: parentPath, Group2: topFolder, Group3: fileName Pattern pathPtn = Pattern.compile( "^(([^/]+)/(?:.*/)?)([^/]+)$" ); for ( File modFile : modFiles ) { if ( !keepRunning ) return false; ZipInputStream zis = null; try { log.info( "" ); log.info( String.format( "Installing mod: %s", modFile.getName() ) ); observer.patchingMod( modFile ); zis = new ZipInputStream( new FileInputStream( modFile ) ); ZipEntry item; while ( (item = zis.getNextEntry()) != null ) { if ( item.isDirectory() ) continue; String innerPath = item.getName(); innerPath = innerPath.replace( '\\', '/' ); // Non-standard zips. Matcher m = pathPtn.matcher( innerPath ); if ( !m.matches() ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } String parentPath = m.group(1); String topFolder = m.group(2); String fileName = m.group(3); AbstractPack ftlP = topFolderMap.get( topFolder ); if ( ftlP == null ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } if ( fileName.endsWith( ".xml.append" ) || fileName.endsWith( ".append.xml" ) ) { innerPath = parentPath + fileName.replaceAll( "[.](?:xml[.]append|append[.]xml)$", ".xml" ); innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !ftlP.contains( innerPath ) ) { log.warn( String.format( "Non-existent innerPath wasn't appended: %s", innerPath ) ); } else { InputStream mainStream = null; try { mainStream = ftlP.getInputStream(innerPath); InputStream mergedStream = ModUtilities.patchXMLFile( mainStream, zis, "windows-1252", ftlP.getName()+":"+innerPath, modFile.getName()+":"+parentPath+fileName ); mainStream.close(); ftlP.remove( innerPath ); ftlP.add( innerPath, mergedStream ); } finally { try {if ( mainStream != null ) mainStream.close();} catch ( IOException e ) {} } if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); } } if ( fileName.endsWith( ".xml" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); InputStream fixedStream = ModUtilities.rebuildXMLFile( zis, "windows-1252", modFile.getName()+":"+parentPath+fileName ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else if ( fileName.endsWith( ".txt" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); // Normalize line endings for other text files to CR-LF. // decodeText() reads anything and returns an LF string. String fixedText = ModUtilities.decodeText( zis, modFile.getName()+":"+parentPath+fileName ).text; fixedText = Pattern.compile("\n").matcher( fixedText ).replaceAll( "\r\n" ); InputStream fixedStream = ModUtilities.encodeText( fixedText, "windows-1252", modFile.getName()+":"+parentPath+fileName+" (with new EOL)" ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, zis ); } zis.closeEntry(); } } finally { try {if (zis != null) zis.close();} catch ( Exception e ) {} System.gc(); } modsInstalled++; observer.patchingProgress( progMilestone + progModsMax/modFiles.size()*modsInstalled, progMax ); } progMilestone += progModsMax; observer.patchingProgress( progMilestone, progMax ); // Prune 'removed' files from dats. for ( AbstractPack ftlP : new AbstractPack[]{dataP,resP} ) { if ( ftlP instanceof FTLPack ) { observer.patchingStatus( String.format( "Repacking \"%s\"...", ftlP.getName() ) ); long bytesChanged = ((FTLPack)ftlP).repack().bytesChanged; log.info( String.format( "Repacked \"%s\" (%d bytes affected)", ftlP.getName(), bytesChanged ) ); datsRepacked++; observer.patchingProgress( progMilestone + progRepackMax/allDats.length*datsRepacked, progMax ); } } progMilestone += progRepackMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingProgress( 100, progMax ); return true; } finally { try {if (dataP != null) dataP.close();} catch( Exception e ) {} try {if (resP != null) resP.close();} catch( Exception e ) {} } }
private boolean patch() throws IOException, JDOMException { observer.patchingProgress( 0, progMax ); BackedUpDat[] allDats = new BackedUpDat[] {dataDat, resDat}; FTLPack dataP = null; FTLPack resP = null; try { int backupsCreated = 0; int datsClobbered = 0; int modsInstalled = 0; int datsRepacked = 0; // Create backup dats, if necessary. for ( BackedUpDat dat : allDats ) { if ( !dat.bakFile.exists() ) { log.info( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Backing up \"%s\".", dat.datFile.getName() ) ); FTLDat.copyFile( dat.datFile, dat.bakFile ); backupsCreated++; observer.patchingProgress( progMilestone + progBackupMax/allDats.length*backupsCreated, progMax ); if ( !keepRunning ) return false; } } progMilestone += progBackupMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingStatus( null ); if ( backupsCreated != allDats.length ) { // Clobber current dat files with their respective backups. // But don't bother if we made those backups just now. for ( BackedUpDat dat : allDats ) { log.info( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); observer.patchingStatus( String.format( "Restoring vanilla \"%s\"...", dat.datFile.getName() ) ); FTLDat.copyFile( dat.bakFile, dat.datFile ); datsClobbered++; observer.patchingProgress( progMilestone + progClobberMax/allDats.length*datsClobbered, progMax ); if ( !keepRunning ) return false; } observer.patchingStatus( null ); } progMilestone += progClobberMax; observer.patchingProgress( progMilestone, progMax ); if ( modFiles.isEmpty() ) { // No mods. Nothing else to do. observer.patchingProgress( progMax, progMax ); return true; } dataP = new FTLPack( dataDat.datFile, false ); resP = new FTLPack( resDat.datFile, false ); Map<String,AbstractPack> topFolderMap = new HashMap<String,AbstractPack>(); topFolderMap.put( "data", dataP ); topFolderMap.put( "audio", resP ); topFolderMap.put( "fonts", resP ); topFolderMap.put( "img", resP ); // Track modified innerPaths in case they're clobbered. List<String> moddedItems = new ArrayList<String>(); List<String> knownPaths = new ArrayList<String>(); knownPaths.addAll( dataP.list() ); knownPaths.addAll( resP.list() ); List<String> knownPathsLower = new ArrayList<String>( knownPaths.size() ); for ( String innerPath : knownPaths ) { knownPathsLower.add( innerPath.toLowerCase() ); } // Group1: parentPath, Group2: topFolder, Group3: fileName Pattern pathPtn = Pattern.compile( "^(([^/]+)/(?:.*/)?)([^/]+)$" ); for ( File modFile : modFiles ) { if ( !keepRunning ) return false; ZipInputStream zis = null; try { log.info( "" ); log.info( String.format( "Installing mod: %s", modFile.getName() ) ); observer.patchingMod( modFile ); zis = new ZipInputStream( new FileInputStream( modFile ) ); ZipEntry item; while ( (item = zis.getNextEntry()) != null ) { if ( item.isDirectory() ) continue; String innerPath = item.getName(); innerPath = innerPath.replace( '\\', '/' ); // Non-standard zips. Matcher m = pathPtn.matcher( innerPath ); if ( !m.matches() ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } String parentPath = m.group(1); String topFolder = m.group(2); String fileName = m.group(3); AbstractPack ftlP = topFolderMap.get( topFolder ); if ( ftlP == null ) { log.warn( String.format( "Unexpected innerPath: %s", innerPath ) ); zis.closeEntry(); continue; } if ( fileName.endsWith( ".xml.append" ) || fileName.endsWith( ".append.xml" ) ) { innerPath = parentPath + fileName.replaceAll( "[.](?:xml[.]append|append[.]xml)$", ".xml" ); innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !ftlP.contains( innerPath ) ) { log.warn( String.format( "Non-existent innerPath wasn't appended: %s", innerPath ) ); } else { InputStream mainStream = null; try { mainStream = ftlP.getInputStream(innerPath); InputStream mergedStream = ModUtilities.patchXMLFile( mainStream, zis, "windows-1252", ftlP.getName()+":"+innerPath, modFile.getName()+":"+parentPath+fileName ); mainStream.close(); ftlP.remove( innerPath ); ftlP.add( innerPath, mergedStream ); } finally { try {if ( mainStream != null ) mainStream.close();} catch ( IOException e ) {} } if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); } } else if ( fileName.endsWith( ".xml" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); InputStream fixedStream = ModUtilities.rebuildXMLFile( zis, "windows-1252", modFile.getName()+":"+parentPath+fileName ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else if ( fileName.endsWith( ".txt" ) ) { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); // Normalize line endings for other text files to CR-LF. // decodeText() reads anything and returns an LF string. String fixedText = ModUtilities.decodeText( zis, modFile.getName()+":"+parentPath+fileName ).text; fixedText = Pattern.compile("\n").matcher( fixedText ).replaceAll( "\r\n" ); InputStream fixedStream = ModUtilities.encodeText( fixedText, "windows-1252", modFile.getName()+":"+parentPath+fileName+" (with new EOL)" ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, fixedStream ); } else { innerPath = checkCase( innerPath, knownPaths, knownPathsLower ); if ( !moddedItems.contains(innerPath) ) moddedItems.add( innerPath ); else log.warn( String.format( "Clobbering earlier mods: %s", innerPath ) ); if ( ftlP.contains( innerPath ) ) ftlP.remove( innerPath ); ftlP.add( innerPath, zis ); } zis.closeEntry(); } } finally { try {if (zis != null) zis.close();} catch ( Exception e ) {} System.gc(); } modsInstalled++; observer.patchingProgress( progMilestone + progModsMax/modFiles.size()*modsInstalled, progMax ); } progMilestone += progModsMax; observer.patchingProgress( progMilestone, progMax ); // Prune 'removed' files from dats. for ( AbstractPack ftlP : new AbstractPack[]{dataP,resP} ) { if ( ftlP instanceof FTLPack ) { observer.patchingStatus( String.format( "Repacking \"%s\"...", ftlP.getName() ) ); long bytesChanged = ((FTLPack)ftlP).repack().bytesChanged; log.info( String.format( "Repacked \"%s\" (%d bytes affected)", ftlP.getName(), bytesChanged ) ); datsRepacked++; observer.patchingProgress( progMilestone + progRepackMax/allDats.length*datsRepacked, progMax ); } } progMilestone += progRepackMax; observer.patchingProgress( progMilestone, progMax ); observer.patchingProgress( 100, progMax ); return true; } finally { try {if (dataP != null) dataP.close();} catch( Exception e ) {} try {if (resP != null) resP.close();} catch( Exception e ) {} } }
diff --git a/src/org/melonbrew/fee/commands/YesCommand.java b/src/org/melonbrew/fee/commands/YesCommand.java index 47bf65a..0d32490 100644 --- a/src/org/melonbrew/fee/commands/YesCommand.java +++ b/src/org/melonbrew/fee/commands/YesCommand.java @@ -1,49 +1,49 @@ package org.melonbrew.fee.commands; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.melonbrew.fee.Fee; import org.melonbrew.fee.Phrase; public class YesCommand implements CommandExecutor { private final Fee plugin; public YesCommand(Fee plugin){ this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ - if (!(sender instanceof CommandSender)){ + if (!(sender instanceof Player)){ sender.sendMessage(Phrase.YOU_ARE_NOT_A_PLAYER.parseWithPrefix()); return true; } Player player = (Player) sender; if (!plugin.containsPlayer(player)){ sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } String command = plugin.getCommand(player); if (plugin.getKeyMoney(command) == -1){ plugin.removeCommand(player); sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } plugin.removeCommand(player); player.chat(command); return true; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (!(sender instanceof CommandSender)){ sender.sendMessage(Phrase.YOU_ARE_NOT_A_PLAYER.parseWithPrefix()); return true; } Player player = (Player) sender; if (!plugin.containsPlayer(player)){ sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } String command = plugin.getCommand(player); if (plugin.getKeyMoney(command) == -1){ plugin.removeCommand(player); sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } plugin.removeCommand(player); player.chat(command); return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (!(sender instanceof Player)){ sender.sendMessage(Phrase.YOU_ARE_NOT_A_PLAYER.parseWithPrefix()); return true; } Player player = (Player) sender; if (!plugin.containsPlayer(player)){ sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } String command = plugin.getCommand(player); if (plugin.getKeyMoney(command) == -1){ plugin.removeCommand(player); sender.sendMessage(Phrase.NO_PENDING_COMMAND.parseWithPrefix()); return true; } plugin.removeCommand(player); player.chat(command); return true; }
diff --git a/src/streamfish/StreamFish.java b/src/streamfish/StreamFish.java index 1b406ea..7a4de3b 100644 --- a/src/streamfish/StreamFish.java +++ b/src/streamfish/StreamFish.java @@ -1,234 +1,234 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package streamfish; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author HJ */ public class StreamFish { /** * @param args the command line arguments */ private String databasedriver; private Connection con; public StreamFish() { try { databasedriver = "org.apache.derby.jdbc.ClientDriver"; Class.forName(databasedriver); // laster inn driverklassen String databasenavn = "jdbc:derby://db.stud.aitel.hist.no/streamfish;user=sfdb;password=XEnhdPy8"; con = DriverManager.getConnection(databasenavn); } catch (SQLException ex) { Logger.getLogger(StreamFish.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(StreamFish.class.getName()).log(Level.SEVERE, null, ex); } } public Menu[] getMenus() { Statement stm; ResultSet res; Menu[] menus; int teller = 0; try { stm = con.createStatement(); res = stm.executeQuery("select count(*) antall from menu"); res.next(); int ant = res.getInt("antall"); menus = new Menu[ant]; Opprydder.lukkResSet(res); res = stm.executeQuery("select * from menu"); while (res.next()) { int menuId = res.getInt("menu_id"); String menuName = res.getString("menu_name"); int price = res.getInt("price"); String description = res.getString("description"); boolean busi = false; menus[teller] = new Menu(menuId, menuName, price, description); teller++; } return menus; } catch (SQLException ex) { ex.printStackTrace(); } return null; } public Order[] getOrders() { Statement stm; ResultSet res; Order[] orders; int teller = 0; try { stm = con.createStatement(); res = stm.executeQuery("select count(*) antall from orders"); res.next(); int ant = res.getInt("antall"); orders = new Order[ant]; Opprydder.lukkResSet(res); res = stm.executeQuery("select * from orders"); while (res.next()) { int orderID = res.getInt("order_id"); int menuID = res.getInt("menu_id"); int customerID = res.getInt("customer_id"); int emplID = res.getInt("empl_id"); int nrPersons = res.getInt("nr_persons"); String deliveryDate = res.getString("delivery_date"); String address = res.getString("address"); orders[teller] = new Order(orderID, menuID, customerID, emplID, nrPersons, deliveryDate, address); teller++; } return orders; } catch (SQLException ex) { ex.printStackTrace(); } return null; } public Customer[] getCustomers(String s){ Statement stm; ResultSet res; Customer[] customers; int teller = 0; try { stm = con.createStatement(); - res = stm.executeQuery("select count(*) antall from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like " + Integer.parseInt(s) + "%"); + res = stm.executeQuery("select count(*) antall from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like '" + Integer.parseInt(s) + "%'"); res.next(); int ant = res.getInt("antall"); customers = new Customer[ant]; Opprydder.lukkResSet(res); - res = stm.executeQuery("select * from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like " + Integer.parseInt(s) + "%"); + res = stm.executeQuery("select * from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like '" + Integer.parseInt(s) + "%'"); while(res.next()){ int customerId = res.getInt("customer_id"); String customerName = res.getString("customer_name"); int phone = res.getInt("phone"); int business = Integer.parseInt(res.getString("business")); boolean busi = false; if(business == 1){ busi = true; } customers[teller] = new Customer(customerId, customerName, phone, busi); teller++; } return customers; } catch (SQLException ex) { System.err.println(ex); ex.printStackTrace(); } return null; } public Employee[] getEmployees() { Statement stm; ResultSet res; Employee[] employees; int teller = 0; try { stm = con.createStatement(); res = stm.executeQuery("select count(*) antall from employees"); res.next(); int ant = res.getInt("antall"); employees = new Employee[ant]; Opprydder.lukkResSet(res); res = stm.executeQuery("select empl_id, user_type, username from employees"); while (res.next()) { int emplID = res.getInt("empl_id"); byte userType = res.getByte("user_type"); String username = res.getString("username"); employees[teller] = new Employee(emplID, userType, username); teller++; } return employees; } catch (SQLException ex) { System.err.println(ex); ex.printStackTrace(); } return null; } public int addOrder(Order order) { Statement stm; try { stm = con.createStatement(); String[] check = {order.getDeliveryDate(), order.getAddress()}; check = removeUnwantedSymbols(check); int succ = stm.executeUpdate("insert into orders (DELIVERY_DATE, ADDRESS, NR_PERSONS, EMPL_ID, MENU_ID,CUSTOMER_ID) values('" + check[0] + "' , '" + check[1] + "', " + order.getNrPersons() + ", " + order.getEmplId() + ", " + order.getMenuId() + " , " + order.getCustomerId() + ")"); Opprydder.lukkSetning(stm); return succ; } catch (SQLException ex) { System.err.println(ex); } return -1; } public int addCustomer(Customer customer) { Statement stm; String[] check = {customer.getCustomerName()}; check = removeUnwantedSymbols(check); System.out.println(check[0]); int isbusiness = 0; if (customer.isBusiness()) { isbusiness = 1; } try { stm = con.createStatement(); int succ = stm.executeUpdate("insert into customer (CUSTOMER_NAME, PHONE, BUSINESS) values('" + check[0] + "' , '" + customer.getPhoneNumber() + "', '" + isbusiness + "')"); Opprydder.lukkSetning(stm); return succ; } catch (SQLException ex) { System.err.println(ex); } return -1; } public String[] removeUnwantedSymbols(String[] table) { String[] checkedTable = table; for (int i = 0; i < table.length; i++) { checkedTable[i] = checkedTable[i].replace("'", ""); checkedTable[i] = checkedTable[i].replace(";", " "); System.out.println(checkedTable[i]); } return checkedTable; } public void close() { try { con.close(); } catch (SQLException ex) { Logger.getLogger(StreamFish.class.getName()).log(Level.SEVERE, null, ex); } } }
false
true
public Customer[] getCustomers(String s){ Statement stm; ResultSet res; Customer[] customers; int teller = 0; try { stm = con.createStatement(); res = stm.executeQuery("select count(*) antall from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like " + Integer.parseInt(s) + "%"); res.next(); int ant = res.getInt("antall"); customers = new Customer[ant]; Opprydder.lukkResSet(res); res = stm.executeQuery("select * from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like " + Integer.parseInt(s) + "%"); while(res.next()){ int customerId = res.getInt("customer_id"); String customerName = res.getString("customer_name"); int phone = res.getInt("phone"); int business = Integer.parseInt(res.getString("business")); boolean busi = false; if(business == 1){ busi = true; } customers[teller] = new Customer(customerId, customerName, phone, busi); teller++; } return customers; } catch (SQLException ex) { System.err.println(ex); ex.printStackTrace(); } return null; }
public Customer[] getCustomers(String s){ Statement stm; ResultSet res; Customer[] customers; int teller = 0; try { stm = con.createStatement(); res = stm.executeQuery("select count(*) antall from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like '" + Integer.parseInt(s) + "%'"); res.next(); int ant = res.getInt("antall"); customers = new Customer[ant]; Opprydder.lukkResSet(res); res = stm.executeQuery("select * from customer where customer_name like '" + s.toLowerCase() + "%' or customer_name like '" + s.toUpperCase() + "%' or phone like '" + Integer.parseInt(s) + "%'"); while(res.next()){ int customerId = res.getInt("customer_id"); String customerName = res.getString("customer_name"); int phone = res.getInt("phone"); int business = Integer.parseInt(res.getString("business")); boolean busi = false; if(business == 1){ busi = true; } customers[teller] = new Customer(customerId, customerName, phone, busi); teller++; } return customers; } catch (SQLException ex) { System.err.println(ex); ex.printStackTrace(); } return null; }
diff --git a/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java b/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java index 0fdc6eca2..18f3e8863 100644 --- a/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java +++ b/grails/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java @@ -1,137 +1,138 @@ package org.codehaus.groovy.grails.web.pages; import junit.framework.TestCase; import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException; import java.io.*; /** * Tests the GSP parser. This can detect issues caused by improper * GSP->Groovy conversion. Normally, to compare the code, you can * run the page with a showSource parameter specified. * * The methods parseCode() and trimAndRemoveCR() have been added * to simplify test case code. * * @author Daiji * */ public class ParseTests extends TestCase { public void testParse() throws Exception { String output = parseCode("myTest", "<div>hi</div>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "out.print('<div>hi</div>')\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedSquareBracket() throws Exception { String output = parseCode("myTest", "<g:message code=\"[\"/>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "attrs1 = [\"code\":\"[\"]\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('message','g',attrs1,body1)\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedGstringThrowsException() throws IOException { try{ parseCode("myTest", "<g:message value=\"${boom\">"); }catch(GrailsTagException e){ assertEquals("Unexpected end of file encountered parsing Tag [message] for myTest. Are you missing a closing brace '}'?", e.getMessage()); return; } fail("Expected parse exception not thrown"); } /** * Eliminate potential issues caused by operating system differences * and minor output differences that we don't care about. * * Note: this code is inefficient and could stand to be optimized. */ public String trimAndRemoveCR(String s) { int index; StringBuffer sb = new StringBuffer(s.trim()); while ((index = sb.toString().indexOf('\r')) != -1) { sb.deleteCharAt(index); } return sb.toString(); } public String parseCode(String uri, String gsp) throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream gspIn = new ByteArrayInputStream(gsp.getBytes()); Parse parse = new Parse(uri, gspIn); InputStream in = parse.parse(); send(in, pw); return sw.toString(); } public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); - //System.out.println(output); - assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); + System.out.println("|"+trimAndRemoveCR(output)+"|"); + System.out.println("|"+trimAndRemoveCR(expected)+"|"); + assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); } /** * Copy all of input to output. * @param in * @param out * @throws IOException */ public static void send(InputStream in, Writer out) throws IOException { try { Reader reader = new InputStreamReader(in); char[] buf = new char[8192]; for (;;) { int read = reader.read(buf); if (read <= 0) break; out.write(buf, 0, read); } } finally { out.close(); in.close(); } } // writeInputStreamToResponse() }
true
true
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); System.out.println("|"+trimAndRemoveCR(output)+"|"); System.out.println("|"+trimAndRemoveCR(expected)+"|"); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
diff --git a/src/anonpds/TaskMistress/TaskMistress.java b/src/anonpds/TaskMistress/TaskMistress.java index 8d244d7..f129426 100644 --- a/src/anonpds/TaskMistress/TaskMistress.java +++ b/src/anonpds/TaskMistress/TaskMistress.java @@ -1,248 +1,248 @@ /* TaskMistress.java - Part of Task Mistress * Written in 2012 by anonymous. * * To the extent possible under law, the author(s) have dedicated all copyright and related and neighbouring rights to * this software to the public domain worldwide. This software is distributed without any warranty. * * Full license at <http://creativecommons.org/publicdomain/zero/1.0/>. */ package anonpds.TaskMistress; import java.io.File; import java.util.Vector; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.UIManager; /* CRITICAL add a debugger; something that stores debug information and outputs it in case of an error */ /** * A class that runs the TaskMistress program. * @author anonpds <[email protected]> */ public class TaskMistress { /** Configuration file directory for the program. */ private static final String CONFIG_DIR = "TaskMistress"; /** Configuration file name for the program. */ private static final String CONFIG_FILE = "main.cfg"; /** The name of the program. */ public static final String PROGRAM_NAME = "Task Mistress"; /** The current version of the program. */ public static final String PROGRAM_VERSION = "0.1e"; /** The name of the variable that contains the default task tree path. */ public static final String CONFIG_DEFAULT = "defaultTree"; /** The number of task tree paths kept in history. */ public static final int HISTORY_SIZE = 10; /** The history configuration variable name; a number is appended to this*/ public static final String CONFIG_HISTORY = "history."; /** The current configuration. */ private static Configuration config; /** * Launches an instance of the program at the given file system path. * @param path the path to the task tree to edit * @param ignoreLock set to true to ignore the lock file, false not to ignore it * @throws TaskTreeLockedException if the task tree is locked (already open) * @throws Exception when the TaskStore cannot be initialised */ public TaskMistress(File path, boolean ignoreLock) throws TaskTreeLockedException, Exception { TaskStore store = new TaskStore(path, ignoreLock); new MainWindow(store); } /** * Shows a dialog that allows the user to select a directory path. * @return the selected directory or null if no directory was selected */ public static File showPathDialog() { /* create a file chooser dialog that only allows single selection and only directories */ JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); /* show the dialog and return the selected directory (returns null if no directory chosen) */ chooser.showOpenDialog(null); return(chooser.getSelectedFile()); } /** * Returns the configuration file. Three environment variables are examined for the directory that contains the * configuration file in the following order: XDG_CONFIG_HOME, HOME and APPDATA. If HOME is used, a directory * called ".config" is appended to it. * * In all three cases the directory stored in the constant CONFIG_DIR is further appended to the used environment * variable to get the directory. Then, finally, the actual configuration file name is appended from the constant * CONFIG_FILE. * * @return the configuration file or null if no suitable place for the configuration file was found */ private static File getConfigFile() { File path = null; /* array of tried env. variables and paths that are appended to them */ String[][] envs = { { "XDG_CONFIG_HOME", null }, { "HOME", ".local" }, { "APPDATA", null } }; for (int i = 0; i < envs.length; i++) { String var = System.getenv(envs[i][0]); if (var != null) { /* the environment variable exists; use it */ path = new File(var); if (envs[i][1] != null) path = new File(path, envs[i][1]); break; } } /* if one of the environment variables existed, append the config file directory and name to it*/ if (path != null) { path = new File(path, CONFIG_DIR); path = new File(path, CONFIG_FILE); } return path; } /** Opens the settings window, if not already open. */ public static void showSettings() { SettingsWindow.open(config); } /** * Adds a task tree path to the history. * @param conf the configuration where the history is stored * @param path the path to add */ private static void addToHistory(Configuration conf, File path) { /* TODO use absolute paths if possible */ int i; for (i = 0; i < HISTORY_SIZE; i++) { String name = CONFIG_HISTORY + i; if (conf.get(name) == null) break; if (conf.get(name).compareTo(path.getPath()) == 0) return; /* the path already exists, don't add */ } if (i < HISTORY_SIZE) { String name = CONFIG_HISTORY + i; conf.add(name, path.getPath()); } } /** * Returns the task tree history. * @return an array of task tree history paths */ public static String[] getHistory() { Vector<String> v = new Vector<String>(); for (int i = 0; i < HISTORY_SIZE; i++) { String name = CONFIG_HISTORY + i; if (config.get(name) == null) continue; v.add(config.get(name)); } String[] array = new String[v.size()]; for (int i = 0; i < v.size(); i++) { array[i] = v.get(i); } return(array); } /** Saves the configuration. */ public static void saveConfiguration() { File confFile = TaskMistress.getConfigFile(); if (confFile != null && config != null) { /* create the conf file path if necessary */ File path = confFile.getParentFile(); if (!path.exists()) path.mkdirs(); try { config.store(confFile); } catch (Exception e) { /* TODO errors */ } } } /** * Runs the program. * @param args command line arguments (unused) */ public static void main(String[] args) { /* set native look and feel if possible */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not set native look and feel; using the default.", "Error!", JOptionPane.ERROR_MESSAGE); } /* get the configuration file */ File confFile = TaskMistress.getConfigFile(); File defaultPath = null; /* try to parse it if it exists and extract the default task tree */ try { config = Configuration.parse(confFile); } catch (Exception e) { /* TODO error */ } if (config != null && config.get(CONFIG_DEFAULT) != null) defaultPath = new File(config.get(CONFIG_DEFAULT)); /* the path can also be set by command line argument, which overrides config */ /* TODO add decent command line argument handling */ if (args.length > 0) defaultPath = new File(args[0]); if (defaultPath == null || !defaultPath.exists()) { /* no default task tree or the default does not exist */ defaultPath = TaskMistress.showPathDialog(); if (defaultPath == null) { /* no directory chosen, show a message and terminate the program */ JOptionPane.showMessageDialog(null, "No directory chosen. Terminating the program.", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } /* create a new config, if no config exists */ if (config == null) config = new Configuration(); /* launch TaskMistress from the given path; done in a loop to catch errors, which the user may ignore and * open the tree anyway */ boolean done = false, ignoreLock = false; while (!done) { try { addToHistory(config, defaultPath); new TaskMistress(defaultPath, ignoreLock); /* if the tree was opened successfully, the loop is done */ done = true; /* if no default, make the used path default */ if (config.get(CONFIG_DEFAULT) == null) config.add(CONFIG_DEFAULT, defaultPath.getPath()); } catch (TaskTreeLockedException e) { /* the tree is locked; ask whether to open it anyway */ int choice = JOptionPane.showConfirmDialog(null, "Warning: the task tree may already be open! Proceed anyway?", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.YES_NO_OPTION); /* on yes, open the tree anyway, on no just quit the program */ if (choice == JOptionPane.YES_OPTION) ignoreLock = true; else System.exit(1); } catch (Exception e) { JOptionPane.showMessageDialog(null, - "Failed to initialize the program: " + e.getMessage(), + "Task tree load failed: " + e.getMessage(), PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.ERROR_MESSAGE); System.exit(1); } } /* exited; save the configuration */ saveConfiguration(); } }
true
true
public static void main(String[] args) { /* set native look and feel if possible */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not set native look and feel; using the default.", "Error!", JOptionPane.ERROR_MESSAGE); } /* get the configuration file */ File confFile = TaskMistress.getConfigFile(); File defaultPath = null; /* try to parse it if it exists and extract the default task tree */ try { config = Configuration.parse(confFile); } catch (Exception e) { /* TODO error */ } if (config != null && config.get(CONFIG_DEFAULT) != null) defaultPath = new File(config.get(CONFIG_DEFAULT)); /* the path can also be set by command line argument, which overrides config */ /* TODO add decent command line argument handling */ if (args.length > 0) defaultPath = new File(args[0]); if (defaultPath == null || !defaultPath.exists()) { /* no default task tree or the default does not exist */ defaultPath = TaskMistress.showPathDialog(); if (defaultPath == null) { /* no directory chosen, show a message and terminate the program */ JOptionPane.showMessageDialog(null, "No directory chosen. Terminating the program.", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } /* create a new config, if no config exists */ if (config == null) config = new Configuration(); /* launch TaskMistress from the given path; done in a loop to catch errors, which the user may ignore and * open the tree anyway */ boolean done = false, ignoreLock = false; while (!done) { try { addToHistory(config, defaultPath); new TaskMistress(defaultPath, ignoreLock); /* if the tree was opened successfully, the loop is done */ done = true; /* if no default, make the used path default */ if (config.get(CONFIG_DEFAULT) == null) config.add(CONFIG_DEFAULT, defaultPath.getPath()); } catch (TaskTreeLockedException e) { /* the tree is locked; ask whether to open it anyway */ int choice = JOptionPane.showConfirmDialog(null, "Warning: the task tree may already be open! Proceed anyway?", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.YES_NO_OPTION); /* on yes, open the tree anyway, on no just quit the program */ if (choice == JOptionPane.YES_OPTION) ignoreLock = true; else System.exit(1); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Failed to initialize the program: " + e.getMessage(), PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.ERROR_MESSAGE); System.exit(1); } } /* exited; save the configuration */ saveConfiguration(); }
public static void main(String[] args) { /* set native look and feel if possible */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Could not set native look and feel; using the default.", "Error!", JOptionPane.ERROR_MESSAGE); } /* get the configuration file */ File confFile = TaskMistress.getConfigFile(); File defaultPath = null; /* try to parse it if it exists and extract the default task tree */ try { config = Configuration.parse(confFile); } catch (Exception e) { /* TODO error */ } if (config != null && config.get(CONFIG_DEFAULT) != null) defaultPath = new File(config.get(CONFIG_DEFAULT)); /* the path can also be set by command line argument, which overrides config */ /* TODO add decent command line argument handling */ if (args.length > 0) defaultPath = new File(args[0]); if (defaultPath == null || !defaultPath.exists()) { /* no default task tree or the default does not exist */ defaultPath = TaskMistress.showPathDialog(); if (defaultPath == null) { /* no directory chosen, show a message and terminate the program */ JOptionPane.showMessageDialog(null, "No directory chosen. Terminating the program.", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } /* create a new config, if no config exists */ if (config == null) config = new Configuration(); /* launch TaskMistress from the given path; done in a loop to catch errors, which the user may ignore and * open the tree anyway */ boolean done = false, ignoreLock = false; while (!done) { try { addToHistory(config, defaultPath); new TaskMistress(defaultPath, ignoreLock); /* if the tree was opened successfully, the loop is done */ done = true; /* if no default, make the used path default */ if (config.get(CONFIG_DEFAULT) == null) config.add(CONFIG_DEFAULT, defaultPath.getPath()); } catch (TaskTreeLockedException e) { /* the tree is locked; ask whether to open it anyway */ int choice = JOptionPane.showConfirmDialog(null, "Warning: the task tree may already be open! Proceed anyway?", PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.YES_NO_OPTION); /* on yes, open the tree anyway, on no just quit the program */ if (choice == JOptionPane.YES_OPTION) ignoreLock = true; else System.exit(1); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Task tree load failed: " + e.getMessage(), PROGRAM_NAME + " " + PROGRAM_VERSION, JOptionPane.ERROR_MESSAGE); System.exit(1); } } /* exited; save the configuration */ saveConfiguration(); }
diff --git a/Core/src/org/sleuthkit/autopsy/datamodel/DataConversion.java b/Core/src/org/sleuthkit/autopsy/datamodel/DataConversion.java index b4672bbb5..5c7ff971f 100644 --- a/Core/src/org/sleuthkit/autopsy/datamodel/DataConversion.java +++ b/Core/src/org/sleuthkit/autopsy/datamodel/DataConversion.java @@ -1,138 +1,138 @@ /* * 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.datamodel; import java.awt.Font; import java.util.Arrays; import java.util.Formatter; /** * Helper methods for converting data. */ public class DataConversion { final private static char[] hexArray = "0123456789ABCDEF".toCharArray(); /** * Return the hex-dump layout of the passed in byte array. * Deprecated because we don't need font * @param array Data to display * @param length Amount of data in array to display * @param arrayOffset Offset of where data in array begins as part of a bigger file (used for arrayOffset column) * @param font Font that will be used to display the text * @return */ @Deprecated public static String byteArrayToHex(byte[] array, int length, long arrayOffset, Font font) { return byteArrayToHex(array, length, arrayOffset); } /** * Return the hex-dump layout of the passed in byte array. * @param array Data to display * @param length Amount of data in array to display * @param arrayOffset Offset of where data in array begins as part of a bigger file (used for arrayOffset column) * @return */ public static String byteArrayToHex(byte[] array, int length, long arrayOffset) { if (array == null) { return ""; } else { StringBuilder outputStringBuilder = new StringBuilder(); // loop through the file in 16-byte increments for (int curOffset = 0; curOffset < length; curOffset += 16) { // how many bytes are we displaying on this line int lineLen = 16; if (length - curOffset < 16) { lineLen = length - curOffset; } // print the offset column //outputStringBuilder.append("0x"); outputStringBuilder.append(String.format("0x%08x: ", arrayOffset + curOffset)); //outputStringBuilder.append(": "); // print the hex columns for (int i = 0; i < 16; i++) { if (i < lineLen) { int v = array[curOffset + i] & 0xFF; outputStringBuilder.append(hexArray[v >>> 4]); outputStringBuilder.append(hexArray[v & 0x0F]); } else { outputStringBuilder.append(" "); } // someday we'll offer the option of these two styles... if (true) { outputStringBuilder.append(" "); if (i % 4 == 3) { outputStringBuilder.append(" "); } if (i == 7) { outputStringBuilder.append(" "); } } // xxd style else { if (i % 2 == 1) { outputStringBuilder.append(" "); } } } outputStringBuilder.append(" "); // print the ascii columns - String ascii = new String(array, curOffset, lineLen); + String ascii = new String(array, curOffset, lineLen, java.nio.charset.StandardCharsets.US_ASCII); for (int i = 0; i < 16; i++) { char c = ' '; - if (i < lineLen) { + if (i < ascii.length()) { c = ascii.charAt(i); int dec = (int) c; if (dec < 32 || dec > 126) { c = '.'; } } outputStringBuilder.append(c); } outputStringBuilder.append("\n"); } return outputStringBuilder.toString(); } } protected static String charArrayToByte(char[] array) { if (array == null) { return ""; } else { String[] binary = new String[array.length]; for (int i = 0; i < array.length; i++) { binary[i] = Integer.toBinaryString(array[i]); } return Arrays.toString(binary); } } }
false
true
public static String byteArrayToHex(byte[] array, int length, long arrayOffset) { if (array == null) { return ""; } else { StringBuilder outputStringBuilder = new StringBuilder(); // loop through the file in 16-byte increments for (int curOffset = 0; curOffset < length; curOffset += 16) { // how many bytes are we displaying on this line int lineLen = 16; if (length - curOffset < 16) { lineLen = length - curOffset; } // print the offset column //outputStringBuilder.append("0x"); outputStringBuilder.append(String.format("0x%08x: ", arrayOffset + curOffset)); //outputStringBuilder.append(": "); // print the hex columns for (int i = 0; i < 16; i++) { if (i < lineLen) { int v = array[curOffset + i] & 0xFF; outputStringBuilder.append(hexArray[v >>> 4]); outputStringBuilder.append(hexArray[v & 0x0F]); } else { outputStringBuilder.append(" "); } // someday we'll offer the option of these two styles... if (true) { outputStringBuilder.append(" "); if (i % 4 == 3) { outputStringBuilder.append(" "); } if (i == 7) { outputStringBuilder.append(" "); } } // xxd style else { if (i % 2 == 1) { outputStringBuilder.append(" "); } } } outputStringBuilder.append(" "); // print the ascii columns String ascii = new String(array, curOffset, lineLen); for (int i = 0; i < 16; i++) { char c = ' '; if (i < lineLen) { c = ascii.charAt(i); int dec = (int) c; if (dec < 32 || dec > 126) { c = '.'; } } outputStringBuilder.append(c); } outputStringBuilder.append("\n"); } return outputStringBuilder.toString(); } }
public static String byteArrayToHex(byte[] array, int length, long arrayOffset) { if (array == null) { return ""; } else { StringBuilder outputStringBuilder = new StringBuilder(); // loop through the file in 16-byte increments for (int curOffset = 0; curOffset < length; curOffset += 16) { // how many bytes are we displaying on this line int lineLen = 16; if (length - curOffset < 16) { lineLen = length - curOffset; } // print the offset column //outputStringBuilder.append("0x"); outputStringBuilder.append(String.format("0x%08x: ", arrayOffset + curOffset)); //outputStringBuilder.append(": "); // print the hex columns for (int i = 0; i < 16; i++) { if (i < lineLen) { int v = array[curOffset + i] & 0xFF; outputStringBuilder.append(hexArray[v >>> 4]); outputStringBuilder.append(hexArray[v & 0x0F]); } else { outputStringBuilder.append(" "); } // someday we'll offer the option of these two styles... if (true) { outputStringBuilder.append(" "); if (i % 4 == 3) { outputStringBuilder.append(" "); } if (i == 7) { outputStringBuilder.append(" "); } } // xxd style else { if (i % 2 == 1) { outputStringBuilder.append(" "); } } } outputStringBuilder.append(" "); // print the ascii columns String ascii = new String(array, curOffset, lineLen, java.nio.charset.StandardCharsets.US_ASCII); for (int i = 0; i < 16; i++) { char c = ' '; if (i < ascii.length()) { c = ascii.charAt(i); int dec = (int) c; if (dec < 32 || dec > 126) { c = '.'; } } outputStringBuilder.append(c); } outputStringBuilder.append("\n"); } return outputStringBuilder.toString(); } }
diff --git a/component/src/main/java/com/celements/photo/service/ImageService.java b/component/src/main/java/com/celements/photo/service/ImageService.java index 73f2c00..fcec60f 100644 --- a/component/src/main/java/com/celements/photo/service/ImageService.java +++ b/component/src/main/java/com/celements/photo/service/ImageService.java @@ -1,384 +1,388 @@ package com.celements.photo.service; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.context.Execution; import org.xwiki.model.EntityType; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceResolver; import org.xwiki.model.reference.SpaceReference; import org.xwiki.model.reference.WikiReference; import com.celements.common.classes.IClassCollectionRole; import com.celements.navigation.NavigationClasses; import com.celements.photo.container.ImageDimensions; import com.celements.photo.image.GenerateThumbnail; import com.celements.web.classcollections.OldCoreClasses; import com.celements.web.plugin.cmd.AttachmentURLCommand; import com.celements.web.plugin.cmd.NextFreeDocNameCommand; import com.celements.web.service.IWebUtilsService; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; @Component public class ImageService implements IImageService { private static final Log LOGGER = LogFactory.getFactory().getInstance( ImageService.class); @Requirement EntityReferenceResolver<String> stringRefResolver; @Requirement("celements.oldCoreClasses") IClassCollectionRole oldCoreClasses; @Requirement("celements.celNavigationClasses") IClassCollectionRole navigationClasses; @Requirement IWebUtilsService webUtilsService; NextFreeDocNameCommand nextFreeDocNameCmd; @Requirement Execution execution; AttachmentURLCommand attURLCmd; private XWikiContext getContext() { return (XWikiContext) execution.getContext().getProperty("xwikicontext"); } private OldCoreClasses getOldCoreClasses() { return (OldCoreClasses) oldCoreClasses; } private NavigationClasses getNavigationClasses() { return (NavigationClasses) navigationClasses; } public BaseObject getPhotoAlbumObject(DocumentReference galleryDocRef ) throws XWikiException { XWikiDocument galleryDoc = getContext().getWiki().getDocument(galleryDocRef, getContext()); BaseObject galleryObj = galleryDoc.getXObject(getOldCoreClasses( ).getPhotoAlbumClassRef(getContext().getDatabase())); return galleryObj; } public BaseObject getPhotoAlbumNavObject(DocumentReference galleryDocRef ) throws XWikiException, NoGalleryDocumentException { XWikiDocument galleryDoc = getContext().getWiki().getDocument(galleryDocRef, getContext()); BaseObject navObj = galleryDoc.getXObject(getNavigationClasses( ).getNavigationConfigClassRef(getContext().getDatabase())); if (navObj == null) { throw new NoGalleryDocumentException(); } return navObj; } public SpaceReference getPhotoAlbumSpaceRef(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { String spaceName = getPhotoAlbumNavObject(galleryDocRef).getStringValue( NavigationClasses.MENU_SPACE_FIELD); return new SpaceReference(spaceName, webUtilsService.getWikiRef( galleryDocRef)); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return null; } public int getPhotoAlbumMaxHeight(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { return getPhotoAlbumObject(galleryDocRef).getIntValue("height2"); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return 2000; } public int getPhotoAlbumMaxWidth(DocumentReference galleryDocRef ) throws NoGalleryDocumentException { try { return getPhotoAlbumObject(galleryDocRef).getIntValue("photoWidth"); } catch (XWikiException exp) { LOGGER.error("Failed to getPhotoAlbumSpaceRef.", exp); } return 2000; } private DocumentReference getDocRefFromFullName(String collDocName) { DocumentReference eventRef = new DocumentReference(stringRefResolver.resolve( collDocName, EntityType.DOCUMENT)); eventRef.setWikiReference(new WikiReference(getContext().getDatabase())); LOGGER.debug("getDocRefFromFullName: for [" + collDocName + "] got reference [" + eventRef + "]."); return eventRef; } public ImageDimensions getDimension(String imageFullName) throws XWikiException { String fullName = imageFullName.split(";")[0]; String imageFileName = imageFullName.split(";")[1]; DocumentReference docRef = getDocRefFromFullName(fullName); AttachmentReference imgRef = new AttachmentReference(imageFileName, docRef); return getDimension(imgRef); } public ImageDimensions getDimension(AttachmentReference imgRef) throws XWikiException { DocumentReference docRef = (DocumentReference) imgRef.getParent(); XWikiDocument theDoc = getContext().getWiki().getDocument(docRef, getContext()); XWikiAttachment theAttachment = theDoc.getAttachment(imgRef.getName()); ImageDimensions imageDimensions = null; GenerateThumbnail genThumbnail = new GenerateThumbnail(); InputStream imageInStream = null; try { imageInStream = theAttachment.getContentInputStream(getContext()); imageDimensions = genThumbnail.getImageDimensions(imageInStream); } finally { if(imageInStream != null) { try { imageInStream.close(); } catch (IOException ioe) { LOGGER.error("Error closing InputStream.", ioe); } } else { imageDimensions = new ImageDimensions(); } } return imageDimensions; } /** * getRandomImages computes a set of <num> randomly chosen images * from the given AttachmentList. It chooses the Images without duplicates if * possible. */ public List<Attachment> getRandomImages(DocumentReference galleryRef, int num) { try { Document imgDoc = getContext().getWiki().getDocument(galleryRef, getContext() ).newDocument(getContext()); List<Attachment> allImagesList = webUtilsService.getAttachmentListSorted(imgDoc, "AttachmentAscendingNameComparator", true); if (allImagesList.size() > 0) { List<Attachment> preSetImgList = prepareMaxCoverSet(num, allImagesList); List<Attachment> imgList = new ArrayList<Attachment>(num); Random rand = new Random(); for (int i=1; i<=num ; i++) { int nextimg = rand.nextInt(preSetImgList.size()); imgList.add(preSetImgList.remove(nextimg)); } return imgList; } } catch (XWikiException e) { LOGGER.error(e); } return Collections.emptyList(); } <T> List<T> prepareMaxCoverSet(int num, List<T> allImagesList) { List<T> preSetImgList = new Vector<T>(num); preSetImgList.addAll(allImagesList); for(int i=2; i <= coveredQuotient(allImagesList.size(), num); i++) { preSetImgList.addAll(allImagesList); } return preSetImgList; } int coveredQuotient(int divisor, int dividend) { if (dividend >= 0) { return ( (dividend + divisor - 1) / divisor); } else { return (dividend / divisor); } } private NextFreeDocNameCommand getNextFreeDocNameCmd() { if (this.nextFreeDocNameCmd == null) { this.nextFreeDocNameCmd = new NextFreeDocNameCommand(); } return this.nextFreeDocNameCmd; } private AttachmentURLCommand getAttURLCmd() { if (attURLCmd == null) { attURLCmd = new AttachmentURLCommand(); } return attURLCmd; } public boolean checkAddSlideRights(DocumentReference galleryDocRef) { try { DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( getPhotoAlbumSpaceRef(galleryDocRef).getName(), "Testname", getContext()); String newSlideDocFN = webUtilsService.getRefDefaultSerializer().serialize( newSlideDocRef); return (getContext().getWiki().getRightService().hasAccessLevel("edit", getContext().getUser(), newSlideDocFN, getContext())); } catch (XWikiException exp) { LOGGER.error("failed to checkAddSlideRights for [" + galleryDocRef + "].", exp); } catch (NoGalleryDocumentException exp) { LOGGER.debug("failed to checkAddSlideRights for no gallery document [" + galleryDocRef + "].", exp); } return false; } public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); String imgURL = getAttURLCmd().getAttachmentURL(attFullName, "download", getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); String fullImgURL = imgURL + ((imgURL.indexOf("?") < 0)?"?":"&") + resizeParam; VelocityContext vcontext = (VelocityContext)getContext().get("vcontext"); vcontext.put("imageURL", fullImgURL); vcontext.put("attFullName", attFullName); Map<String, String> metaTagMap = new HashMap<String, String>(); DocumentReference attDocRef = webUtilsService.resolveDocumentReference( attFullName.replaceAll("^(.*);.*$", "$1")); - DocumentReference centralFBDocRef = webUtilsService.resolveDocumentReference( - getContext().getWiki().getWebPreference("cel_centralfilebase", getContext())); + DocumentReference centralFBDocRef = null; + String centralFB = getContext().getWiki().getWebPreference("cel_centralfilebase", + getContext()); + if((centralFB != null) && !"".equals(centralFB.trim())) { + centralFBDocRef = webUtilsService.resolveDocumentReference(centralFB); + } if(getContext().getWiki().exists(attDocRef, getContext()) && !attDocRef.equals(centralFBDocRef)) { XWikiDocument attDoc = getContext().getWiki().getDocument(attDocRef, getContext( )); DocumentReference tagClassRef = webUtilsService.resolveDocumentReference( "Classes.PhotoMetainfoClass"); List<BaseObject> metaObjs = attDoc.getXObjects(tagClassRef); if(metaObjs != null) { for(BaseObject tag : metaObjs) { if(tag != null) { metaTagMap.put(tag.getStringValue("name"), tag.getStringValue( "description")); } } } } else if(attDocRef.equals(centralFBDocRef)) { // metaTagMap.putAll(metaInfoService.getAllTags(attDocRef, // attFullName.replaceAll("^.*;(.*)$", "$1"))); } vcontext.put("metaTagMap", metaTagMap); DocumentReference slideContentRef = new DocumentReference(getContext( ).getDatabase(), "Templates", "ImageSlideImportContent"); String slideContent = webUtilsService.renderInheritableDocument(slideContentRef, getContext().getLanguage(), webUtilsService.getDefaultLanguage()); newSlideDoc.setContent(slideContent); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; } public DocumentReference getImageSlideTemplateRef() { DocumentReference slideTemplateRef = new DocumentReference( getContext().getDatabase(), "ImageGalleryTemplates", "NewImageGallerySlide"); if(!getContext().getWiki().exists(slideTemplateRef, getContext())) { slideTemplateRef = new DocumentReference("celements2web", "ImageGalleryTemplates", "NewImageGallerySlide"); } return slideTemplateRef; } public Map<String, String> getImageURLinAllAspectRatios(XWikiAttachment ximage) { ImageDimensions dim = null; try { dim = (new GenerateThumbnail()).getThumbnailDimensions(ximage.getContentInputStream( getContext()), -1, -1, false, null); } catch (XWikiException xwe) { LOGGER.error("Exception reading image dimensions", xwe); } Map<String, String> urlMap = new HashMap<String, String>(); if(dim != null) { String baseURL = ximage.getDoc().getExternalAttachmentURL( ximage.getFilename(), "download", getContext()); if(baseURL.indexOf("?") < 0) { baseURL += "?"; } else if(!baseURL.endsWith("&")) { baseURL += "&"; } urlMap.put("1:1", baseURL + getFixedAspectURL(dim, 1, 1)); urlMap.put("3:4", baseURL + getFixedAspectURL(dim, 3, 4)); urlMap.put("4:3", baseURL + getFixedAspectURL(dim, 4, 3)); urlMap.put("16:9", baseURL + getFixedAspectURL(dim, 16, 9)); urlMap.put("16:10", baseURL + getFixedAspectURL(dim, 16, 10)); } return urlMap; } String getFixedAspectURL(ImageDimensions dim, int xFact, int yFact) { double width = dim.getWidth(); double height = dim.getHeight(); double isAspRatio = width / (double)height; double targetAspRatio = xFact / (double)yFact; double epsylon = 0.00001; String urlParams = ""; //only crop if dim does not matche target aspect ratio if(Math.abs(isAspRatio - targetAspRatio) > epsylon) { if(isAspRatio < targetAspRatio) { urlParams += "cropX=0&cropW=" + (int)width; int newHeight = (int)Math.floor(width * (1 / targetAspRatio)); int top = (int)Math.floor((height - (double)newHeight) / 2); urlParams += "&cropY=" + top + "&cropH=" + newHeight; } else { int newWidth = (int)Math.floor(height * targetAspRatio); int left = (int)Math.floor((width - (double)newWidth) / 2); urlParams += "cropX=" + left + "&cropW=" + newWidth; urlParams += "&cropY=0&cropH=" + (int)height; } } return urlParams; } }
true
true
public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); String imgURL = getAttURLCmd().getAttachmentURL(attFullName, "download", getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); String fullImgURL = imgURL + ((imgURL.indexOf("?") < 0)?"?":"&") + resizeParam; VelocityContext vcontext = (VelocityContext)getContext().get("vcontext"); vcontext.put("imageURL", fullImgURL); vcontext.put("attFullName", attFullName); Map<String, String> metaTagMap = new HashMap<String, String>(); DocumentReference attDocRef = webUtilsService.resolveDocumentReference( attFullName.replaceAll("^(.*);.*$", "$1")); DocumentReference centralFBDocRef = webUtilsService.resolveDocumentReference( getContext().getWiki().getWebPreference("cel_centralfilebase", getContext())); if(getContext().getWiki().exists(attDocRef, getContext()) && !attDocRef.equals(centralFBDocRef)) { XWikiDocument attDoc = getContext().getWiki().getDocument(attDocRef, getContext( )); DocumentReference tagClassRef = webUtilsService.resolveDocumentReference( "Classes.PhotoMetainfoClass"); List<BaseObject> metaObjs = attDoc.getXObjects(tagClassRef); if(metaObjs != null) { for(BaseObject tag : metaObjs) { if(tag != null) { metaTagMap.put(tag.getStringValue("name"), tag.getStringValue( "description")); } } } } else if(attDocRef.equals(centralFBDocRef)) { // metaTagMap.putAll(metaInfoService.getAllTags(attDocRef, // attFullName.replaceAll("^.*;(.*)$", "$1"))); } vcontext.put("metaTagMap", metaTagMap); DocumentReference slideContentRef = new DocumentReference(getContext( ).getDatabase(), "Templates", "ImageSlideImportContent"); String slideContent = webUtilsService.renderInheritableDocument(slideContentRef, getContext().getLanguage(), webUtilsService.getDefaultLanguage()); newSlideDoc.setContent(slideContent); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; }
public boolean addSlideFromTemplate(DocumentReference galleryDocRef, String slideBaseName, String attFullName) { try { DocumentReference slideTemplateRef = getImageSlideTemplateRef(); String gallerySpaceName = getPhotoAlbumSpaceRef(galleryDocRef).getName(); DocumentReference newSlideDocRef = getNextFreeDocNameCmd().getNextTitledPageDocRef( gallerySpaceName, slideBaseName, getContext()); if (getContext().getWiki().copyDocument(slideTemplateRef, newSlideDocRef, true, getContext())) { XWikiDocument newSlideDoc = getContext().getWiki().getDocument(newSlideDocRef, getContext()); newSlideDoc.setDefaultLanguage(webUtilsService.getDefaultLanguage( gallerySpaceName)); Date creationDate = new Date(); newSlideDoc.setLanguage(""); newSlideDoc.setCreationDate(creationDate); newSlideDoc.setContentUpdateDate(creationDate); newSlideDoc.setDate(creationDate); newSlideDoc.setCreator(getContext().getUser()); newSlideDoc.setAuthor(getContext().getUser()); newSlideDoc.setTranslation(0); String imgURL = getAttURLCmd().getAttachmentURL(attFullName, "download", getContext()); String resizeParam = "celwidth=" + getPhotoAlbumMaxWidth(galleryDocRef) + "&celheight=" + getPhotoAlbumMaxHeight(galleryDocRef); String fullImgURL = imgURL + ((imgURL.indexOf("?") < 0)?"?":"&") + resizeParam; VelocityContext vcontext = (VelocityContext)getContext().get("vcontext"); vcontext.put("imageURL", fullImgURL); vcontext.put("attFullName", attFullName); Map<String, String> metaTagMap = new HashMap<String, String>(); DocumentReference attDocRef = webUtilsService.resolveDocumentReference( attFullName.replaceAll("^(.*);.*$", "$1")); DocumentReference centralFBDocRef = null; String centralFB = getContext().getWiki().getWebPreference("cel_centralfilebase", getContext()); if((centralFB != null) && !"".equals(centralFB.trim())) { centralFBDocRef = webUtilsService.resolveDocumentReference(centralFB); } if(getContext().getWiki().exists(attDocRef, getContext()) && !attDocRef.equals(centralFBDocRef)) { XWikiDocument attDoc = getContext().getWiki().getDocument(attDocRef, getContext( )); DocumentReference tagClassRef = webUtilsService.resolveDocumentReference( "Classes.PhotoMetainfoClass"); List<BaseObject> metaObjs = attDoc.getXObjects(tagClassRef); if(metaObjs != null) { for(BaseObject tag : metaObjs) { if(tag != null) { metaTagMap.put(tag.getStringValue("name"), tag.getStringValue( "description")); } } } } else if(attDocRef.equals(centralFBDocRef)) { // metaTagMap.putAll(metaInfoService.getAllTags(attDocRef, // attFullName.replaceAll("^.*;(.*)$", "$1"))); } vcontext.put("metaTagMap", metaTagMap); DocumentReference slideContentRef = new DocumentReference(getContext( ).getDatabase(), "Templates", "ImageSlideImportContent"); String slideContent = webUtilsService.renderInheritableDocument(slideContentRef, getContext().getLanguage(), webUtilsService.getDefaultLanguage()); newSlideDoc.setContent(slideContent); getContext().getWiki().saveDocument(newSlideDoc, "add default image slide" + " content", true, getContext()); return true; } else { LOGGER.warn("failed to copy slideTemplateRef [" + slideTemplateRef + "] to new slide doc [" + newSlideDocRef + "]."); } } catch (NoGalleryDocumentException exp) { LOGGER.error("failed to addSlideFromTemplate because no gallery doc.", exp); } catch (XWikiException exp) { LOGGER.error("failed to addSlideFromTemplate.", exp); } return false; }
diff --git a/core/sail/nativerdf/src/main/java/org/openrdf/sail/nativerdf/config/NativeStoreFactory.java b/core/sail/nativerdf/src/main/java/org/openrdf/sail/nativerdf/config/NativeStoreFactory.java index 2f3ab4026..c1518bc1b 100644 --- a/core/sail/nativerdf/src/main/java/org/openrdf/sail/nativerdf/config/NativeStoreFactory.java +++ b/core/sail/nativerdf/src/main/java/org/openrdf/sail/nativerdf/config/NativeStoreFactory.java @@ -1,56 +1,57 @@ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 2007. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.sail.nativerdf.config; import org.openrdf.sail.Sail; import org.openrdf.sail.config.SailConfigException; import org.openrdf.sail.config.SailFactory; import org.openrdf.sail.config.SailImplConfig; import org.openrdf.sail.nativerdf.NativeStore; /** * A {@link SailFactory} that creates {@link NativeStore}s based on RDF * configuration data. * * @author Arjohn Kampman */ public class NativeStoreFactory implements SailFactory { /** * The type of repositories that are created by this factory. * * @see SailFactory#getSailType() */ public static final String SAIL_TYPE = "openrdf:NativeStore"; /** * Returns the Sail's type: <tt>openrdf:NativeStore</tt>. */ public String getSailType() { return SAIL_TYPE; } public SailImplConfig getConfig() { return new NativeStoreConfig(); } public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } NativeStore nativeStore = new NativeStore(); if (config instanceof NativeStoreConfig) { NativeStoreConfig nativeConfig = (NativeStoreConfig)config; nativeStore.setTripleIndexes(nativeConfig.getTripleIndexes()); + nativeStore.setForceSync(nativeConfig.getForceSync()); } return nativeStore; } }
true
true
public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } NativeStore nativeStore = new NativeStore(); if (config instanceof NativeStoreConfig) { NativeStoreConfig nativeConfig = (NativeStoreConfig)config; nativeStore.setTripleIndexes(nativeConfig.getTripleIndexes()); } return nativeStore; }
public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } NativeStore nativeStore = new NativeStore(); if (config instanceof NativeStoreConfig) { NativeStoreConfig nativeConfig = (NativeStoreConfig)config; nativeStore.setTripleIndexes(nativeConfig.getTripleIndexes()); nativeStore.setForceSync(nativeConfig.getForceSync()); } return nativeStore; }
diff --git a/Paintroid/Paintroid/src/at/tugraz/ist/paintroid/FileIO.java b/Paintroid/Paintroid/src/at/tugraz/ist/paintroid/FileIO.java index 9e6141af..62533ed5 100644 --- a/Paintroid/Paintroid/src/at/tugraz/ist/paintroid/FileIO.java +++ b/Paintroid/Paintroid/src/at/tugraz/ist/paintroid/FileIO.java @@ -1,177 +1,179 @@ /* Catroid: An on-device graphical programming language for Android devices * Copyright (C) 2010 Catroid development team * (<http://code.google.com/p/catroid/wiki/Credits>) * * 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 at.tugraz.ist.paintroid; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.media.MediaScannerConnection; import android.media.MediaScannerConnection.MediaScannerConnectionClient; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; /** * Helper class for saving an image to the sdcard. * * Status: refactored 04.02.2011 * @author PaintroidTeam * @version 6.0b */ public class FileIO { private Context callerContext; private final String paintroidImagesFolder = "/Paintroid/"; FileIO(Context context){ callerContext = context; } /** * This class is responsible for reloading the media gallery * after we added a new file. A new instance should be created * before adding a new file. */ private static class MediaScannerNotifier implements MediaScannerConnectionClient { private MediaScannerConnection mConnection; private String mPath; private String mMimeType; public MediaScannerNotifier(Context context, String path, String mimeType) { mPath = path; mMimeType = mimeType; mConnection = new MediaScannerConnection(context, this); mConnection.connect(); } public void onMediaScannerConnected() { Log.d("PAINTROID", "onMediaScannerConnected"); mConnection.scanFile(mPath, mMimeType); } public void onScanCompleted(String path, Uri uri) { if(uri == null) { Log.d("PAINTROID", "onScanCompleted failed"); } else { Log.d("PAINTROID", "onScanCompleted successful"); } mConnection.disconnect(); } } /** * Get the real path from an Android gallery-URI. This is a static * method that can be called without creating an instance of this class. * * @param cr ContentResolver from the calling activity * @param contentUri Gallery-URI to convert into real path * @return real Path as a STring */ static public String getRealPathFromURI(ContentResolver cr, Uri contentUri) { String[] data = { MediaStore.Images.Media.DATA }; Cursor cursor = cr.query(contentUri, data, null, null, null); int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String realPath = cursor.getString(columnIndex); return realPath; } /** * Saves a Bitmap to a file in the standard pictures folder on the sdcard. * * @param cr ContentResolver from the calling activity * @param save_name Save name for the bitmap * @param bitmap Bitmap to save * * @return 0 on success, otherwise -1 */ public Uri saveBitmapToSDCard(ContentResolver cr, String savename, Bitmap bitmap){ // checking whether media (sdcard) is available boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } if(!mExternalStorageAvailable || !mExternalStorageWriteable) { Log.d("PAINTROID", "Error: SDCard not available!"); return null; } String externalStorageDirectory = Environment.getExternalStorageDirectory().toString(); String paintroidImagesDirectory = externalStorageDirectory + paintroidImagesFolder; File newPaintroidImagesDirectory = new File(paintroidImagesDirectory); if(!newPaintroidImagesDirectory.mkdirs()) { Log.d("PAINTROID", "Error: Could not create directory structure to save picture."); + //catch when try to save empty bitmap + if (bitmap == null){ return null;} } File outputFile = new File(newPaintroidImagesDirectory, savename + ".png"); try { FileOutputStream out = new FileOutputStream(outputFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); Log.d("PAINTROID", "FileIO: Bitmap saved with name: " + savename); } catch (FileNotFoundException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } catch (IOException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } // Add new file to the media gallery new MediaScannerNotifier(callerContext, outputFile.getAbsolutePath(), null); return Uri.fromFile(outputFile); } }
true
true
public Uri saveBitmapToSDCard(ContentResolver cr, String savename, Bitmap bitmap){ // checking whether media (sdcard) is available boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } if(!mExternalStorageAvailable || !mExternalStorageWriteable) { Log.d("PAINTROID", "Error: SDCard not available!"); return null; } String externalStorageDirectory = Environment.getExternalStorageDirectory().toString(); String paintroidImagesDirectory = externalStorageDirectory + paintroidImagesFolder; File newPaintroidImagesDirectory = new File(paintroidImagesDirectory); if(!newPaintroidImagesDirectory.mkdirs()) { Log.d("PAINTROID", "Error: Could not create directory structure to save picture."); } File outputFile = new File(newPaintroidImagesDirectory, savename + ".png"); try { FileOutputStream out = new FileOutputStream(outputFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); Log.d("PAINTROID", "FileIO: Bitmap saved with name: " + savename); } catch (FileNotFoundException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } catch (IOException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } // Add new file to the media gallery new MediaScannerNotifier(callerContext, outputFile.getAbsolutePath(), null); return Uri.fromFile(outputFile); }
public Uri saveBitmapToSDCard(ContentResolver cr, String savename, Bitmap bitmap){ // checking whether media (sdcard) is available boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } if(!mExternalStorageAvailable || !mExternalStorageWriteable) { Log.d("PAINTROID", "Error: SDCard not available!"); return null; } String externalStorageDirectory = Environment.getExternalStorageDirectory().toString(); String paintroidImagesDirectory = externalStorageDirectory + paintroidImagesFolder; File newPaintroidImagesDirectory = new File(paintroidImagesDirectory); if(!newPaintroidImagesDirectory.mkdirs()) { Log.d("PAINTROID", "Error: Could not create directory structure to save picture."); //catch when try to save empty bitmap if (bitmap == null){ return null;} } File outputFile = new File(newPaintroidImagesDirectory, savename + ".png"); try { FileOutputStream out = new FileOutputStream(outputFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); Log.d("PAINTROID", "FileIO: Bitmap saved with name: " + savename); } catch (FileNotFoundException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } catch (IOException e) { Log.d("PAINTROID", "FileNotFoundException: " + e); return null; } // Add new file to the media gallery new MediaScannerNotifier(callerContext, outputFile.getAbsolutePath(), null); return Uri.fromFile(outputFile); }
diff --git a/NearMeServer/src/com/nearme/NearbyPoiServlet.java b/NearMeServer/src/com/nearme/NearbyPoiServlet.java index be9885e..f8e9373 100644 --- a/NearMeServer/src/com/nearme/NearbyPoiServlet.java +++ b/NearMeServer/src/com/nearme/NearbyPoiServlet.java @@ -1,71 +1,71 @@ package com.nearme; import java.io.IOException; import java.lang.reflect.Type; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * This servlet responds to HTTP GET requests of the form * * http://server/nearme/pois/LAT/LONG/RADIUS * * where * * LAT is a latitude * LONG is a longitude * RADIUS is a radius (in metres) * * and returns a JSON data structure with a list of Points of Interest * * @author twhume * */ public class NearbyPoiServlet extends GenericNearMeServlet { private static final long serialVersionUID = 4851880984536596503L; // Having this stops Eclipse moaning at us private static Logger logger = Logger.getLogger(NearbyPoiServlet.class); protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("application/json"); PoiQuery pq = new PoiQuery(req.getPathInfo()); try { PoiFinder pf = new DatabasePoiFinder(datasource); UserDAO uf = new UserDAOImpl(datasource); /* Get a list of all nearby points of interest and add in nearby friends */ User u = uf.read(1); //TODO fix grotty hardcoding, take device-ID from URL List<Poi> points = pf.find(pq); logger.info("found " + points.size() + " POIs for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); List<Poi> friends = uf.getNearestUsers(u, pq.getRadius()); - logger.info("found " + friends.size() + " POIs for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); + logger.info("found " + friends.size() + " friends for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); points.addAll(friends); /* Use GSon to serialise this list onto a JSON structure, and send it to the client. * This is a little bit complicated because we're asking it to serialise a list of stuff; * see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples * if you /really/ want to find out why... */ Gson gson = new Gson(); Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType(); res.getOutputStream().print(gson.toJson(points, listOfPois)); logger.debug("delivered POIs OK"); } catch (SQLException e) { logger.error(e); e.printStackTrace(); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("application/json"); PoiQuery pq = new PoiQuery(req.getPathInfo()); try { PoiFinder pf = new DatabasePoiFinder(datasource); UserDAO uf = new UserDAOImpl(datasource); /* Get a list of all nearby points of interest and add in nearby friends */ User u = uf.read(1); //TODO fix grotty hardcoding, take device-ID from URL List<Poi> points = pf.find(pq); logger.info("found " + points.size() + " POIs for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); List<Poi> friends = uf.getNearestUsers(u, pq.getRadius()); logger.info("found " + friends.size() + " POIs for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); points.addAll(friends); /* Use GSon to serialise this list onto a JSON structure, and send it to the client. * This is a little bit complicated because we're asking it to serialise a list of stuff; * see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples * if you /really/ want to find out why... */ Gson gson = new Gson(); Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType(); res.getOutputStream().print(gson.toJson(points, listOfPois)); logger.debug("delivered POIs OK"); } catch (SQLException e) { logger.error(e); e.printStackTrace(); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("application/json"); PoiQuery pq = new PoiQuery(req.getPathInfo()); try { PoiFinder pf = new DatabasePoiFinder(datasource); UserDAO uf = new UserDAOImpl(datasource); /* Get a list of all nearby points of interest and add in nearby friends */ User u = uf.read(1); //TODO fix grotty hardcoding, take device-ID from URL List<Poi> points = pf.find(pq); logger.info("found " + points.size() + " POIs for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); List<Poi> friends = uf.getNearestUsers(u, pq.getRadius()); logger.info("found " + friends.size() + " friends for user 1 within " + pq.getRadius() + " of (" + pq.getLatitude() + "," + pq.getLongitude() + ")"); points.addAll(friends); /* Use GSon to serialise this list onto a JSON structure, and send it to the client. * This is a little bit complicated because we're asking it to serialise a list of stuff; * see the manual at https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples * if you /really/ want to find out why... */ Gson gson = new Gson(); Type listOfPois = (Type) (new TypeToken<List<Poi>>(){}).getType(); res.getOutputStream().print(gson.toJson(points, listOfPois)); logger.debug("delivered POIs OK"); } catch (SQLException e) { logger.error(e); e.printStackTrace(); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
diff --git a/src/com/ph/tymyreader/TymyListActivity.java b/src/com/ph/tymyreader/TymyListActivity.java index 9d1b536..33c6a73 100644 --- a/src/com/ph/tymyreader/TymyListActivity.java +++ b/src/com/ph/tymyreader/TymyListActivity.java @@ -1,372 +1,372 @@ package com.ph.tymyreader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.ListActivity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ph.tymyreader.model.TymyPref; public class TymyListActivity extends ListActivity { // private static final String TAG = TymyReader.TAG; private static final int EDIT_TYMY_ACTIVITY = 1; private static final int DS_LIST_ACTIVITY = 2; private String[] from = new String[] {TymyPref.ONE, TymyPref.TWO}; private int[] to = new int[] {R.id.text1, R.id.text2}; private List<HashMap<String, String>> tymyList = new ArrayList<HashMap<String,String>>(); private List<TymyPref> tymyPrefList = new ArrayList<TymyPref>(); private SimpleAdapter adapter; private TymyListUtil tlu; ListView lv; private TymyReader app; private List<LoginAndUpdateTymy> loginAndUpdateTymy = new ArrayList<TymyListActivity.LoginAndUpdateTymy>(); private UpdateNewItemsTymy updateNewItemsTymy; private ProgressBar pb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tymy_list); app = (TymyReader) getApplication(); tlu = new TymyListUtil(); + pb = (ProgressBar) findViewById(R.id.progress_bar); TymyListActivity oldState = (TymyListActivity) getLastNonConfigurationInstance(); if (oldState == null) { // activity was started => load configuration app.loadTymyCfg(); tymyPrefList = app.getTymyPrefList(); - pb = (ProgressBar) findViewById(R.id.progress_bar); adapter = new SimpleAdapter(this, tymyList, R.layout.two_line_list_discs, from, to); refreshListView(); //refresh discussions from web // reloadTymyDsList(); // reload i seznamu diskusi, muze byt pomaljesi reloadTymyNewItems(); // reload pouze poctu novych prispevku } else { // Configuration was changed, reload data tymyList = oldState.tymyList; tymyPrefList = oldState.tymyPrefList; updateNewItemsTymy = oldState.updateNewItemsTymy; // pb = oldState.pb; // pb.setVisibility(oldState.pb.getVisibility()); adapter = oldState.adapter; refreshListView(); } // Set-up adapter for tymyList lv = getListView(); lv.setAdapter(adapter); registerForContextMenu(getListView()); if (!app.isOnline()) { Toast.makeText(this, R.string.no_connection, Toast.LENGTH_LONG).show(); } } @Override protected void onPause() { super.onPause(); if (isFinishing()) { cancelBackgroundTasks(); } } @Override protected void onDestroy () { super.onDestroy(); //save configuration app.saveTymyCfg(tymyPrefList); } @Override public Object onRetainNonConfigurationInstance() { return this; } // ************** Activity Option menu ************** // @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_tymy_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_settings: showSettings(); return true; case R.id.menu_add_tymy: showAddTymy(); return true; case R.id.menu_refresh: // refreshTymyPrefList(); reloadTymyNewItems(); return true; // case R.id.menu_send_report: // ACRA.getErrorReporter().handleException(new Exception("Manual report")); // return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); int index = tlu.getIndexFromUrl(tymyPrefList, tymyList.get(position).get(TymyPref.ONE)); if ((index == -1) || (tymyPrefList.size() == 0) || tymyPrefList.get(index).noDs()) { Toast.makeText(this, getString(R.string.no_discussion), Toast.LENGTH_LONG).show(); return; } cancelBackgroundTasks(); Bundle bundle = new Bundle(); bundle.putInt("index", index); Intent intent = new Intent(this, DiscussionListActivity.class); intent.putExtras(bundle); startActivityForResult(intent, DS_LIST_ACTIVITY); } // ************** Context menu ************** // @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MenuInflater inflater = getMenuInflater(); int index = tlu.getIndexFromUrl(tymyPrefList, tymyList.get(info.position).get(TymyPref.ONE)); if (index != -1) { menu.setHeaderTitle(tymyPrefList.get(index).getUrl()); inflater.inflate(R.menu.tymy_list_context_menu, menu); } } public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); int index = tlu.getIndexFromUrl(tymyPrefList, tymyList.get((int) info.id).get(TymyPref.ONE)); switch(item.getItemId()) { case R.id.menu_context_edit: showAddTymy(index); return true; case R.id.menu_context_delete: deleteTymy(index); return true; case R.id.menu_context_web: goToWeb(index); return true; default: return super.onContextItemSelected(item); } } private void goToWeb(int index) { String attr = new String(); if (tymyPrefList.get(index).getHttpContext() == null) { // TODO Doresit spravnou skladbu parametru v URL aby nebylo nutne prihlasovani attr = TymyLoader.getURLLoginAttr(tymyPrefList.get(index).getHttpContext()); } Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://" + tymyPrefList.get(index).getUrl() + attr)); startActivity(browserIntent); } // ***************** Setting ******************** // private void showSettings() { Intent intent = new Intent(this, GeneralSettingsActivity.class); startActivity(intent); } private void showAddTymy() { showAddTymy(-1); } private void showAddTymy(int position) { Bundle bundle = new Bundle(); bundle.putInt("position", position); Intent intent = new Intent(this, EditTymyActivity.class); intent.putExtras(bundle); startActivityForResult(intent, EDIT_TYMY_ACTIVITY); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case EDIT_TYMY_ACTIVITY: if (resultCode == RESULT_OK) { int index = data.getIntExtra("index", -1); reloadTymyDsList(index); refreshListView(); } break; case DS_LIST_ACTIVITY: if (resultCode == RESULT_OK) { int index = data.getIntExtra("index", -1); reloadTymyNewItems(index); } break; } } private void deleteTymy(int position) { app.deleteTymyCfg(tymyPrefList.get(position).getUrl()); tlu.removeTymyPref(tymyPrefList, position); app.setTymyPrefList(tymyPrefList); refreshListView(); } private void cancelBackgroundTasks() { //cancel background threads for (LoginAndUpdateTymy loader : loginAndUpdateTymy) { if (loader != null) { loader.cancel(true); } } if (updateNewItemsTymy != null) { updateNewItemsTymy.cancel(true); } } // TODO tyhle methody by meli byt v samostatny tride private void reloadTymyDsList(int index) { if (app.isOnline()) { if (index == -1) reloadTymyDsList(); int i = 0; i = loginAndUpdateTymy.size(); loginAndUpdateTymy.add(i, (LoginAndUpdateTymy) new LoginAndUpdateTymy()); loginAndUpdateTymy.get(i).execute(tymyPrefList.get(index)); app.setTymyPrefList(tymyPrefList); app.saveTymyCfg(tymyPrefList); } } private void reloadTymyDsList() { if (app.isOnline()) { // Slozitejsi pouziti copy_tymyPrefList aby se zabranilo soucasne modifikaci tymyPrefList ArrayList<TymyPref> copy_tymyPrefList = new ArrayList<TymyPref>(); for (TymyPref tP : tymyPrefList) { copy_tymyPrefList.add(tP); } int i = 0; for(TymyPref tP : copy_tymyPrefList) { i = loginAndUpdateTymy.size(); int index = copy_tymyPrefList.indexOf(tP); loginAndUpdateTymy.add(i, (LoginAndUpdateTymy) new LoginAndUpdateTymy()); loginAndUpdateTymy.get(i).execute(tP); tymyPrefList.remove(index); tymyPrefList.add(index, tP); app.setTymyPrefList(tymyPrefList); //This maybe could cause problems when due to lost connectivity the download data will be corrupted, //but next update should fix it (or refresh UI functionality) app.saveTymyCfg(tymyPrefList); } } } private void reloadTymyNewItems(int index) { if (app.isOnline()) { if (index == -1) reloadTymyNewItems(); // Slozitejsi pouziti copy_tymyPrefList aby se zabranilo soucasne modifikaci tymyPrefList updateNewItemsTymy = new UpdateNewItemsTymy(); updateNewItemsTymy.execute(tymyPrefList.get(index)); app.setTymyPrefList(tymyPrefList); refreshListView(); } } private void reloadTymyNewItems() { if (app.isOnline()) { if (updateNewItemsTymy != null) { updateNewItemsTymy.cancel(true); } updateNewItemsTymy = new UpdateNewItemsTymy(); updateNewItemsTymy.execute(tymyPrefList.toArray(new TymyPref[tymyPrefList.size()])); } } private void refreshListView() { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); String noNewItems = pref.getString(getString(R.string.no_new_items_key), getString(R.string.no_new_items_default)); // tymyPrefList = app.getTymyPrefList(); if (tymyPrefList.isEmpty()) { tlu.addMapToList(true, getString(R.string.no_tymy), getString(R.string.no_tymy_hint), tymyList); } else { tlu.updateTymyList(tymyPrefList, noNewItems, tymyList); adapter.notifyDataSetChanged(); } } //**************************************************************// //******************* AsyncTasks *****************************// private class LoginAndUpdateTymy extends AsyncTask<TymyPref, Integer, TymyPref> { @Override protected TymyPref doInBackground(TymyPref... tymyPref) { return tlu.updateTymDs(tymyPref); } @Override protected void onProgressUpdate(Integer... progress) { setProgress(progress[0]); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(TymyPref tymyPref) { // Toast.makeText(getApplicationContext(), "discussions list " + tymyPref.getUrl() + " updated" , Toast.LENGTH_SHORT).show(); refreshListView(); //save configuration app.saveTymyCfg(tymyPrefList); } } private class UpdateNewItemsTymy extends AsyncTask<TymyPref, Integer, Void> { @Override protected void onPreExecute() { pb.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(TymyPref... tymyPref) { for (TymyPref tp : tymyPref) { tlu.updateNewItems(tp); publishProgress(0); if (isCancelled()) break; } return null; } @Override protected void onProgressUpdate(Integer... progress) { setProgress(progress[0]); refreshListView(); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(Void v) { pb.setVisibility(View.GONE); } @Override protected void onCancelled() { pb.setVisibility(View.GONE); } } }
false
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tymy_list); app = (TymyReader) getApplication(); tlu = new TymyListUtil(); TymyListActivity oldState = (TymyListActivity) getLastNonConfigurationInstance(); if (oldState == null) { // activity was started => load configuration app.loadTymyCfg(); tymyPrefList = app.getTymyPrefList(); pb = (ProgressBar) findViewById(R.id.progress_bar); adapter = new SimpleAdapter(this, tymyList, R.layout.two_line_list_discs, from, to); refreshListView(); //refresh discussions from web // reloadTymyDsList(); // reload i seznamu diskusi, muze byt pomaljesi reloadTymyNewItems(); // reload pouze poctu novych prispevku } else { // Configuration was changed, reload data tymyList = oldState.tymyList; tymyPrefList = oldState.tymyPrefList; updateNewItemsTymy = oldState.updateNewItemsTymy; // pb = oldState.pb; // pb.setVisibility(oldState.pb.getVisibility()); adapter = oldState.adapter; refreshListView(); } // Set-up adapter for tymyList lv = getListView(); lv.setAdapter(adapter); registerForContextMenu(getListView()); if (!app.isOnline()) { Toast.makeText(this, R.string.no_connection, Toast.LENGTH_LONG).show(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tymy_list); app = (TymyReader) getApplication(); tlu = new TymyListUtil(); pb = (ProgressBar) findViewById(R.id.progress_bar); TymyListActivity oldState = (TymyListActivity) getLastNonConfigurationInstance(); if (oldState == null) { // activity was started => load configuration app.loadTymyCfg(); tymyPrefList = app.getTymyPrefList(); adapter = new SimpleAdapter(this, tymyList, R.layout.two_line_list_discs, from, to); refreshListView(); //refresh discussions from web // reloadTymyDsList(); // reload i seznamu diskusi, muze byt pomaljesi reloadTymyNewItems(); // reload pouze poctu novych prispevku } else { // Configuration was changed, reload data tymyList = oldState.tymyList; tymyPrefList = oldState.tymyPrefList; updateNewItemsTymy = oldState.updateNewItemsTymy; // pb = oldState.pb; // pb.setVisibility(oldState.pb.getVisibility()); adapter = oldState.adapter; refreshListView(); } // Set-up adapter for tymyList lv = getListView(); lv.setAdapter(adapter); registerForContextMenu(getListView()); if (!app.isOnline()) { Toast.makeText(this, R.string.no_connection, Toast.LENGTH_LONG).show(); } }
diff --git a/src/ru/krikun/s2e/Partition.java b/src/ru/krikun/s2e/Partition.java index 5554b8a..9f44b66 100644 --- a/src/ru/krikun/s2e/Partition.java +++ b/src/ru/krikun/s2e/Partition.java @@ -1,96 +1,99 @@ /* * Copyright (C) 2012 OlegKrikun * * 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 ru.krikun.s2e; import android.os.StatFs; import android.util.Log; import java.util.List; class Partition { private final String path; private boolean root = false; private long size = 0; private long free = 0; private long used = 0; long getFree() { return free; } long getSize() { return size; } long getUsed() { return used; } public Partition(String name) { path = "/" + name; load(); } public Partition(String name, boolean root) { this.root = root; path = "/" + name; load(); } void refresh() { size = 0; free = 0; used = 0; load(); } private void load() { if (root) loadOverShell(); else loadOverAPI(); } private void loadOverAPI() { try { StatFs statFs = new StatFs(path); long blockSize = statFs.getBlockSize(); size = (statFs.getBlockCount() * blockSize) / 1024L; free = (statFs.getAvailableBlocks() * blockSize) / 1024L; used = size - free; } catch (IllegalArgumentException er) { Log.e(App.TAG, "IllegalArgumentException"); } } private void loadOverShell() { List<String> output = App.getShell().run("busybox df " + path); if (output != null) { String[] array = output.get(1).split("\\s+"); if (array.length == 6) { - Log.e(App.TAG, "0 = " + array[0] + "; 1 = " + array[1] + "; 2 = " + array[2] + "; 3 = " + array[2] + "; 4 = " + array[4] + "; 5 = " + array[5]); - // 1 - Size; 2 - Used; 3 - Free - size = Long.parseLong(array[1]); - free = Long.parseLong(array[3]); - used = size - free; + try { + // 1 - Size; 2 - Used; 3 - Free + size = Long.parseLong(array[1]); + free = Long.parseLong(array[3]); + used = size - free; + } catch (NumberFormatException er) { + Log.e(App.TAG, "NumberFormatException in loadOverShell"); + } } } } }
true
true
private void loadOverShell() { List<String> output = App.getShell().run("busybox df " + path); if (output != null) { String[] array = output.get(1).split("\\s+"); if (array.length == 6) { Log.e(App.TAG, "0 = " + array[0] + "; 1 = " + array[1] + "; 2 = " + array[2] + "; 3 = " + array[2] + "; 4 = " + array[4] + "; 5 = " + array[5]); // 1 - Size; 2 - Used; 3 - Free size = Long.parseLong(array[1]); free = Long.parseLong(array[3]); used = size - free; } } }
private void loadOverShell() { List<String> output = App.getShell().run("busybox df " + path); if (output != null) { String[] array = output.get(1).split("\\s+"); if (array.length == 6) { try { // 1 - Size; 2 - Used; 3 - Free size = Long.parseLong(array[1]); free = Long.parseLong(array[3]); used = size - free; } catch (NumberFormatException er) { Log.e(App.TAG, "NumberFormatException in loadOverShell"); } } } }
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/setup/FirstAdministratorFormAction.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/setup/FirstAdministratorFormAction.java index 66d62b23d..65b638af3 100644 --- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/setup/FirstAdministratorFormAction.java +++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/setup/FirstAdministratorFormAction.java @@ -1,64 +1,65 @@ package edu.northwestern.bioinformatics.studycalendar.web.setup; import org.springframework.webflow.action.FormAction; import org.springframework.webflow.execution.RequestContext; import org.springframework.webflow.execution.ScopeType; import org.springframework.beans.factory.annotation.Required; import edu.northwestern.bioinformatics.studycalendar.web.CreateUserCommand; import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao; import edu.northwestern.bioinformatics.studycalendar.dao.UserDao; import edu.northwestern.bioinformatics.studycalendar.service.UserService; import edu.northwestern.bioinformatics.studycalendar.service.UserRoleService; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.nwu.bioinformatics.commons.spring.ValidatableValidator; import java.util.Map; /** * @author Rhett Sutphin */ public class FirstAdministratorFormAction extends FormAction { private SiteDao siteDao; private UserDao userDao; private UserService userService; private UserRoleService userRoleService; public FirstAdministratorFormAction() { super(CreateUserCommand.class); setFormObjectName("adminCommand"); setValidator(new ValidatableValidator()); setFormObjectScope(ScopeType.REQUEST); } protected Object createFormObject(RequestContext context) throws Exception { CreateUserCommand command = new CreateUserCommand(null, siteDao, userService, userDao, userRoleService); command.setUserActiveFlag(true); + command.setPasswordModified(true); // set sys admin role for all sites, just to be safe (there should only be one site at this point) for (Map<Role, CreateUserCommand.RoleCell> map : command.getRolesGrid().values()) { map.get(Role.SYSTEM_ADMINISTRATOR).setSelected(true); } return command; } ////// CONFIGURATION @Required public void setSiteDao(SiteDao siteDao) { this.siteDao = siteDao; } @Required public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Required public void setUserService(UserService userService) { this.userService = userService; } @Required public void setUserRoleService(UserRoleService userRoleService) { this.userRoleService = userRoleService; } }
true
true
protected Object createFormObject(RequestContext context) throws Exception { CreateUserCommand command = new CreateUserCommand(null, siteDao, userService, userDao, userRoleService); command.setUserActiveFlag(true); // set sys admin role for all sites, just to be safe (there should only be one site at this point) for (Map<Role, CreateUserCommand.RoleCell> map : command.getRolesGrid().values()) { map.get(Role.SYSTEM_ADMINISTRATOR).setSelected(true); } return command; }
protected Object createFormObject(RequestContext context) throws Exception { CreateUserCommand command = new CreateUserCommand(null, siteDao, userService, userDao, userRoleService); command.setUserActiveFlag(true); command.setPasswordModified(true); // set sys admin role for all sites, just to be safe (there should only be one site at this point) for (Map<Role, CreateUserCommand.RoleCell> map : command.getRolesGrid().values()) { map.get(Role.SYSTEM_ADMINISTRATOR).setSelected(true); } return command; }
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/logmanipulators/GZIPManipulator.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/logmanipulators/GZIPManipulator.java index 5ba6d4f8..15aa39a1 100644 --- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/logmanipulators/GZIPManipulator.java +++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/logmanipulators/GZIPManipulator.java @@ -1,85 +1,85 @@ /******************************************************************************** * CruiseControl, a Continuous Integration Toolkit * Copyright (c) 2006, ThoughtWorks, Inc. * 651 W Washington Ave. Suite 600 * Chicago, IL 60661 USA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * + Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * + Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ package net.sourceforge.cruisecontrol.logmanipulators; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import net.sourceforge.cruisecontrol.util.IO; import org.apache.log4j.Logger; public class GZIPManipulator extends BaseManipulator { private static final Logger LOG = Logger.getLogger(GZIPManipulator.class); private static final int BUFFER_SIZE = 4 * 1024; public void execute(String logDir) { File[] filesToGZip = getRelevantFiles(logDir, false); for (int i = 0; i < filesToGZip.length; i++) { File file = filesToGZip[i]; gzipFile(file, logDir); } } private void gzipFile(File logfile, String logDir) { OutputStream out = null; InputStream in = null; try { String fileName = logfile.getName() + ".gz"; out = new GZIPOutputStream( new FileOutputStream(new File(logDir, fileName))); in = new FileInputStream(logfile); int len; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = in.read(buffer)) > 0) { - out.write(buffer, 0 ,len); + out.write(buffer, 0, len); } out.flush(); logfile.delete(); } catch (IOException e) { - LOG.warn("could not gzip " + logfile.getName() + ": " +e.getMessage(), e); + LOG.warn("could not gzip " + logfile.getName() + ": " + e.getMessage(), e); } finally { IO.close(out); IO.close(in); } } }
false
true
private void gzipFile(File logfile, String logDir) { OutputStream out = null; InputStream in = null; try { String fileName = logfile.getName() + ".gz"; out = new GZIPOutputStream( new FileOutputStream(new File(logDir, fileName))); in = new FileInputStream(logfile); int len; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0 ,len); } out.flush(); logfile.delete(); } catch (IOException e) { LOG.warn("could not gzip " + logfile.getName() + ": " +e.getMessage(), e); } finally { IO.close(out); IO.close(in); } }
private void gzipFile(File logfile, String logDir) { OutputStream out = null; InputStream in = null; try { String fileName = logfile.getName() + ".gz"; out = new GZIPOutputStream( new FileOutputStream(new File(logDir, fileName))); in = new FileInputStream(logfile); int len; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); logfile.delete(); } catch (IOException e) { LOG.warn("could not gzip " + logfile.getName() + ": " + e.getMessage(), e); } finally { IO.close(out); IO.close(in); } }
diff --git a/src/net/sf/freecol/client/gui/panel/DropListener.java b/src/net/sf/freecol/client/gui/panel/DropListener.java index d2a5ad654..9ad2d58a3 100644 --- a/src/net/sf/freecol/client/gui/panel/DropListener.java +++ b/src/net/sf/freecol/client/gui/panel/DropListener.java @@ -1,43 +1,43 @@ package net.sf.freecol.client.gui.panel; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.TransferHandler; /** * A DropListener should be attached to Swing components that have a * TransferHandler attached. The DropListener will make sure that the * Swing component to which it is attached can accept dragable data. */ public final class DropListener extends MouseAdapter { public static final String COPYRIGHT = "Copyright (C) 2003 The FreeCol Team"; public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html"; public static final String REVISION = "$Revision$"; private static Logger logger = Logger.getLogger(DropListener.class.getName()); /** * Gets called when the mouse was released on a Swing component that has this * object as a MouseListener. * @param e The event that holds the information about the mouse click. */ public void mouseReleased(MouseEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipData = clipboard.getContents(clipboard); if (clipData != null) { - if (clipData.isDataFlavorSupported(DataFlavor.imageFlavor)) { + if (clipData.isDataFlavorSupported(DefaultTransferHandler.flavor)) { JComponent comp = (JComponent)e.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.importData(comp, clipData); } } } }
true
true
public void mouseReleased(MouseEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipData = clipboard.getContents(clipboard); if (clipData != null) { if (clipData.isDataFlavorSupported(DataFlavor.imageFlavor)) { JComponent comp = (JComponent)e.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.importData(comp, clipData); } } }
public void mouseReleased(MouseEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipData = clipboard.getContents(clipboard); if (clipData != null) { if (clipData.isDataFlavorSupported(DefaultTransferHandler.flavor)) { JComponent comp = (JComponent)e.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.importData(comp, clipData); } } }
diff --git a/LinphoneCoreFactoryImpl.java b/LinphoneCoreFactoryImpl.java index 3dedd06d..29f1c58c 100644 --- a/LinphoneCoreFactoryImpl.java +++ b/LinphoneCoreFactoryImpl.java @@ -1,162 +1,164 @@ /* LinphoneCoreFactoryImpl.java Copyright (C) 2010 Belledonne Communications, Grenoble, France 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.linphone.core; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.linphone.mediastream.Version; import android.util.Log; public class LinphoneCoreFactoryImpl extends LinphoneCoreFactory { private static void loadOptionalLibrary(String s) { try { System.loadLibrary(s); } catch (Throwable e) { Log.w("Unable to load optional library lib", s); } } static { // FFMPEG (audio/video) if (!hasNeonInCpuFeatures()) { loadOptionalLibrary("avutilnoneon"); loadOptionalLibrary("swscalenoneon"); loadOptionalLibrary("avcorenoneon"); loadOptionalLibrary("avcodecnoneon"); } else { loadOptionalLibrary("avutil"); loadOptionalLibrary("swscale"); loadOptionalLibrary("avcore"); loadOptionalLibrary("avcodec"); } // OPENSSL (cryptography) // lin prefix avoids collision with libs in /system/lib loadOptionalLibrary("lincrypto"); loadOptionalLibrary("linssl"); // Secure RTP and key negotiation loadOptionalLibrary("srtp"); loadOptionalLibrary("zrtpcpp"); // GPLv3+ // Tunnel loadOptionalLibrary("tunnelclient"); // g729 A implementation loadOptionalLibrary("bcg729"); //Main library if (!hasNeonInCpuFeatures()) { System.loadLibrary("linphonenoneon"); } else { System.loadLibrary("linphone"); } Version.dumpCapabilities(); } @Override public LinphoneAuthInfo createAuthInfo(String username, String password, String realm) { return new LinphoneAuthInfoImpl(username,password,realm); } @Override public LinphoneAddress createLinphoneAddress(String username, String domain, String displayName) { return new LinphoneAddressImpl(username,domain,displayName); } @Override public LinphoneAddress createLinphoneAddress(String identity) { return new LinphoneAddressImpl(identity); } @Override public LinphoneCore createLinphoneCore(LinphoneCoreListener listener, String userConfig, String factoryConfig, Object userdata) throws LinphoneCoreException { try { return new LinphoneCoreImpl(listener,new File(userConfig),new File(factoryConfig),userdata); } catch (IOException e) { throw new LinphoneCoreException("Cannot create LinphoneCore",e); } } @Override public LinphoneCore createLinphoneCore(LinphoneCoreListener listener) throws LinphoneCoreException { try { return new LinphoneCoreImpl(listener); } catch (IOException e) { throw new LinphoneCoreException("Cannot create LinphoneCore",e); } } @Override public LinphoneProxyConfig createProxyConfig(String identity, String proxy, String route, boolean enableRegister) throws LinphoneCoreException { return new LinphoneProxyConfigImpl(identity,proxy,route,enableRegister); } @Override public native void setDebugMode(boolean enable); @Override public void setLogHandler(LinphoneLogHandler handler) { //not implemented on Android } @Override public LinphoneFriend createLinphoneFriend(String friendUri) { return new LinphoneFriendImpl(friendUri); } @Override public LinphoneFriend createLinphoneFriend() { return createLinphoneFriend(null); } public static boolean hasNeonInCpuFeatures() { ProcessBuilder cmd; boolean result = false; try { String[] args = {"/system/bin/cat", "/proc/cpuinfo"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while(in.read(re) != -1){ String line = new String(re); - if (line.startsWith("Features")) + if (line.startsWith("Features")) { result = line.contains("neon"); + break; + } } in.close(); } catch(IOException ex){ ex.printStackTrace(); } return result; } }
false
true
public static boolean hasNeonInCpuFeatures() { ProcessBuilder cmd; boolean result = false; try { String[] args = {"/system/bin/cat", "/proc/cpuinfo"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while(in.read(re) != -1){ String line = new String(re); if (line.startsWith("Features")) result = line.contains("neon"); } in.close(); } catch(IOException ex){ ex.printStackTrace(); } return result; }
public static boolean hasNeonInCpuFeatures() { ProcessBuilder cmd; boolean result = false; try { String[] args = {"/system/bin/cat", "/proc/cpuinfo"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while(in.read(re) != -1){ String line = new String(re); if (line.startsWith("Features")) { result = line.contains("neon"); break; } } in.close(); } catch(IOException ex){ ex.printStackTrace(); } return result; }
diff --git a/src/de/earthdawn/ECEWorker.java b/src/de/earthdawn/ECEWorker.java index 1af19d7..65f4e8f 100644 --- a/src/de/earthdawn/ECEWorker.java +++ b/src/de/earthdawn/ECEWorker.java @@ -1,789 +1,791 @@ package de.earthdawn; /******************************************************************************\ Copyright (C) 2010-2011 Holger von Rhein <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. \******************************************************************************/ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import de.earthdawn.config.ApplicationProperties; import de.earthdawn.config.ECECapabilities; import de.earthdawn.data.*; /** * Hilfsklasse zur Verarbeitung eines Earthdawn-Charakters. * * @author lortas */ public class ECEWorker { public final ApplicationProperties PROPERTIES=ApplicationProperties.create(); public final String durabilityTalentName = PROPERTIES.getDurabilityName(); public final String questorTalentName = PROPERTIES.getQuestorTalentName(); public final ECECapabilities capabilities = new ECECapabilities(PROPERTIES.getCapabilities().getSKILLOrTALENT()); public final boolean OptionalRule_SpellLegendPointCost=PROPERTIES.getOptionalRules().getSPELLLEGENDPOINTCOST().getUsed().equals(YesnoType.YES); public final boolean OptionalRule_ShowDefaultSkills=PROPERTIES.getOptionalRules().getSHOWDEFAULTSKILLS().getUsed().equals(YesnoType.YES); public final boolean OptionalRule_QuestorTalentNeedLegendpoints=PROPERTIES.getOptionalRules().getQUESTORTALENTNEEDLEGENDPOINTS().getUsed().equals(YesnoType.YES); public final boolean OptionalRule_autoincrementDiciplinetalents=PROPERTIES.getOptionalRules().getAUTOINCREMENTDICIPLINETALENTS().getUsed().equals(YesnoType.YES); public final boolean OptionalRule_LegendpointsForAttributeIncrease=PROPERTIES.getOptionalRules().getLEGENDPOINTSFORATTRIBUTEINCREASE().getUsed().equals(YesnoType.YES); public final boolean OptionalRule_AutoInsertLegendPointSpent=PROPERTIES.getOptionalRules().getAUTOINSERTLEGENDPOINTSPENT().getUsed().equals(YesnoType.YES); private HashMap<String, ATTRIBUTEType> characterAttributes=null; CALCULATEDLEGENDPOINTSType calculatedLP = null; /** * Verabeiten eines Charakters. */ public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) { CharacterContainer character = new CharacterContainer(charakter); // Orignal berechnete LP sichern CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints(); // Berechnete LP erstmal zurücksetzen calculatedLP = character.resetCalculatedLegendpoints(); // Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter": NAMEGIVERABILITYType namegiver = character.getRace(); // Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden List<ITEMType> itemList = character.getItems(); if( itemList.isEmpty() ) { itemList.addAll(PROPERTIES.getStartingItems()); } List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList(); List<WEAPONType> weaponList = character.getWeapons(); if( weaponList.isEmpty() ) { // Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden weaponList.addAll(PROPERTIES.getStartingWeapons()); } weaponList.addAll(magicWeapons); // **ATTRIBUTE** int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints(); // Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung characterAttributes = character.getAttributes(); for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) { // Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName()); attribute.setRacevalue(raceattribute.getValue()); attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue())); int value = attribute.getRacevalue() + attribute.getGenerationvalue(); attribute.setBasevalue(value); value += attribute.getLpincrease(); attribute.setCurrentvalue(value); STEPDICEType stepdice=attribute2StepAndDice(value); attribute.setDice(stepdice.getDice()); attribute.setStep(stepdice.getStep()); karmaMaxBonus-=attribute.getCost(); if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease())); } if( karmaMaxBonus <0 ) { System.err.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus)); } // **DEFENSE** DEFENSEType defense = character.getDefence(); defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue())); defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue())); defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue())); for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) { switch (racedefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } // **INITIATIVE** STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue()); INITIATIVEType initiative = character.getInitiative(); // Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden. initiative.setModification(0); initiative.setBase(initiativeStepdice.getStep()); initiative.setStep(initiativeStepdice.getStep()); initiative.setDice(initiativeStepdice.getDice()); // **HEALTH** CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue()); DEATHType death=character.getDeath(); DEATHType unconsciousness=character.getUnconsciousness(); death.setBase(newhealth.getDeath()); death.setAdjustment(0); unconsciousness.setBase(newhealth.getUnconsciousness()); unconsciousness.setAdjustment(0); character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold()); RECOVERYType recovery = character.getRecovery(); recovery.setTestsperday(newhealth.getRecovery()); recovery.setStep(characterAttributes.get("TOU").getStep()); recovery.setDice(characterAttributes.get("TOU").getDice()); // **KARMA** TALENTType karmaritualTalent = null; final String KARMARITUAL = PROPERTIES.getKarmaritualName(); if( KARMARITUAL == null ) { System.err.println("Karmaritual talent name is not defined for selected language."); } else { for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) { if( talent.getRealigned() == 0 ) { karmaritualTalent=talent; break; } } if(karmaritualTalent == null ) { System.err.println("No Karmaritual ("+KARMARITUAL+") could be found."); } } int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus); calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP); // **MOVEMENT** character.calculateMovement(); // **CARRYING** character.calculateCarrying(); // Berechne Gewicht aller Münzen for( COINSType coins : character.getAllCoins() ) { // Mit doppelter Genauigkeit die Gewichte der Münzen addieren, double weight = 0; // Kupfermünzen: 0,5 Unze (oz) weight += coins.getCopper() / 32.0; // Silbermünzen: 0,2 Unze (oz) weight += coins.getSilver() / 80.0; // Goldmünzen: 0,1 Unze (oz) weight += coins.getGold() / 160.0; // Elementarmünzen: 0,1 Unze (oz) weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0; // zum Abspeichern langt die einfache Genaugkeit coins.setWeight((float)weight); } // ** ARMOR ** // Zu erstmal alles entfernen was nicht eine Reale Rüstung ist: List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList(); // natural ARMOR bestimmen ARMORType namegiverArmor = namegiver.getARMOR(); ARMORType naturalArmor = new ARMORType(); naturalArmor.setName(namegiverArmor.getName()); naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue())); naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor()); naturalArmor.setPenalty(namegiverArmor.getPhysicalarmor()); naturalArmor.setUsed(namegiverArmor.getUsed()); naturalArmor.setWeight(namegiverArmor.getWeight()); naturalArmor.setVirtual(YesnoType.YES); // Natürliche Rüstung der Liste voranstellen totalarmor.add(0, naturalArmor); // magischen Rüstung/Rüstungsschutz anhängen: totalarmor.addAll(character.getMagicArmor()); // Bestimme nun den aktuellen Gesamtrüstungsschutz int mysticalarmor=0; int physicalarmor=0; int protectionpenalty=0; for (ARMORType armor : totalarmor ) { if( armor.getUsed().equals(YesnoType.YES) ) { mysticalarmor+=armor.getMysticarmor(); physicalarmor+=armor.getPhysicalarmor(); protectionpenalty+=armor.getPenalty(); initiative.setModification(initiative.getModification()-armor.getPenalty()); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); } } PROTECTIONType protection = character.getProtection(); protection.setMysticarmor(mysticalarmor); protection.setPenalty(protectionpenalty); protection.setPhysicalarmor(physicalarmor); character.setAbilities(concatStrings(namegiver.getABILITY())); // Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen character.clearDisciplineBonuses(); // Stelle sicher dass ale Disziplin Talent eingügt werden character.ensureDisciplinTalentsExits(); // Entferne alle Talente die zuhohle Kreise haben. character.removeIllegalTalents(); // Entferne alle Optionalen Talente ohne Rang. character.removeZeroRankOptionalTalents(); // Prüfe ob Talente realigned weren müssen. character.realignOptionalTalents(); character.updateRealignedTalents(); HashMap<Integer,TALENTSType> allTalents = character.getAllTalentsByDisziplinOrder(); List<DISCIPLINEType> allDisciplines = character.getDisciplines(); HashMap<String,Integer> diciplineCircle = new HashMap<String,Integer>(); // Sammle alle Namensgeber spezial Talente in einer Liste zusammen HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>(); for( TALENTABILITYType t : namegiver.getTALENT() ) { namegivertalents.put(t.getName(), t); } int maxKarmaStepBonus=0; for( Integer disciplinenumber : allTalents.keySet() ) { List<TALENTType> durabilityTalents = new ArrayList<TALENTType>(); DISCIPLINEType currentDiscipline = allDisciplines.get(disciplinenumber-1); TALENTSType currentTalents = allTalents.get(disciplinenumber); for( TALENTType talent : currentTalents.getDISZIPLINETALENT() ) { RANKType rank = talent.getRANK(); if( rank == null ) { rank = new RANKType(); talent.setRANK(rank); } } HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getDISZIPLINETALENT(), true); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getOPTIONALTALENT(), false); // Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren, // werden nun den optionalen Talenten beigefügt. for( String t : namegivertalents.keySet() ) { TALENTType talent = new TALENTType(); talent.setName(namegivertalents.get(t).getName()); talent.setLimitation(namegivertalents.get(t).getLimitation()); talent.setCircle(0); enforceCapabilityParams(talent); + talent.setTEACHER(new TALENTTEACHERType()); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden for( String t : defaultOptionalTalents.keySet() ) { // Talente aus späteren Kreisen werden auch erst später eingefügt int circle = defaultOptionalTalents.get(t); if( circle > currentDiscipline.getCircle() ) continue; TALENTType talent = new TALENTType(); talent.setName(t); talent.setCircle(circle); enforceCapabilityParams(talent); + talent.setTEACHER(new TALENTTEACHERType()); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } // Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank // die Erhöhung von Todes- und Bewustlosigkeitsschwelle for( TALENTType durabilityTalent : durabilityTalents ) { DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName()); if( disziplinProperties != null ) { DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY(); int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank(); death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank)); unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank)); durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness()); } } diciplineCircle.put(currentDiscipline.getName(), currentDiscipline.getCircle()); // Nur der höchtse Bonus wird gewertet. int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline); if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus; List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS(); currentBonuses.clear(); currentBonuses.addAll(getDisciplineBonuses(currentDiscipline)); } // ** KARMA STEP ** KARMAType karma = character.getKarma(); karma.setStep(4 + maxKarmaStepBonus); // mindestens d6 karma.setDice(step2Dice(karma.getStep())); int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills(); character.removeEmptySkills(); List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL()); for( SKILLType skill : character.getSkills() ) { RANKType rank = skill.getRANK(); int startrank = rank.getStartrank(); skillsStartranks+=startrank; int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank()); int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank); rank.setLpcost(lpcostfull-lpcoststart); rank.setBonus(0); calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost()); enforceCapabilityParams(skill); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } removeIfContains(defaultSkills,skill.getName()); } calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks); // Wenn gewünscht dann zeige auch die DefaultSkills mit an if( OptionalRule_ShowDefaultSkills ) { for( CAPABILITYType defaultSkill : defaultSkills ) { SKILLType skill = new SKILLType(); RANKType rank = new RANKType(); rank.setBonus(0); rank.setLpcost(0); rank.setRank(0); skill.setRANK(rank); skill.setName(defaultSkill.getName()); skill.setLimitation(defaultSkill.getLimitation()); skill.setAction(defaultSkill.getAction()); skill.setAttribute(defaultSkill.getAttribute()); skill.setBonus(defaultSkill.getBonus()); skill.setKarma(defaultSkill.getKarma()); skill.setStrain(defaultSkill.getStrain()); skill.setDefault(defaultSkill.getDefault()); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } character.getSkills().add(skill); } } DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle); defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical()); defense.setSocial(defense.getSocial()+disciplineDefense.getSocial()); defense.setSpell(defense.getSpell()+disciplineDefense.getSpell()); initiative.setModification(initiative.getModification()+getDisciplineInitiative(diciplineCircle)); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle)); recovery.setDice(step2Dice(recovery.getStep())); // ** SPELLS ** String firstDisciplineName = ""; if( ! allDisciplines.isEmpty() ) { DISCIPLINEType firstDiscipline = allDisciplines.get(0); if( firstDiscipline != null ) firstDisciplineName=firstDiscipline.getName(); } int startingSpellLegendPointCost = 0; if( OptionalRule_SpellLegendPointCost ) { // Starting Spell can be from 1st and 2nd circle. Substact these Legendpoints from the legendpoints spend for spells ATTRIBUTEType per = characterAttributes.get("PER"); startingSpellLegendPointCost = 100 * attribute2StepAndDice(per.getBasevalue()).getStep(); int lpbonus = 0; for( int spellability : getDisciplineSpellAbility(diciplineCircle) ) { lpbonus += PROPERTIES.getCharacteristics().getSpellLP(spellability); } calculatedLP.setSpells(-lpbonus); } else { calculatedLP.setSpells(0); } HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells(); for( SPELLSType spells : character.getAllSpells() ) { if( spells.getDiscipline().equals(firstDisciplineName) && OptionalRule_SpellLegendPointCost ) { // Wenn die erste Disziplin eine Zauberdisciplin ist und die Optionale Regel, dass Zaubersprüche LP Kosten // gewählt wurde, dann reduziere die ZauberLPKosten um die StartZauber calculatedLP.setSpells(calculatedLP.getSpells()-startingSpellLegendPointCost); // Es ist jetzt schon einmal abgezogen. Stelle nun sicher dass nicht noch ein zweites Mal abgezogen werden kann. startingSpellLegendPointCost=0; } for( SPELLType spell : spells.getSPELL() ) { SPELLDEFType spelldef = spelllist.get(spell.getName()); if( spelldef == null ) { System.err.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour."); } else { spell.setCastingdifficulty(spelldef.getCastingdifficulty()); spell.setDuration(spelldef.getDuration()); spell.setEffect(spelldef.getEffect()); spell.setEffectarea(spelldef.getEffectarea()); spell.setRange(spelldef.getRange()); spell.setReattuningdifficulty(spelldef.getReattuningdifficulty()); spell.setThreads(spelldef.getThreads()); spell.setWeavingdifficulty(spelldef.getWeavingdifficulty()); } if( OptionalRule_SpellLegendPointCost ) { // The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle()); calculatedLP.setSpells(calculatedLP.getSpells()+lpcost); } } } for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) { if( item.getUsed().equals(YesnoType.YES) ) { death.setAdjustment(death.getAdjustment()-item.getBlooddamage()); unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage()); } } for( THREADITEMType item : character.getThreadItem() ) { for( int rank=0; rank<item.getWeaventhreadrank(); rank++ ) { THREADRANKType threadrank = item.getTHREADRANK().get(rank); if( threadrank == null ) { System.err.println("Undefined Threadrank for "+item.getName()+" for rank "+rank ); continue; } for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) { switch (itemdefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) { String limitation = itemtalent.getLimitation(); boolean notfound=true; for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) { if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) { notfound=false; RANKType talentrank = talent.getRANK(); talentrank.setBonus(talentrank.getBonus()+1); calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value())); } } if( notfound ) { if( limitation.isEmpty() ) limitation ="(#)"; else limitation += " (#)"; TALENTType bonusTalent = new TALENTType(); bonusTalent.setName(itemtalent.getName()); bonusTalent.setLimitation(limitation); bonusTalent.setCircle(0); enforceCapabilityParams(bonusTalent); RANKType bonusrank = new RANKType(); bonusrank.setRank(0); bonusrank.setBonus(1); calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value())); bonusTalent.setRANK(bonusrank); TALENTTEACHERType teacher = new TALENTTEACHERType(); teacher.setByversatility(YesnoType.NO); teacher.setTalentcircle(rank); teacher.setTeachercircle(rank); teacher.setName(item.getName()); bonusTalent.setTEACHER(teacher); allTalents.get(1).getOPTIONALTALENT().add(bonusTalent); } } for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) { initiative.setModification(initiative.getModification()+iteminitiative.getCount()); } initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); // TODO: other effects of MagicItems } // TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT(); } // Veränderungen am death/unconsciousness adjustment sollen beachtet werden death.setValue(death.getBase()+death.getAdjustment()); unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment()); if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0); calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+ calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+ calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks()); if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP); character.calculateLegendPointsAndStatus(); character.calculateDevotionPoints(); return charakter; } private void calculateTalents(HashMap<String, TALENTABILITYType> namegivertalents, HashMap<String, Integer> defaultOptionalTalents, int disciplinenumber, int disciplinecircle, List<TALENTType> durabilityTalents, List<TALENTType> talents, boolean disTalents) { int totallpcost=0; int startranks=calculatedLP.getUSEDSTARTRANKS().getTalents(); for( TALENTType talent : talents ) { TALENTTEACHERType teacher = talent.getTEACHER(); if( teacher == null ) { teacher = new TALENTTEACHERType(); talent.setTEACHER(teacher); } RANKType rank = talent.getRANK(); if( rank == null ) { rank = new RANKType(); talent.setRANK(rank); } if( disTalents && OptionalRule_autoincrementDiciplinetalents && (talent.getCircle() < disciplinecircle) && (rank.getRank() < disciplinecircle) ) { rank.setRank(disciplinecircle); } if( rank.getRank() < rank.getStartrank() ) rank.setRank(rank.getStartrank()); if( rank.getRank() < rank.getRealignedrank() ) rank.setRank(rank.getRealignedrank()); rank.setBonus(0); enforceCapabilityParams(talent); final int lpcostfull=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getRank()); final int lpcoststart=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getStartrank()); final int lpcostrealigned=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getRealignedrank()); if( lpcostrealigned > lpcoststart ) { rank.setLpcost(lpcostfull-lpcostrealigned); } else { rank.setLpcost(lpcostfull-lpcoststart); } totallpcost+=rank.getLpcost(); startranks+=rank.getStartrank(); ATTRIBUTENameType attr = talent.getAttribute(); if( attr != null ) calculateCapabilityRank(rank,characterAttributes.get(attr.value())); if( talent.getName().equals(durabilityTalentName)) durabilityTalents.add(talent); calculateKnacks(disciplinenumber, talent, rank.getRank()); if( namegivertalents.containsKey(talent.getName()) ) { namegivertalents.remove(talent.getName()); } if( defaultOptionalTalents.containsKey(talent.getName()) ) { defaultOptionalTalents.remove(talent.getName()); } } calculatedLP.getUSEDSTARTRANKS().setTalents(startranks); if( disTalents ) { calculatedLP.setDisciplinetalents(calculatedLP.getDisciplinetalents()+totallpcost); } else { calculatedLP.setOptionaltalents(calculatedLP.getOptionaltalents()+totallpcost); } } public static void removeIfContains(List<CAPABILITYType> defaultSkills, String name) { List<CAPABILITYType> remove = new ArrayList<CAPABILITYType>(); for( CAPABILITYType skill : defaultSkills) { if( skill.getName().equals(name)) { remove.add(skill); } } defaultSkills.removeAll(remove); } public static String concatStrings(List<String> strings) { String result = ""; for ( String s : strings ) { if( ! result.isEmpty() ) result += ", "; result += s; } return result; } private static int calculateKarma(KARMAType karma, TALENTType karmaritualTalent, int karmaModifier, int karmaMaxBonus) { karma.setMaxmodificator(karmaMaxBonus); if( (karmaritualTalent != null) && (karmaritualTalent.getRANK() != null) ) { karma.setMax( karmaMaxBonus + (karmaModifier * karmaritualTalent.getRANK().getRank()) ); } else { System.err.println("No karmaritual talent found, skipping maximal karma calculation."); } List<Integer> k = CharacterContainer.calculateAccounting(karma.getKARMAPOINTS()); karma.setCurrent(k.get(0)-k.get(1)); return 10*k.get(0); // KarmaLP } private void calculateKnacks(int disciplinenumber, TALENTType talent, int rank) { for( KNACKType knack : talent.getKNACK() ) { if( knack.getMinrank() > rank ) { System.err.println("The rank of the talent '"+talent.getName()+"' is lower than the minimal rank for the kack '"+knack.getName()+"': " +rank+" vs. "+knack.getMinrank()); } int lp = PROPERTIES.getCharacteristics().getTalentRankLPIncreaseTable(disciplinenumber,talent.getCircle()).get(knack.getMinrank()).getCost(); calculatedLP.setKnacks(calculatedLP.getKnacks()+lp); } } private static int getDisciplineKarmaStepBonus(DISCIPLINEType discipline) { int result = 0; int circlenr=0; DISCIPLINE disziplinProperties = ApplicationProperties.create().getDisziplin(discipline.getName()); if( disziplinProperties == null ) return result; for( DISCIPLINECIRCLEType circle : disziplinProperties.getCIRCLE()) { circlenr++; if( circlenr > discipline.getCircle() ) break; for( DISZIPINABILITYType karmastep : circle.getKARMASTEP()) { result += karmastep.getCount(); } } return result; } private static int getDisciplineRecoveryTestBonus(HashMap<String,Integer> diciplineCircle) { int result = 0; for( String discipline : diciplineCircle.keySet() ) { DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline); if( d == null ) continue; int tmp = 0; int circlenr=0; for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) { circlenr++; if( circlenr > diciplineCircle.get(discipline) ) break; for( DISZIPINABILITYType recoverytest : circle.getRECOVERYTEST() ) { tmp += recoverytest.getCount(); } } if( tmp > result ) result=tmp; } return result; } private static int getDisciplineInitiative(HashMap<String,Integer> diciplineCircle) { int result = 0; for( String discipline : diciplineCircle.keySet() ) { DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline); if( d == null ) continue; int tmp = 0; int circlenr=0; for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) { circlenr++; if( circlenr > diciplineCircle.get(discipline) ) break; for( DISZIPINABILITYType initiative : circle.getINITIATIVE() ) { tmp += initiative.getCount(); } } if( tmp > result ) result=tmp; } return result; } // Der Defense Bonus wird nicht über Alle Disziplinen addiert, sondern // der Character erhält von des Disziplinen nur den jeweils höchsten DefenseBonus private static DEFENSEType getDisciplineDefense(HashMap<String,Integer> diciplineCircle) { DEFENSEType result = new DEFENSEType(); result.setPhysical(0); result.setSocial(0); result.setSpell(0); for( String discipline : diciplineCircle.keySet() ) { DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline); if( d == null ) continue; DEFENSEType tmp = new DEFENSEType(); tmp.setPhysical(0); tmp.setSocial(0); tmp.setSpell(0); int circlenr = 0; for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) { circlenr++; if( circlenr > diciplineCircle.get(discipline) ) break; for( DEFENSEABILITYType defense : circle.getDEFENSE() ) { switch( defense.getKind() ) { case PHYSICAL: tmp.setPhysical(tmp.getPhysical()+1); break; case SOCIAL: tmp.setSocial(tmp.getSocial()+1); break; case SPELL: tmp.setSpell(tmp.getSpell()+1); break; } } } if( tmp.getPhysical() > result.getPhysical() ) result.setPhysical(tmp.getPhysical()); if( tmp.getSocial() > result.getSocial() ) result.setSocial(tmp.getSocial()); if( tmp.getSpell() > result.getSpell() ) result.setSpell(tmp.getSpell()); } return result; } private static List<Integer> getDisciplineSpellAbility(HashMap<String,Integer> diciplineCircle) { List<Integer> result = new ArrayList<Integer>(); for( String discipline : diciplineCircle.keySet() ) { DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline); if( d == null ) continue; int circlenr = 0; for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) { circlenr++; for( DISZIPINABILITYType spell : circle.getSPELLABILITY() ) { for(int i=0; i<spell.getCount(); i++) result.add(circlenr); } } } return result; } public static int berechneWiederstandskraft(int value) { int defense=0; for (CHARACTERISTICSDEFENSERAITING defenserating : ApplicationProperties.create().getCharacteristics().getDEFENSERAITING() ) { // System.err.println("berechneWiederstandskraft value "+value+" defense "+defense+" defenserating "+defenserating.getAttribute()); if( (value >= defenserating.getAttribute()) && (defense<defenserating.getDefense()) ) { defense=defenserating.getDefense(); } } return defense; } public static int berechneAttriubteCost(int modifier) { if ( modifier < -2 ) { System.err.println("The generation attribute value was to low. Value will increased to -2."); modifier = -2; } if ( modifier > 8 ) { System.err.println("The generation attribute value was to high. Value will be lower down to 8."); modifier = 8; } HashMap<Integer,Integer> attributecost = ApplicationProperties.create().getCharacteristics().getATTRIBUTECOST(); return attributecost.get(modifier); } public static CHARACTERISTICSHEALTHRATING bestimmeHealth(int value) { HashMap<Integer,CHARACTERISTICSHEALTHRATING> healthrating = ApplicationProperties.create().getCharacteristics().getHEALTHRATING(); return healthrating.get(value); } public static int berechneMysticArmor(int value) { List<Integer> mysticArmorTable = ApplicationProperties.create().getCharacteristics().getMYSTICARMOR(); int mysticArmor=-1; for( int attribute : mysticArmorTable ) { if( attribute > value ) break; mysticArmor++; } return mysticArmor; } public static STEPDICEType attribute2StepAndDice(int value) { while( value >= 0 ) { CHARACTERISTICSSTEPDICETABLE result = ApplicationProperties.create().getCharacteristics().getSTEPDICEbyAttribute(value); if( result != null ) { return result; } value--; } // Not found return null; } public static DiceType step2Dice(int value) { return ApplicationProperties.create().getCharacteristics().getSTEPDICEbyStep(value).getDice(); } public void calculateCapabilityRank(RANKType talentRank, ATTRIBUTEType attr) { if( attr == null ) { talentRank.setStep(talentRank.getRank()+talentRank.getBonus()); } else { talentRank.setStep(talentRank.getRank()+talentRank.getBonus()+attr.getStep()); } talentRank.setDice(step2Dice(talentRank.getStep())); } private void enforceCapabilityParams(CAPABILITYType capability) { CAPABILITYType replacment = null; if( capability instanceof TALENTType ) { replacment=capabilities.getTalent(capability.getName()); } else { replacment=capabilities.getSkill(capability.getName()); } if( replacment == null ) { System.err.println("Capability '"+capability.getName()+"' not found : "+capability.getClass().getSimpleName()); } else { capability.setAction(replacment.getAction()); capability.setAttribute(replacment.getAttribute()); capability.setBonus(replacment.getBonus()); capability.setKarma(replacment.getKarma()); capability.setStrain(replacment.getStrain()); capability.setBookref(replacment.getBookref()); } } public static List<DISCIPLINEBONUSType> getDisciplineBonuses(DISCIPLINEType discipline) { List<DISCIPLINEBONUSType> bonuses = new ArrayList<DISCIPLINEBONUSType>(); int circlenr=0; DISCIPLINE disziplinProperties = ApplicationProperties.create().getDisziplin(discipline.getName()); if( disziplinProperties == null ) return bonuses; for(DISCIPLINECIRCLEType circle : disziplinProperties.getCIRCLE()) { circlenr++; if( circlenr > discipline.getCircle() ) break; for( KARMAABILITYType karma : circle.getKARMA() ) { DISCIPLINEBONUSType bonus = new DISCIPLINEBONUSType(); bonus.setCircle(circlenr); bonus.setBonus("Can spend Karma for "+karma.getSpend()); bonuses.add(bonus); } for( String ability : circle.getABILITY() ) { DISCIPLINEBONUSType bonus = new DISCIPLINEBONUSType(); bonus.setCircle(circlenr); bonus.setBonus("Ability: "+ability); bonuses.add(bonus); } } return bonuses; } }
false
true
public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) { CharacterContainer character = new CharacterContainer(charakter); // Orignal berechnete LP sichern CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints(); // Berechnete LP erstmal zurücksetzen calculatedLP = character.resetCalculatedLegendpoints(); // Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter": NAMEGIVERABILITYType namegiver = character.getRace(); // Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden List<ITEMType> itemList = character.getItems(); if( itemList.isEmpty() ) { itemList.addAll(PROPERTIES.getStartingItems()); } List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList(); List<WEAPONType> weaponList = character.getWeapons(); if( weaponList.isEmpty() ) { // Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden weaponList.addAll(PROPERTIES.getStartingWeapons()); } weaponList.addAll(magicWeapons); // **ATTRIBUTE** int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints(); // Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung characterAttributes = character.getAttributes(); for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) { // Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName()); attribute.setRacevalue(raceattribute.getValue()); attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue())); int value = attribute.getRacevalue() + attribute.getGenerationvalue(); attribute.setBasevalue(value); value += attribute.getLpincrease(); attribute.setCurrentvalue(value); STEPDICEType stepdice=attribute2StepAndDice(value); attribute.setDice(stepdice.getDice()); attribute.setStep(stepdice.getStep()); karmaMaxBonus-=attribute.getCost(); if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease())); } if( karmaMaxBonus <0 ) { System.err.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus)); } // **DEFENSE** DEFENSEType defense = character.getDefence(); defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue())); defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue())); defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue())); for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) { switch (racedefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } // **INITIATIVE** STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue()); INITIATIVEType initiative = character.getInitiative(); // Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden. initiative.setModification(0); initiative.setBase(initiativeStepdice.getStep()); initiative.setStep(initiativeStepdice.getStep()); initiative.setDice(initiativeStepdice.getDice()); // **HEALTH** CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue()); DEATHType death=character.getDeath(); DEATHType unconsciousness=character.getUnconsciousness(); death.setBase(newhealth.getDeath()); death.setAdjustment(0); unconsciousness.setBase(newhealth.getUnconsciousness()); unconsciousness.setAdjustment(0); character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold()); RECOVERYType recovery = character.getRecovery(); recovery.setTestsperday(newhealth.getRecovery()); recovery.setStep(characterAttributes.get("TOU").getStep()); recovery.setDice(characterAttributes.get("TOU").getDice()); // **KARMA** TALENTType karmaritualTalent = null; final String KARMARITUAL = PROPERTIES.getKarmaritualName(); if( KARMARITUAL == null ) { System.err.println("Karmaritual talent name is not defined for selected language."); } else { for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) { if( talent.getRealigned() == 0 ) { karmaritualTalent=talent; break; } } if(karmaritualTalent == null ) { System.err.println("No Karmaritual ("+KARMARITUAL+") could be found."); } } int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus); calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP); // **MOVEMENT** character.calculateMovement(); // **CARRYING** character.calculateCarrying(); // Berechne Gewicht aller Münzen for( COINSType coins : character.getAllCoins() ) { // Mit doppelter Genauigkeit die Gewichte der Münzen addieren, double weight = 0; // Kupfermünzen: 0,5 Unze (oz) weight += coins.getCopper() / 32.0; // Silbermünzen: 0,2 Unze (oz) weight += coins.getSilver() / 80.0; // Goldmünzen: 0,1 Unze (oz) weight += coins.getGold() / 160.0; // Elementarmünzen: 0,1 Unze (oz) weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0; // zum Abspeichern langt die einfache Genaugkeit coins.setWeight((float)weight); } // ** ARMOR ** // Zu erstmal alles entfernen was nicht eine Reale Rüstung ist: List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList(); // natural ARMOR bestimmen ARMORType namegiverArmor = namegiver.getARMOR(); ARMORType naturalArmor = new ARMORType(); naturalArmor.setName(namegiverArmor.getName()); naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue())); naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor()); naturalArmor.setPenalty(namegiverArmor.getPhysicalarmor()); naturalArmor.setUsed(namegiverArmor.getUsed()); naturalArmor.setWeight(namegiverArmor.getWeight()); naturalArmor.setVirtual(YesnoType.YES); // Natürliche Rüstung der Liste voranstellen totalarmor.add(0, naturalArmor); // magischen Rüstung/Rüstungsschutz anhängen: totalarmor.addAll(character.getMagicArmor()); // Bestimme nun den aktuellen Gesamtrüstungsschutz int mysticalarmor=0; int physicalarmor=0; int protectionpenalty=0; for (ARMORType armor : totalarmor ) { if( armor.getUsed().equals(YesnoType.YES) ) { mysticalarmor+=armor.getMysticarmor(); physicalarmor+=armor.getPhysicalarmor(); protectionpenalty+=armor.getPenalty(); initiative.setModification(initiative.getModification()-armor.getPenalty()); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); } } PROTECTIONType protection = character.getProtection(); protection.setMysticarmor(mysticalarmor); protection.setPenalty(protectionpenalty); protection.setPhysicalarmor(physicalarmor); character.setAbilities(concatStrings(namegiver.getABILITY())); // Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen character.clearDisciplineBonuses(); // Stelle sicher dass ale Disziplin Talent eingügt werden character.ensureDisciplinTalentsExits(); // Entferne alle Talente die zuhohle Kreise haben. character.removeIllegalTalents(); // Entferne alle Optionalen Talente ohne Rang. character.removeZeroRankOptionalTalents(); // Prüfe ob Talente realigned weren müssen. character.realignOptionalTalents(); character.updateRealignedTalents(); HashMap<Integer,TALENTSType> allTalents = character.getAllTalentsByDisziplinOrder(); List<DISCIPLINEType> allDisciplines = character.getDisciplines(); HashMap<String,Integer> diciplineCircle = new HashMap<String,Integer>(); // Sammle alle Namensgeber spezial Talente in einer Liste zusammen HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>(); for( TALENTABILITYType t : namegiver.getTALENT() ) { namegivertalents.put(t.getName(), t); } int maxKarmaStepBonus=0; for( Integer disciplinenumber : allTalents.keySet() ) { List<TALENTType> durabilityTalents = new ArrayList<TALENTType>(); DISCIPLINEType currentDiscipline = allDisciplines.get(disciplinenumber-1); TALENTSType currentTalents = allTalents.get(disciplinenumber); for( TALENTType talent : currentTalents.getDISZIPLINETALENT() ) { RANKType rank = talent.getRANK(); if( rank == null ) { rank = new RANKType(); talent.setRANK(rank); } } HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getDISZIPLINETALENT(), true); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getOPTIONALTALENT(), false); // Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren, // werden nun den optionalen Talenten beigefügt. for( String t : namegivertalents.keySet() ) { TALENTType talent = new TALENTType(); talent.setName(namegivertalents.get(t).getName()); talent.setLimitation(namegivertalents.get(t).getLimitation()); talent.setCircle(0); enforceCapabilityParams(talent); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden for( String t : defaultOptionalTalents.keySet() ) { // Talente aus späteren Kreisen werden auch erst später eingefügt int circle = defaultOptionalTalents.get(t); if( circle > currentDiscipline.getCircle() ) continue; TALENTType talent = new TALENTType(); talent.setName(t); talent.setCircle(circle); enforceCapabilityParams(talent); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } // Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank // die Erhöhung von Todes- und Bewustlosigkeitsschwelle for( TALENTType durabilityTalent : durabilityTalents ) { DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName()); if( disziplinProperties != null ) { DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY(); int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank(); death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank)); unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank)); durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness()); } } diciplineCircle.put(currentDiscipline.getName(), currentDiscipline.getCircle()); // Nur der höchtse Bonus wird gewertet. int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline); if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus; List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS(); currentBonuses.clear(); currentBonuses.addAll(getDisciplineBonuses(currentDiscipline)); } // ** KARMA STEP ** KARMAType karma = character.getKarma(); karma.setStep(4 + maxKarmaStepBonus); // mindestens d6 karma.setDice(step2Dice(karma.getStep())); int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills(); character.removeEmptySkills(); List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL()); for( SKILLType skill : character.getSkills() ) { RANKType rank = skill.getRANK(); int startrank = rank.getStartrank(); skillsStartranks+=startrank; int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank()); int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank); rank.setLpcost(lpcostfull-lpcoststart); rank.setBonus(0); calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost()); enforceCapabilityParams(skill); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } removeIfContains(defaultSkills,skill.getName()); } calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks); // Wenn gewünscht dann zeige auch die DefaultSkills mit an if( OptionalRule_ShowDefaultSkills ) { for( CAPABILITYType defaultSkill : defaultSkills ) { SKILLType skill = new SKILLType(); RANKType rank = new RANKType(); rank.setBonus(0); rank.setLpcost(0); rank.setRank(0); skill.setRANK(rank); skill.setName(defaultSkill.getName()); skill.setLimitation(defaultSkill.getLimitation()); skill.setAction(defaultSkill.getAction()); skill.setAttribute(defaultSkill.getAttribute()); skill.setBonus(defaultSkill.getBonus()); skill.setKarma(defaultSkill.getKarma()); skill.setStrain(defaultSkill.getStrain()); skill.setDefault(defaultSkill.getDefault()); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } character.getSkills().add(skill); } } DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle); defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical()); defense.setSocial(defense.getSocial()+disciplineDefense.getSocial()); defense.setSpell(defense.getSpell()+disciplineDefense.getSpell()); initiative.setModification(initiative.getModification()+getDisciplineInitiative(diciplineCircle)); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle)); recovery.setDice(step2Dice(recovery.getStep())); // ** SPELLS ** String firstDisciplineName = ""; if( ! allDisciplines.isEmpty() ) { DISCIPLINEType firstDiscipline = allDisciplines.get(0); if( firstDiscipline != null ) firstDisciplineName=firstDiscipline.getName(); } int startingSpellLegendPointCost = 0; if( OptionalRule_SpellLegendPointCost ) { // Starting Spell can be from 1st and 2nd circle. Substact these Legendpoints from the legendpoints spend for spells ATTRIBUTEType per = characterAttributes.get("PER"); startingSpellLegendPointCost = 100 * attribute2StepAndDice(per.getBasevalue()).getStep(); int lpbonus = 0; for( int spellability : getDisciplineSpellAbility(diciplineCircle) ) { lpbonus += PROPERTIES.getCharacteristics().getSpellLP(spellability); } calculatedLP.setSpells(-lpbonus); } else { calculatedLP.setSpells(0); } HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells(); for( SPELLSType spells : character.getAllSpells() ) { if( spells.getDiscipline().equals(firstDisciplineName) && OptionalRule_SpellLegendPointCost ) { // Wenn die erste Disziplin eine Zauberdisciplin ist und die Optionale Regel, dass Zaubersprüche LP Kosten // gewählt wurde, dann reduziere die ZauberLPKosten um die StartZauber calculatedLP.setSpells(calculatedLP.getSpells()-startingSpellLegendPointCost); // Es ist jetzt schon einmal abgezogen. Stelle nun sicher dass nicht noch ein zweites Mal abgezogen werden kann. startingSpellLegendPointCost=0; } for( SPELLType spell : spells.getSPELL() ) { SPELLDEFType spelldef = spelllist.get(spell.getName()); if( spelldef == null ) { System.err.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour."); } else { spell.setCastingdifficulty(spelldef.getCastingdifficulty()); spell.setDuration(spelldef.getDuration()); spell.setEffect(spelldef.getEffect()); spell.setEffectarea(spelldef.getEffectarea()); spell.setRange(spelldef.getRange()); spell.setReattuningdifficulty(spelldef.getReattuningdifficulty()); spell.setThreads(spelldef.getThreads()); spell.setWeavingdifficulty(spelldef.getWeavingdifficulty()); } if( OptionalRule_SpellLegendPointCost ) { // The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle()); calculatedLP.setSpells(calculatedLP.getSpells()+lpcost); } } } for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) { if( item.getUsed().equals(YesnoType.YES) ) { death.setAdjustment(death.getAdjustment()-item.getBlooddamage()); unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage()); } } for( THREADITEMType item : character.getThreadItem() ) { for( int rank=0; rank<item.getWeaventhreadrank(); rank++ ) { THREADRANKType threadrank = item.getTHREADRANK().get(rank); if( threadrank == null ) { System.err.println("Undefined Threadrank for "+item.getName()+" for rank "+rank ); continue; } for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) { switch (itemdefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) { String limitation = itemtalent.getLimitation(); boolean notfound=true; for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) { if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) { notfound=false; RANKType talentrank = talent.getRANK(); talentrank.setBonus(talentrank.getBonus()+1); calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value())); } } if( notfound ) { if( limitation.isEmpty() ) limitation ="(#)"; else limitation += " (#)"; TALENTType bonusTalent = new TALENTType(); bonusTalent.setName(itemtalent.getName()); bonusTalent.setLimitation(limitation); bonusTalent.setCircle(0); enforceCapabilityParams(bonusTalent); RANKType bonusrank = new RANKType(); bonusrank.setRank(0); bonusrank.setBonus(1); calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value())); bonusTalent.setRANK(bonusrank); TALENTTEACHERType teacher = new TALENTTEACHERType(); teacher.setByversatility(YesnoType.NO); teacher.setTalentcircle(rank); teacher.setTeachercircle(rank); teacher.setName(item.getName()); bonusTalent.setTEACHER(teacher); allTalents.get(1).getOPTIONALTALENT().add(bonusTalent); } } for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) { initiative.setModification(initiative.getModification()+iteminitiative.getCount()); } initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); // TODO: other effects of MagicItems } // TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT(); } // Veränderungen am death/unconsciousness adjustment sollen beachtet werden death.setValue(death.getBase()+death.getAdjustment()); unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment()); if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0); calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+ calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+ calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks()); if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP); character.calculateLegendPointsAndStatus(); character.calculateDevotionPoints(); return charakter; }
public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) { CharacterContainer character = new CharacterContainer(charakter); // Orignal berechnete LP sichern CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints(); // Berechnete LP erstmal zurücksetzen calculatedLP = character.resetCalculatedLegendpoints(); // Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter": NAMEGIVERABILITYType namegiver = character.getRace(); // Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden List<ITEMType> itemList = character.getItems(); if( itemList.isEmpty() ) { itemList.addAll(PROPERTIES.getStartingItems()); } List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList(); List<WEAPONType> weaponList = character.getWeapons(); if( weaponList.isEmpty() ) { // Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden weaponList.addAll(PROPERTIES.getStartingWeapons()); } weaponList.addAll(magicWeapons); // **ATTRIBUTE** int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints(); // Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung characterAttributes = character.getAttributes(); for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) { // Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName()); attribute.setRacevalue(raceattribute.getValue()); attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue())); int value = attribute.getRacevalue() + attribute.getGenerationvalue(); attribute.setBasevalue(value); value += attribute.getLpincrease(); attribute.setCurrentvalue(value); STEPDICEType stepdice=attribute2StepAndDice(value); attribute.setDice(stepdice.getDice()); attribute.setStep(stepdice.getStep()); karmaMaxBonus-=attribute.getCost(); if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease())); } if( karmaMaxBonus <0 ) { System.err.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus)); } // **DEFENSE** DEFENSEType defense = character.getDefence(); defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue())); defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue())); defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue())); for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) { switch (racedefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } // **INITIATIVE** STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue()); INITIATIVEType initiative = character.getInitiative(); // Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden. initiative.setModification(0); initiative.setBase(initiativeStepdice.getStep()); initiative.setStep(initiativeStepdice.getStep()); initiative.setDice(initiativeStepdice.getDice()); // **HEALTH** CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue()); DEATHType death=character.getDeath(); DEATHType unconsciousness=character.getUnconsciousness(); death.setBase(newhealth.getDeath()); death.setAdjustment(0); unconsciousness.setBase(newhealth.getUnconsciousness()); unconsciousness.setAdjustment(0); character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold()); RECOVERYType recovery = character.getRecovery(); recovery.setTestsperday(newhealth.getRecovery()); recovery.setStep(characterAttributes.get("TOU").getStep()); recovery.setDice(characterAttributes.get("TOU").getDice()); // **KARMA** TALENTType karmaritualTalent = null; final String KARMARITUAL = PROPERTIES.getKarmaritualName(); if( KARMARITUAL == null ) { System.err.println("Karmaritual talent name is not defined for selected language."); } else { for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) { if( talent.getRealigned() == 0 ) { karmaritualTalent=talent; break; } } if(karmaritualTalent == null ) { System.err.println("No Karmaritual ("+KARMARITUAL+") could be found."); } } int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus); calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP); // **MOVEMENT** character.calculateMovement(); // **CARRYING** character.calculateCarrying(); // Berechne Gewicht aller Münzen for( COINSType coins : character.getAllCoins() ) { // Mit doppelter Genauigkeit die Gewichte der Münzen addieren, double weight = 0; // Kupfermünzen: 0,5 Unze (oz) weight += coins.getCopper() / 32.0; // Silbermünzen: 0,2 Unze (oz) weight += coins.getSilver() / 80.0; // Goldmünzen: 0,1 Unze (oz) weight += coins.getGold() / 160.0; // Elementarmünzen: 0,1 Unze (oz) weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0; // zum Abspeichern langt die einfache Genaugkeit coins.setWeight((float)weight); } // ** ARMOR ** // Zu erstmal alles entfernen was nicht eine Reale Rüstung ist: List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList(); // natural ARMOR bestimmen ARMORType namegiverArmor = namegiver.getARMOR(); ARMORType naturalArmor = new ARMORType(); naturalArmor.setName(namegiverArmor.getName()); naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue())); naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor()); naturalArmor.setPenalty(namegiverArmor.getPhysicalarmor()); naturalArmor.setUsed(namegiverArmor.getUsed()); naturalArmor.setWeight(namegiverArmor.getWeight()); naturalArmor.setVirtual(YesnoType.YES); // Natürliche Rüstung der Liste voranstellen totalarmor.add(0, naturalArmor); // magischen Rüstung/Rüstungsschutz anhängen: totalarmor.addAll(character.getMagicArmor()); // Bestimme nun den aktuellen Gesamtrüstungsschutz int mysticalarmor=0; int physicalarmor=0; int protectionpenalty=0; for (ARMORType armor : totalarmor ) { if( armor.getUsed().equals(YesnoType.YES) ) { mysticalarmor+=armor.getMysticarmor(); physicalarmor+=armor.getPhysicalarmor(); protectionpenalty+=armor.getPenalty(); initiative.setModification(initiative.getModification()-armor.getPenalty()); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); } } PROTECTIONType protection = character.getProtection(); protection.setMysticarmor(mysticalarmor); protection.setPenalty(protectionpenalty); protection.setPhysicalarmor(physicalarmor); character.setAbilities(concatStrings(namegiver.getABILITY())); // Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen character.clearDisciplineBonuses(); // Stelle sicher dass ale Disziplin Talent eingügt werden character.ensureDisciplinTalentsExits(); // Entferne alle Talente die zuhohle Kreise haben. character.removeIllegalTalents(); // Entferne alle Optionalen Talente ohne Rang. character.removeZeroRankOptionalTalents(); // Prüfe ob Talente realigned weren müssen. character.realignOptionalTalents(); character.updateRealignedTalents(); HashMap<Integer,TALENTSType> allTalents = character.getAllTalentsByDisziplinOrder(); List<DISCIPLINEType> allDisciplines = character.getDisciplines(); HashMap<String,Integer> diciplineCircle = new HashMap<String,Integer>(); // Sammle alle Namensgeber spezial Talente in einer Liste zusammen HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>(); for( TALENTABILITYType t : namegiver.getTALENT() ) { namegivertalents.put(t.getName(), t); } int maxKarmaStepBonus=0; for( Integer disciplinenumber : allTalents.keySet() ) { List<TALENTType> durabilityTalents = new ArrayList<TALENTType>(); DISCIPLINEType currentDiscipline = allDisciplines.get(disciplinenumber-1); TALENTSType currentTalents = allTalents.get(disciplinenumber); for( TALENTType talent : currentTalents.getDISZIPLINETALENT() ) { RANKType rank = talent.getRANK(); if( rank == null ) { rank = new RANKType(); talent.setRANK(rank); } } HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getDISZIPLINETALENT(), true); calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentDiscipline.getCircle(), durabilityTalents, currentTalents.getOPTIONALTALENT(), false); // Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren, // werden nun den optionalen Talenten beigefügt. for( String t : namegivertalents.keySet() ) { TALENTType talent = new TALENTType(); talent.setName(namegivertalents.get(t).getName()); talent.setLimitation(namegivertalents.get(t).getLimitation()); talent.setCircle(0); enforceCapabilityParams(talent); talent.setTEACHER(new TALENTTEACHERType()); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden for( String t : defaultOptionalTalents.keySet() ) { // Talente aus späteren Kreisen werden auch erst später eingefügt int circle = defaultOptionalTalents.get(t); if( circle > currentDiscipline.getCircle() ) continue; TALENTType talent = new TALENTType(); talent.setName(t); talent.setCircle(circle); enforceCapabilityParams(talent); talent.setTEACHER(new TALENTTEACHERType()); RANKType rank = new RANKType(); calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value())); talent.setRANK(rank); currentTalents.getOPTIONALTALENT().add(talent); } // Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank // die Erhöhung von Todes- und Bewustlosigkeitsschwelle for( TALENTType durabilityTalent : durabilityTalents ) { DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName()); if( disziplinProperties != null ) { DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY(); int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank(); death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank)); unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank)); durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness()); } } diciplineCircle.put(currentDiscipline.getName(), currentDiscipline.getCircle()); // Nur der höchtse Bonus wird gewertet. int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline); if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus; List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS(); currentBonuses.clear(); currentBonuses.addAll(getDisciplineBonuses(currentDiscipline)); } // ** KARMA STEP ** KARMAType karma = character.getKarma(); karma.setStep(4 + maxKarmaStepBonus); // mindestens d6 karma.setDice(step2Dice(karma.getStep())); int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills(); character.removeEmptySkills(); List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL()); for( SKILLType skill : character.getSkills() ) { RANKType rank = skill.getRANK(); int startrank = rank.getStartrank(); skillsStartranks+=startrank; int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank()); int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank); rank.setLpcost(lpcostfull-lpcoststart); rank.setBonus(0); calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost()); enforceCapabilityParams(skill); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } removeIfContains(defaultSkills,skill.getName()); } calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks); // Wenn gewünscht dann zeige auch die DefaultSkills mit an if( OptionalRule_ShowDefaultSkills ) { for( CAPABILITYType defaultSkill : defaultSkills ) { SKILLType skill = new SKILLType(); RANKType rank = new RANKType(); rank.setBonus(0); rank.setLpcost(0); rank.setRank(0); skill.setRANK(rank); skill.setName(defaultSkill.getName()); skill.setLimitation(defaultSkill.getLimitation()); skill.setAction(defaultSkill.getAction()); skill.setAttribute(defaultSkill.getAttribute()); skill.setBonus(defaultSkill.getBonus()); skill.setKarma(defaultSkill.getKarma()); skill.setStrain(defaultSkill.getStrain()); skill.setDefault(defaultSkill.getDefault()); if( skill.getAttribute() != null ) { calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value())); } character.getSkills().add(skill); } } DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle); defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical()); defense.setSocial(defense.getSocial()+disciplineDefense.getSocial()); defense.setSpell(defense.getSpell()+disciplineDefense.getSpell()); initiative.setModification(initiative.getModification()+getDisciplineInitiative(diciplineCircle)); initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle)); recovery.setDice(step2Dice(recovery.getStep())); // ** SPELLS ** String firstDisciplineName = ""; if( ! allDisciplines.isEmpty() ) { DISCIPLINEType firstDiscipline = allDisciplines.get(0); if( firstDiscipline != null ) firstDisciplineName=firstDiscipline.getName(); } int startingSpellLegendPointCost = 0; if( OptionalRule_SpellLegendPointCost ) { // Starting Spell can be from 1st and 2nd circle. Substact these Legendpoints from the legendpoints spend for spells ATTRIBUTEType per = characterAttributes.get("PER"); startingSpellLegendPointCost = 100 * attribute2StepAndDice(per.getBasevalue()).getStep(); int lpbonus = 0; for( int spellability : getDisciplineSpellAbility(diciplineCircle) ) { lpbonus += PROPERTIES.getCharacteristics().getSpellLP(spellability); } calculatedLP.setSpells(-lpbonus); } else { calculatedLP.setSpells(0); } HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells(); for( SPELLSType spells : character.getAllSpells() ) { if( spells.getDiscipline().equals(firstDisciplineName) && OptionalRule_SpellLegendPointCost ) { // Wenn die erste Disziplin eine Zauberdisciplin ist und die Optionale Regel, dass Zaubersprüche LP Kosten // gewählt wurde, dann reduziere die ZauberLPKosten um die StartZauber calculatedLP.setSpells(calculatedLP.getSpells()-startingSpellLegendPointCost); // Es ist jetzt schon einmal abgezogen. Stelle nun sicher dass nicht noch ein zweites Mal abgezogen werden kann. startingSpellLegendPointCost=0; } for( SPELLType spell : spells.getSPELL() ) { SPELLDEFType spelldef = spelllist.get(spell.getName()); if( spelldef == null ) { System.err.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour."); } else { spell.setCastingdifficulty(spelldef.getCastingdifficulty()); spell.setDuration(spelldef.getDuration()); spell.setEffect(spelldef.getEffect()); spell.setEffectarea(spelldef.getEffectarea()); spell.setRange(spelldef.getRange()); spell.setReattuningdifficulty(spelldef.getReattuningdifficulty()); spell.setThreads(spelldef.getThreads()); spell.setWeavingdifficulty(spelldef.getWeavingdifficulty()); } if( OptionalRule_SpellLegendPointCost ) { // The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle()); calculatedLP.setSpells(calculatedLP.getSpells()+lpcost); } } } for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) { if( item.getUsed().equals(YesnoType.YES) ) { death.setAdjustment(death.getAdjustment()-item.getBlooddamage()); unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage()); } } for( THREADITEMType item : character.getThreadItem() ) { for( int rank=0; rank<item.getWeaventhreadrank(); rank++ ) { THREADRANKType threadrank = item.getTHREADRANK().get(rank); if( threadrank == null ) { System.err.println("Undefined Threadrank for "+item.getName()+" for rank "+rank ); continue; } for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) { switch (itemdefense.getKind()) { case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break; case SPELL: defense.setSpell(defense.getSpell()+1); break; case SOCIAL: defense.setSocial(defense.getSocial()+1); break; } } for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) { String limitation = itemtalent.getLimitation(); boolean notfound=true; for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) { if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) { notfound=false; RANKType talentrank = talent.getRANK(); talentrank.setBonus(talentrank.getBonus()+1); calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value())); } } if( notfound ) { if( limitation.isEmpty() ) limitation ="(#)"; else limitation += " (#)"; TALENTType bonusTalent = new TALENTType(); bonusTalent.setName(itemtalent.getName()); bonusTalent.setLimitation(limitation); bonusTalent.setCircle(0); enforceCapabilityParams(bonusTalent); RANKType bonusrank = new RANKType(); bonusrank.setRank(0); bonusrank.setBonus(1); calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value())); bonusTalent.setRANK(bonusrank); TALENTTEACHERType teacher = new TALENTTEACHERType(); teacher.setByversatility(YesnoType.NO); teacher.setTalentcircle(rank); teacher.setTeachercircle(rank); teacher.setName(item.getName()); bonusTalent.setTEACHER(teacher); allTalents.get(1).getOPTIONALTALENT().add(bonusTalent); } } for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) { initiative.setModification(initiative.getModification()+iteminitiative.getCount()); } initiative.setStep(initiative.getBase()+initiative.getModification()); initiative.setDice(step2Dice(initiative.getStep())); // TODO: other effects of MagicItems } // TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT(); } // Veränderungen am death/unconsciousness adjustment sollen beachtet werden death.setValue(death.getBase()+death.getAdjustment()); unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment()); if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0); calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+ calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+ calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks()); if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP); character.calculateLegendPointsAndStatus(); character.calculateDevotionPoints(); return charakter; }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/CopyContextToAction.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/CopyContextToAction.java index 18042f9e1..95e9c7e46 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/CopyContextToAction.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/CopyContextToAction.java @@ -1,113 +1,113 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.context.ui.actions; import java.io.File; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.mylar.context.core.ContextCorePlugin; import org.eclipse.mylar.internal.tasks.ui.actions.TaskSelectionDialog; import org.eclipse.mylar.internal.tasks.ui.views.TaskListView; import org.eclipse.mylar.tasks.core.AbstractQueryHit; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PlatformUI; /** * @author Mik Kersten */ public class CopyContextToAction implements IViewActionDelegate { private static final String OPEN_TASK_ACTION_DIALOG_SETTINGS = "open.task.action.dialog.settings"; private ISelection selection; public void init(IViewPart view) { // ignore } public void run(IAction action) { ITask sourceTask = null; if (selection instanceof StructuredSelection) { Object selectedObject = ((StructuredSelection) selection).getFirstElement(); if (selectedObject instanceof ITask) { sourceTask = (ITask) selectedObject; } else if (selectedObject instanceof AbstractQueryHit) { sourceTask = ((AbstractQueryHit) selectedObject).getCorrespondingTask(); } } if (sourceTask == null) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No source task selected."); } TaskSelectionDialog dialog = new TaskSelectionDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell()); dialog.setTitle("Select Target Task"); IDialogSettings settings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings dlgSettings = settings.getSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); if (dlgSettings == null) { dlgSettings = settings.addNewSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); } dialog.setDialogBoundsSettings(dlgSettings, Dialog.DIALOG_PERSISTLOCATION | Dialog.DIALOG_PERSISTSIZE); int ret = dialog.open(); if (ret != Window.OK) { return; } Object result = dialog.getFirstResult(); ITask targetTask = null; if (result instanceof AbstractQueryHit) { AbstractQueryHit hit = (AbstractQueryHit) result; targetTask = hit.getOrCreateCorrespondingTask(); } else if (result instanceof ITask) { targetTask = (ITask) result; } if (targetTask != null) { TasksUiPlugin.getTaskListManager().deactivateAllTasks(); File contextFile = ContextCorePlugin.getContextManager() .getFileForContext(sourceTask.getHandleIdentifier()); if (!contextFile.exists()) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), - TasksUiPlugin.TITLE_DIALOG, "Source task does not hava a context."); + TasksUiPlugin.TITLE_DIALOG, "Source task does not have a context."); } else { ContextCorePlugin.getContextManager().transferContextAndActivate(targetTask.getHandleIdentifier(), contextFile); TasksUiPlugin.getTaskListManager().activateTask(targetTask); TaskListView view = TaskListView.getFromActivePerspective(); if (view != null) { view.refreshAndFocus(false); } } } else { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No target task selected."); } } public void selectionChanged(IAction action, ISelection selection) { this.selection = selection; } }
true
true
public void run(IAction action) { ITask sourceTask = null; if (selection instanceof StructuredSelection) { Object selectedObject = ((StructuredSelection) selection).getFirstElement(); if (selectedObject instanceof ITask) { sourceTask = (ITask) selectedObject; } else if (selectedObject instanceof AbstractQueryHit) { sourceTask = ((AbstractQueryHit) selectedObject).getCorrespondingTask(); } } if (sourceTask == null) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No source task selected."); } TaskSelectionDialog dialog = new TaskSelectionDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell()); dialog.setTitle("Select Target Task"); IDialogSettings settings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings dlgSettings = settings.getSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); if (dlgSettings == null) { dlgSettings = settings.addNewSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); } dialog.setDialogBoundsSettings(dlgSettings, Dialog.DIALOG_PERSISTLOCATION | Dialog.DIALOG_PERSISTSIZE); int ret = dialog.open(); if (ret != Window.OK) { return; } Object result = dialog.getFirstResult(); ITask targetTask = null; if (result instanceof AbstractQueryHit) { AbstractQueryHit hit = (AbstractQueryHit) result; targetTask = hit.getOrCreateCorrespondingTask(); } else if (result instanceof ITask) { targetTask = (ITask) result; } if (targetTask != null) { TasksUiPlugin.getTaskListManager().deactivateAllTasks(); File contextFile = ContextCorePlugin.getContextManager() .getFileForContext(sourceTask.getHandleIdentifier()); if (!contextFile.exists()) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "Source task does not hava a context."); } else { ContextCorePlugin.getContextManager().transferContextAndActivate(targetTask.getHandleIdentifier(), contextFile); TasksUiPlugin.getTaskListManager().activateTask(targetTask); TaskListView view = TaskListView.getFromActivePerspective(); if (view != null) { view.refreshAndFocus(false); } } } else { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No target task selected."); } }
public void run(IAction action) { ITask sourceTask = null; if (selection instanceof StructuredSelection) { Object selectedObject = ((StructuredSelection) selection).getFirstElement(); if (selectedObject instanceof ITask) { sourceTask = (ITask) selectedObject; } else if (selectedObject instanceof AbstractQueryHit) { sourceTask = ((AbstractQueryHit) selectedObject).getCorrespondingTask(); } } if (sourceTask == null) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No source task selected."); } TaskSelectionDialog dialog = new TaskSelectionDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell()); dialog.setTitle("Select Target Task"); IDialogSettings settings = TasksUiPlugin.getDefault().getDialogSettings(); IDialogSettings dlgSettings = settings.getSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); if (dlgSettings == null) { dlgSettings = settings.addNewSection(OPEN_TASK_ACTION_DIALOG_SETTINGS); } dialog.setDialogBoundsSettings(dlgSettings, Dialog.DIALOG_PERSISTLOCATION | Dialog.DIALOG_PERSISTSIZE); int ret = dialog.open(); if (ret != Window.OK) { return; } Object result = dialog.getFirstResult(); ITask targetTask = null; if (result instanceof AbstractQueryHit) { AbstractQueryHit hit = (AbstractQueryHit) result; targetTask = hit.getOrCreateCorrespondingTask(); } else if (result instanceof ITask) { targetTask = (ITask) result; } if (targetTask != null) { TasksUiPlugin.getTaskListManager().deactivateAllTasks(); File contextFile = ContextCorePlugin.getContextManager() .getFileForContext(sourceTask.getHandleIdentifier()); if (!contextFile.exists()) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "Source task does not have a context."); } else { ContextCorePlugin.getContextManager().transferContextAndActivate(targetTask.getHandleIdentifier(), contextFile); TasksUiPlugin.getTaskListManager().activateTask(targetTask); TaskListView view = TaskListView.getFromActivePerspective(); if (view != null) { view.refreshAndFocus(false); } } } else { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), TasksUiPlugin.TITLE_DIALOG, "No target task selected."); } }
diff --git a/wms/src/main/java/org/geoserver/wms/map/PNGMapResponse.java b/wms/src/main/java/org/geoserver/wms/map/PNGMapResponse.java index bf3d9eb49..0bab53b2e 100644 --- a/wms/src/main/java/org/geoserver/wms/map/PNGMapResponse.java +++ b/wms/src/main/java/org/geoserver/wms/map/PNGMapResponse.java @@ -1,101 +1,101 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.wms.map; import java.awt.image.IndexColorModel; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.io.IOException; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; import org.geoserver.platform.ServiceException; import org.geoserver.wms.MapProducerCapabilities; import org.geoserver.wms.WMS; import org.geoserver.wms.WMSMapContext; import org.geotools.image.ImageWorker; import org.geotools.image.palette.InverseColorMapOp; import org.geotools.util.logging.Logging; /** * Handles a GetMap request that spects a map in GIF format. * * @author Simone Giannecchini * @author Didier Richard * @version $Id */ public class PNGMapResponse extends RenderedImageMapResponse { /** Logger */ private static final Logger LOGGER = Logging.getLogger(PNGMapResponse.class); private static final String MIME_TYPE = "image/png"; private static final String[] OUTPUT_FORMATS = { MIME_TYPE, "image/png8" }; /** * Default capabilities for PNG format. * * <p> * <ol> * <li>tiled = supported</li> * <li>multipleValues = unsupported</li> * <li>paletteSupported = supported</li> * <li>transparency = supported</li> * </ol> */ private static MapProducerCapabilities CAPABILITIES= new MapProducerCapabilities(true, false, true, true); /** * @param format * the format name as to be reported in the capabilities document * @param wms */ public PNGMapResponse(WMS wms) { super(OUTPUT_FORMATS, wms); } /** * Transforms the rendered image into the appropriate format, streaming to the output stream. * * @see RasterMapOutputFormat#formatImageOutputStream(RenderedImage, OutputStream) */ public void formatImageOutputStream(RenderedImage image, OutputStream outStream, WMSMapContext mapContext) throws ServiceException, IOException { // ///////////////////////////////////////////////////////////////// // // Reformatting this image for png // // ///////////////////////////////////////////////////////////////// if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ..."); } // get the one required by the GetMapRequest final String format = mapContext.getRequest().getFormat(); if ("image/png8".equalsIgnoreCase(format) || (mapContext.getPaletteInverter() != null)) { InverseColorMapOp paletteInverter = mapContext.getPaletteInverter(); image = forceIndexed8Bitmask(image, paletteInverter); } Boolean PNGNativeAcc = wms.getPNGNativeAcceleration(); float quality = (100 - wms.getPngCompression()) / 100.0f; SampleModel sm = image.getSampleModel(); int numBits = sm.getSampleSize(0); // png acceleration only works on 2 bit and 8 bit images, crashes on 4 bits - boolean nativeAcceleration = PNGNativeAcc.booleanValue() && (numBits == 2 || numBits == 8); + boolean nativeAcceleration = PNGNativeAcc.booleanValue() && (numBits > 1 && numBits < 8); new ImageWorker(image).writePNG(outStream, "FILTERED", quality, nativeAcceleration, image.getColorModel() instanceof IndexColorModel); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ... done!"); } } @Override public MapProducerCapabilities getCapabilities(String outputFormat) { return CAPABILITIES; } }
true
true
public void formatImageOutputStream(RenderedImage image, OutputStream outStream, WMSMapContext mapContext) throws ServiceException, IOException { // ///////////////////////////////////////////////////////////////// // // Reformatting this image for png // // ///////////////////////////////////////////////////////////////// if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ..."); } // get the one required by the GetMapRequest final String format = mapContext.getRequest().getFormat(); if ("image/png8".equalsIgnoreCase(format) || (mapContext.getPaletteInverter() != null)) { InverseColorMapOp paletteInverter = mapContext.getPaletteInverter(); image = forceIndexed8Bitmask(image, paletteInverter); } Boolean PNGNativeAcc = wms.getPNGNativeAcceleration(); float quality = (100 - wms.getPngCompression()) / 100.0f; SampleModel sm = image.getSampleModel(); int numBits = sm.getSampleSize(0); // png acceleration only works on 2 bit and 8 bit images, crashes on 4 bits boolean nativeAcceleration = PNGNativeAcc.booleanValue() && (numBits == 2 || numBits == 8); new ImageWorker(image).writePNG(outStream, "FILTERED", quality, nativeAcceleration, image.getColorModel() instanceof IndexColorModel); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ... done!"); } }
public void formatImageOutputStream(RenderedImage image, OutputStream outStream, WMSMapContext mapContext) throws ServiceException, IOException { // ///////////////////////////////////////////////////////////////// // // Reformatting this image for png // // ///////////////////////////////////////////////////////////////// if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ..."); } // get the one required by the GetMapRequest final String format = mapContext.getRequest().getFormat(); if ("image/png8".equalsIgnoreCase(format) || (mapContext.getPaletteInverter() != null)) { InverseColorMapOp paletteInverter = mapContext.getPaletteInverter(); image = forceIndexed8Bitmask(image, paletteInverter); } Boolean PNGNativeAcc = wms.getPNGNativeAcceleration(); float quality = (100 - wms.getPngCompression()) / 100.0f; SampleModel sm = image.getSampleModel(); int numBits = sm.getSampleSize(0); // png acceleration only works on 2 bit and 8 bit images, crashes on 4 bits boolean nativeAcceleration = PNGNativeAcc.booleanValue() && (numBits > 1 && numBits < 8); new ImageWorker(image).writePNG(outStream, "FILTERED", quality, nativeAcceleration, image.getColorModel() instanceof IndexColorModel); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Writing png image ... done!"); } }
diff --git a/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/datamap/DataMap.java b/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/datamap/DataMap.java index 00d5aedaa..2bd5a400f 100644 --- a/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/datamap/DataMap.java +++ b/OldSoar/trunk/visualsoar/Source/edu/umich/visualsoar/datamap/DataMap.java @@ -1,355 +1,355 @@ package edu.umich.visualsoar.datamap; import edu.umich.visualsoar.graph.*; import edu.umich.visualsoar.MainFrame; import edu.umich.visualsoar.graph.SoarIdentifierVertex; import edu.umich.visualsoar.graph.NamedEdge; import edu.umich.visualsoar.misc.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.util.Vector; /** * This class is the internal frame in which the DataMap resides * @author Brad Jones * @see DataMapTree */ public class DataMap extends CustomInternalFrame { DataMapTree dataMapTree; int id; //////////////////////////////////////// // Constructors //////////////////////////////////////// // Deny Default Construction private DataMap() {} /** * Create a DataMap in an internal frame * @param swmm Working Memory - SoarWorkingMemoryModel * @param siv the vertex that is the root of datamap * @param title the name of the datamap window, generally the name of the selected operator node * @see SoarWMTreeModelWrapper * @see DataMapTree */ public DataMap(SoarWorkingMemoryModel swmm, SoarIdentifierVertex siv,String title) { - super(title,true,true,true,true); + super("Datamap " + title,true,true,true,true); setType(DATAMAP); setBounds(0,0,250,100); id = siv.getValue(); // Retile the internal frames after closing a window setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addInternalFrameListener( new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { MainFrame mf = MainFrame.getMainFrame(); mf.getDesktopPane().dmRemove(id); dispose(); if(Preferences.getInstance().isAutoTilingEnabled()) { mf.getDesktopPane().performTileAction(); } mf.selectNewInternalFrame(); } }); TreeModel soarTreeModel = new SoarWMTreeModelWrapper(swmm,siv,title); soarTreeModel.addTreeModelListener(new DataMapListenerModel()); dataMapTree = new DataMapTree(soarTreeModel,swmm); getContentPane().add(new JScrollPane(dataMapTree)); dataMapTree.setCellRenderer(new DataMapTreeRenderer()); JMenuBar menuBar = new JMenuBar(); JMenu editMenu = new JMenu("Edit"); JMenu validateMenu = new JMenu("Validation"); /* Too Dangerous, see DataMapTree.java JMenuItem cutItem = new JMenuItem("Cut"); editMenu.add(cutItem); cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.CTRL_MASK)); cutItem.addActionListener(dataMapTree.cutAction); */ JMenuItem copyItem = new JMenuItem("Copy"); editMenu.add(copyItem); copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK)); copyItem.addActionListener(dataMapTree.copyAction); JMenuItem pasteItem = new JMenuItem("Paste"); editMenu.add(pasteItem); pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK)); pasteItem.addActionListener(dataMapTree.pasteAction); JMenuItem searchItem = new JMenuItem("Search DataMap"); editMenu.add(searchItem); searchItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK)); searchItem.addActionListener(dataMapTree.searchAction); JMenuItem validateItem = new JMenuItem("Validate DataMap"); validateMenu.add(validateItem); validateItem.addActionListener(dataMapTree.validateDataMapAction); JMenuItem removeItem = new JMenuItem("Remove Non-Validated"); validateMenu.add(removeItem); removeItem.addActionListener(dataMapTree.removeInvalidAction); menuBar.add(editMenu); menuBar.add(validateMenu); setJMenuBar(menuBar); } public int getId() { return id; } public Vector searchTestDataMap(SoarIdentifierVertex in_siv, String dataMapName) { return dataMapTree.searchTestDataMap(in_siv, dataMapName); } public Vector searchCreateDataMap(SoarIdentifierVertex in_siv, String dataMapName) { return dataMapTree.searchCreateDataMap(in_siv, dataMapName); } public Vector searchTestNoCreateDataMap(SoarIdentifierVertex in_siv, String dataMapName) { return dataMapTree.searchTestNoCreateDataMap(in_siv, dataMapName); } public Vector searchCreateNoTestDataMap(SoarIdentifierVertex in_siv, String dataMapName) { return dataMapTree.searchCreateNoTestDataMap(in_siv, dataMapName); } public Vector searchNoTestNoCreateDataMap(SoarIdentifierVertex in_siv, String dataMapName) { return dataMapTree.searchNoTestNoCreateDataMap(in_siv, dataMapName); } public void displayGeneratedNodes() { dataMapTree.displayGeneratedNodes(); } /** * Selects (highlights and centers) the requested edge within the datamap. * @param edge the requested NamedEdge to select * @return true if success, false if could not find edge */ public boolean selectEdge(NamedEdge edge) { FakeTreeNode node = dataMapTree.selectEdge(edge); if(node != null) { TreePath path = new TreePath(node.getTreePath().toArray()); dataMapTree.scrollPathToVisible(path); dataMapTree.setSelectionPath(path); return true; } else { JOptionPane.showMessageDialog(null, "Could not find a matching FakeTreeNode in the datamap"); return false; } } /** * This class is meant to catch if the user closes an internal frame without saving * the file, it prompts them to save, or discard the file or cancel the close */ class CloseListener implements VetoableChangeListener { public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException { } } /** * This class customizes the look of the the DataMap Tree. * It is responsible for changing the color of the text of nodes * generated by the datamap generator. */ private class DataMapTreeRenderer extends DefaultTreeCellRenderer { public DataMapTreeRenderer() { } public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus); if (isGeneratedNode(value)) { setForeground(Color.green.darker().darker()); } /// The following were just for testing purposes ///// /* if (isUnTested(value)) { setForeground(Color.magenta.darker()); } */ /* if (isNotMentioned(value)) { setForeground(Color.red.darker()); } if(isTEST(value)) { setForeground(Color.blue.darker()); } */ return this; } protected boolean isGeneratedNode(Object value) { if(value instanceof FakeTreeNode) { FakeTreeNode node = (FakeTreeNode) value; NamedEdge ne = node.getEdge(); if(ne != null) { if(ne.isGenerated()) { return true; } else { return false; } } } return false; } // end of isGeneratedNode() member function protected boolean isNotMentioned(Object value) { if(value instanceof FakeTreeNode) { FakeTreeNode node = (FakeTreeNode) value; NamedEdge ne = node.getEdge(); if(ne != null) { if(ne.notMentioned()) { return true; } else { return false; } } } return false; } // end of isNotMentioned() member function protected boolean isUnTested(Object value) { if(value instanceof FakeTreeNode) { FakeTreeNode node = (FakeTreeNode) value; NamedEdge ne = node.getEdge(); if(ne != null) { if(!ne.isTested()) { return true; } else { return false; } } } return false; } // end of isNotMentioned() member function protected boolean isTEST(Object value) { if(value instanceof FakeTreeNode) { FakeTreeNode node = (FakeTreeNode) value; NamedEdge ne = node.getEdge(); if(ne != null) { if(ne.getTestedStatus() == 1) { return true; } else { return false; } } } return false; } // end of isNotMentioned() member function } // end of DataMapRenderer class private class DataMapListenerModel implements TreeModelListener { public void treeNodesChanged(TreeModelEvent e) { } public void treeNodesInserted(TreeModelEvent e) { // Make sure to expand path to display created node dataMapTree.expandPath(e.getTreePath()); } public void treeNodesRemoved(TreeModelEvent e) { } public void treeStructureChanged(TreeModelEvent e) { } } } // end of DataMap class
true
true
public DataMap(SoarWorkingMemoryModel swmm, SoarIdentifierVertex siv,String title) { super(title,true,true,true,true); setType(DATAMAP); setBounds(0,0,250,100); id = siv.getValue(); // Retile the internal frames after closing a window setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addInternalFrameListener( new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { MainFrame mf = MainFrame.getMainFrame(); mf.getDesktopPane().dmRemove(id); dispose(); if(Preferences.getInstance().isAutoTilingEnabled()) { mf.getDesktopPane().performTileAction(); } mf.selectNewInternalFrame(); } }); TreeModel soarTreeModel = new SoarWMTreeModelWrapper(swmm,siv,title); soarTreeModel.addTreeModelListener(new DataMapListenerModel()); dataMapTree = new DataMapTree(soarTreeModel,swmm); getContentPane().add(new JScrollPane(dataMapTree)); dataMapTree.setCellRenderer(new DataMapTreeRenderer()); JMenuBar menuBar = new JMenuBar(); JMenu editMenu = new JMenu("Edit"); JMenu validateMenu = new JMenu("Validation"); /* Too Dangerous, see DataMapTree.java JMenuItem cutItem = new JMenuItem("Cut"); editMenu.add(cutItem); cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.CTRL_MASK)); cutItem.addActionListener(dataMapTree.cutAction); */ JMenuItem copyItem = new JMenuItem("Copy"); editMenu.add(copyItem); copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK)); copyItem.addActionListener(dataMapTree.copyAction); JMenuItem pasteItem = new JMenuItem("Paste"); editMenu.add(pasteItem); pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK)); pasteItem.addActionListener(dataMapTree.pasteAction); JMenuItem searchItem = new JMenuItem("Search DataMap"); editMenu.add(searchItem); searchItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK)); searchItem.addActionListener(dataMapTree.searchAction); JMenuItem validateItem = new JMenuItem("Validate DataMap"); validateMenu.add(validateItem); validateItem.addActionListener(dataMapTree.validateDataMapAction); JMenuItem removeItem = new JMenuItem("Remove Non-Validated"); validateMenu.add(removeItem); removeItem.addActionListener(dataMapTree.removeInvalidAction); menuBar.add(editMenu); menuBar.add(validateMenu); setJMenuBar(menuBar); }
public DataMap(SoarWorkingMemoryModel swmm, SoarIdentifierVertex siv,String title) { super("Datamap " + title,true,true,true,true); setType(DATAMAP); setBounds(0,0,250,100); id = siv.getValue(); // Retile the internal frames after closing a window setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); addInternalFrameListener( new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { MainFrame mf = MainFrame.getMainFrame(); mf.getDesktopPane().dmRemove(id); dispose(); if(Preferences.getInstance().isAutoTilingEnabled()) { mf.getDesktopPane().performTileAction(); } mf.selectNewInternalFrame(); } }); TreeModel soarTreeModel = new SoarWMTreeModelWrapper(swmm,siv,title); soarTreeModel.addTreeModelListener(new DataMapListenerModel()); dataMapTree = new DataMapTree(soarTreeModel,swmm); getContentPane().add(new JScrollPane(dataMapTree)); dataMapTree.setCellRenderer(new DataMapTreeRenderer()); JMenuBar menuBar = new JMenuBar(); JMenu editMenu = new JMenu("Edit"); JMenu validateMenu = new JMenu("Validation"); /* Too Dangerous, see DataMapTree.java JMenuItem cutItem = new JMenuItem("Cut"); editMenu.add(cutItem); cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,Event.CTRL_MASK)); cutItem.addActionListener(dataMapTree.cutAction); */ JMenuItem copyItem = new JMenuItem("Copy"); editMenu.add(copyItem); copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK)); copyItem.addActionListener(dataMapTree.copyAction); JMenuItem pasteItem = new JMenuItem("Paste"); editMenu.add(pasteItem); pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK)); pasteItem.addActionListener(dataMapTree.pasteAction); JMenuItem searchItem = new JMenuItem("Search DataMap"); editMenu.add(searchItem); searchItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK)); searchItem.addActionListener(dataMapTree.searchAction); JMenuItem validateItem = new JMenuItem("Validate DataMap"); validateMenu.add(validateItem); validateItem.addActionListener(dataMapTree.validateDataMapAction); JMenuItem removeItem = new JMenuItem("Remove Non-Validated"); validateMenu.add(removeItem); removeItem.addActionListener(dataMapTree.removeInvalidAction); menuBar.add(editMenu); menuBar.add(validateMenu); setJMenuBar(menuBar); }
diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java index 1ebb6389..bc6b27ae 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java @@ -1,200 +1,200 @@ package com.earth2me.essentials.chat; import com.earth2me.essentials.ChargeException; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; //TODO: Translate the local/spy tags public abstract class EssentialsChatPlayer implements Listener { protected transient IEssentials ess; protected final static Logger logger = Logger.getLogger("Minecraft"); protected final transient Map<String, IEssentialsChatListener> listeners; protected final transient Server server; protected final transient Map<AsyncPlayerChatEvent, ChatStore> chatStorage; public EssentialsChatPlayer(final Server server, final IEssentials ess, final Map<String, IEssentialsChatListener> listeners, final Map<AsyncPlayerChatEvent, ChatStore> chatStorage) { this.ess = ess; this.listeners = listeners; this.server = server; this.chatStorage = chatStorage; } public void onPlayerChat(final AsyncPlayerChatEvent event) { } public boolean isAborted(final AsyncPlayerChatEvent event) { if (event.isCancelled()) { return true; } synchronized (listeners) { for (Map.Entry<String, IEssentialsChatListener> listener : listeners.entrySet()) { try { if (listener.getValue().shouldHandleThisChat(event)) { return true; } } catch (Throwable t) { if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage(), t); } else { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage()); } } } } return false; } public String getChatType(final String message) { switch (message.charAt(0)) { case '!': return "shout"; case '?': return "question"; //case '@': //return "admin"; default: return ""; } } public ChatStore getChatStore(final AsyncPlayerChatEvent event) { return chatStorage.get(event); } public void setChatStore(final AsyncPlayerChatEvent event, final ChatStore chatStore) { chatStorage.put(event, chatStore); } public ChatStore delChatStore(final AsyncPlayerChatEvent event) { return chatStorage.remove(event); } protected void charge(final User user, final Trade charge) throws ChargeException { charge.charge(user); } protected boolean charge(final AsyncPlayerChatEvent event, final ChatStore chatStore) { try { charge(chatStore.getUser(), chatStore.getCharge()); } catch (ChargeException e) { ess.showError(chatStore.getUser(), e, chatStore.getLongType()); event.setCancelled(true); return false; } return true; } protected void sendLocalChat(final AsyncPlayerChatEvent event, final ChatStore chatStore) { event.setCancelled(true); final User sender = chatStore.getUser(); logger.info(_("localFormat", sender.getName(), event.getMessage())); final Location loc = sender.getLocation(); final World world = loc.getWorld(); if (charge(event, chatStore) == false) { return; } for (Player onlinePlayer : server.getOnlinePlayers()) { String type = _("chatTypeLocal"); final User onlineUser = ess.getUser(onlinePlayer); if (onlineUser.isIgnoredPlayer(sender)) { continue; } if (!onlineUser.equals(sender)) { boolean abort = false; final Location playerLoc = onlineUser.getLocation(); if (playerLoc.getWorld() != world) { abort = true; } else { final double delta = playerLoc.distanceSquared(loc); if (delta > chatStore.getRadius()) { abort = true; } } if (abort) { if (onlineUser.isAuthorized("essentials.chat.spy")) { type = type.concat(_("chatTypeSpy")); } else { continue; } } } - String message = String.format(event.getFormat(), type.concat(sender.getDisplayName()), event.getMessage()); + String message = type.concat(String.format(event.getFormat(), sender.getDisplayName(), event.getMessage())); synchronized (listeners) { for (Map.Entry<String, IEssentialsChatListener> listener : listeners.entrySet()) { try { message = listener.getValue().modifyMessage(event, onlinePlayer, message); } catch (Throwable t) { if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage(), t); } else { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage()); } } } } onlineUser.sendMessage(message); } } }
true
true
protected void sendLocalChat(final AsyncPlayerChatEvent event, final ChatStore chatStore) { event.setCancelled(true); final User sender = chatStore.getUser(); logger.info(_("localFormat", sender.getName(), event.getMessage())); final Location loc = sender.getLocation(); final World world = loc.getWorld(); if (charge(event, chatStore) == false) { return; } for (Player onlinePlayer : server.getOnlinePlayers()) { String type = _("chatTypeLocal"); final User onlineUser = ess.getUser(onlinePlayer); if (onlineUser.isIgnoredPlayer(sender)) { continue; } if (!onlineUser.equals(sender)) { boolean abort = false; final Location playerLoc = onlineUser.getLocation(); if (playerLoc.getWorld() != world) { abort = true; } else { final double delta = playerLoc.distanceSquared(loc); if (delta > chatStore.getRadius()) { abort = true; } } if (abort) { if (onlineUser.isAuthorized("essentials.chat.spy")) { type = type.concat(_("chatTypeSpy")); } else { continue; } } } String message = String.format(event.getFormat(), type.concat(sender.getDisplayName()), event.getMessage()); synchronized (listeners) { for (Map.Entry<String, IEssentialsChatListener> listener : listeners.entrySet()) { try { message = listener.getValue().modifyMessage(event, onlinePlayer, message); } catch (Throwable t) { if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage(), t); } else { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage()); } } } } onlineUser.sendMessage(message); } }
protected void sendLocalChat(final AsyncPlayerChatEvent event, final ChatStore chatStore) { event.setCancelled(true); final User sender = chatStore.getUser(); logger.info(_("localFormat", sender.getName(), event.getMessage())); final Location loc = sender.getLocation(); final World world = loc.getWorld(); if (charge(event, chatStore) == false) { return; } for (Player onlinePlayer : server.getOnlinePlayers()) { String type = _("chatTypeLocal"); final User onlineUser = ess.getUser(onlinePlayer); if (onlineUser.isIgnoredPlayer(sender)) { continue; } if (!onlineUser.equals(sender)) { boolean abort = false; final Location playerLoc = onlineUser.getLocation(); if (playerLoc.getWorld() != world) { abort = true; } else { final double delta = playerLoc.distanceSquared(loc); if (delta > chatStore.getRadius()) { abort = true; } } if (abort) { if (onlineUser.isAuthorized("essentials.chat.spy")) { type = type.concat(_("chatTypeSpy")); } else { continue; } } } String message = type.concat(String.format(event.getFormat(), sender.getDisplayName(), event.getMessage())); synchronized (listeners) { for (Map.Entry<String, IEssentialsChatListener> listener : listeners.entrySet()) { try { message = listener.getValue().modifyMessage(event, onlinePlayer, message); } catch (Throwable t) { if (ess.getSettings().isDebug()) { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage(), t); } else { logger.log(Level.WARNING, "Error with EssentialsChat listener of " + listener.getKey() + ": " + t.getMessage()); } } } } onlineUser.sendMessage(message); } }
diff --git a/src/info/ata4/unity/cli/DisUnityCli.java b/src/info/ata4/unity/cli/DisUnityCli.java index b9f1eb1..7d415db 100644 --- a/src/info/ata4/unity/cli/DisUnityCli.java +++ b/src/info/ata4/unity/cli/DisUnityCli.java @@ -1,145 +1,145 @@ /* ** 2013 July 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.unity.cli; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import info.ata4.log.LogUtils; import info.ata4.unity.DisUnity; import info.ata4.unity.cli.classfilter.SimpleClassFilter; import info.ata4.unity.util.ClassID; import java.nio.file.Paths; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; /** * DisUnity command line interface. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class DisUnityCli implements Runnable { private static final Logger L = LogUtils.getLogger(); /** * @param args the command line arguments */ public static void main(String[] args) { LogUtils.configure(); L.log(Level.INFO, DisUnity.getSignature()); try { DisUnityCli cli = new DisUnityCli(); JCommander cmd = new JCommander(); cmd.setProgramName(DisUnity.getProgramName()); cmd.addObject(cli); cmd.parse(args); if (cli.showUsage()) { cmd.usage(); } else { cli.run(); } } catch (Throwable t) { L.log(Level.SEVERE, "Fatal error", t); } } @Parameter( names = { "-v", "--verbose" }, description = "Show more verbose log output." ) private boolean verbose; @Parameter( names = { "-f", "--include" }, description = "Only process objects that use these classes. Expects a string with class names or IDs, separated by commas." ) private String classListInclude; @Parameter( names = { "-x", "--exclude" }, description = "Exclude objects from processing that use these classes. Expects a string with class names or IDs, separated by commas." ) private String classListExclude; @Parameter( description = "<command> <files>" ) private List<String> remaining; public boolean showUsage() { return remaining == null || remaining.size() < 2; } @Override public void run() { // convert unnamed argument list to deque Deque<String> args = new ArrayDeque<>(remaining); DisUnityOptions ops = new DisUnityOptions(); // set command ops.setCommand(args.pollFirst()); // add files for (String path : args) { ops.getFiles().add(Paths.get(path)); } // set class filter lists if (classListInclude != null || classListExclude != null) { SimpleClassFilter classFilter = new SimpleClassFilter(); parseClassList(classFilter.getAcceptedIDs(), classListInclude); - parseClassList(classFilter.getAcceptedIDs(), classListExclude); + parseClassList(classFilter.getRejectedIDs(), classListExclude); ops.setClassFilter(classFilter); } // increase logging level if requested if (verbose) { LogUtils.configure(Level.ALL); } // run processor DisUnityProcessor processor = new DisUnityProcessor(ops); processor.run(); } private void parseClassList(Set<Integer> classIDList, String classListString) { if (StringUtils.isEmpty(classListString)) { return; } String[] values = StringUtils.split(classListString, ","); for (String className : values) { Integer classID; try { classID = Integer.parseInt(className); } catch (NumberFormatException e) { classID = ClassID.getIDForName(className, true); } if (classID == null) { L.log(Level.WARNING, "Invalid class name or ID for filter: {0}", className); continue; } classIDList.add(classID); } } }
true
true
public void run() { // convert unnamed argument list to deque Deque<String> args = new ArrayDeque<>(remaining); DisUnityOptions ops = new DisUnityOptions(); // set command ops.setCommand(args.pollFirst()); // add files for (String path : args) { ops.getFiles().add(Paths.get(path)); } // set class filter lists if (classListInclude != null || classListExclude != null) { SimpleClassFilter classFilter = new SimpleClassFilter(); parseClassList(classFilter.getAcceptedIDs(), classListInclude); parseClassList(classFilter.getAcceptedIDs(), classListExclude); ops.setClassFilter(classFilter); } // increase logging level if requested if (verbose) { LogUtils.configure(Level.ALL); } // run processor DisUnityProcessor processor = new DisUnityProcessor(ops); processor.run(); }
public void run() { // convert unnamed argument list to deque Deque<String> args = new ArrayDeque<>(remaining); DisUnityOptions ops = new DisUnityOptions(); // set command ops.setCommand(args.pollFirst()); // add files for (String path : args) { ops.getFiles().add(Paths.get(path)); } // set class filter lists if (classListInclude != null || classListExclude != null) { SimpleClassFilter classFilter = new SimpleClassFilter(); parseClassList(classFilter.getAcceptedIDs(), classListInclude); parseClassList(classFilter.getRejectedIDs(), classListExclude); ops.setClassFilter(classFilter); } // increase logging level if requested if (verbose) { LogUtils.configure(Level.ALL); } // run processor DisUnityProcessor processor = new DisUnityProcessor(ops); processor.run(); }
diff --git a/src/com/android/dialer/PhoneCallDetailsHelper.java b/src/com/android/dialer/PhoneCallDetailsHelper.java index f4a6538..44450df 100644 --- a/src/com/android/dialer/PhoneCallDetailsHelper.java +++ b/src/com/android/dialer/PhoneCallDetailsHelper.java @@ -1,242 +1,245 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dialer; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Typeface; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.view.View; import android.widget.TextView; import com.android.contacts.common.test.NeededForTesting; import com.android.dialer.calllog.CallTypeHelper; import com.android.dialer.calllog.ContactInfo; import com.android.dialer.calllog.PhoneNumberHelper; import com.android.dialer.calllog.PhoneNumberUtilsWrapper; import com.android.internal.util.mm.DeviceUtils; import java.util.Locale; /** * Helper class to fill in the views in {@link PhoneCallDetailsViews}. */ public class PhoneCallDetailsHelper { /** The maximum number of icons will be shown to represent the call types in a group. */ private static final int MAX_CALL_TYPE_ICONS = 3; private final Resources mResources; /** The injected current time in milliseconds since the epoch. Used only by tests. */ private Long mCurrentTimeMillisForTest; // Helper classes. private final CallTypeHelper mCallTypeHelper; private final PhoneNumberHelper mPhoneNumberHelper; private final PhoneNumberUtilsWrapper mPhoneNumberUtilsWrapper; /** * Creates a new instance of the helper. * <p> * Generally you should have a single instance of this helper in any context. * * @param resources used to look up strings */ public PhoneCallDetailsHelper(Resources resources, CallTypeHelper callTypeHelper, PhoneNumberUtilsWrapper phoneUtils) { mResources = resources; mCallTypeHelper = callTypeHelper; mPhoneNumberHelper = new PhoneNumberHelper(resources); mPhoneNumberUtilsWrapper = phoneUtils; } /** Fills the call details views with content. */ public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details, boolean isHighlighted) { // Display up to a given number of icons. views.callTypeIcons.clear(); int count = details.callTypes.length; for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) { views.callTypeIcons.add(details.callTypes[index]); } views.callTypeIcons.requestLayout(); views.callTypeIcons.setVisibility(View.VISIBLE); // Show the total call count only if there are more than the maximum number of icons. final Integer callCount; if (count > MAX_CALL_TYPE_ICONS) { callCount = count; } else { callCount = null; } // The color to highlight the count and date in, if any. This is based on the first call. Integer highlightColor = isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null; // The date of this call, relative to the current time. CharSequence dateText = DateUtils.getRelativeTimeSpanString(details.date, getCurrentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); // Set the call count and date. setCallCountAndDate(views, callCount, dateText, highlightColor); CharSequence numberFormattedLabel = null; // Only show a label if the number is shown and it is not a SIP address. if (!TextUtils.isEmpty(details.number) && !PhoneNumberUtils.isUriNumber(details.number.toString())) { if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) { numberFormattedLabel = details.geocode; } else { numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType, details.numberLabel); } } final CharSequence nameText; final CharSequence numberText; final CharSequence labelText; final CharSequence displayNumber = mPhoneNumberHelper.getDisplayNumber(details.number, details.numberPresentation, details.formattedNumber); if (TextUtils.isEmpty(details.name)) { nameText = displayNumber; if (TextUtils.isEmpty(details.geocode) || mPhoneNumberUtilsWrapper.isVoicemailNumber(details.number)) { numberText = mResources.getString(R.string.call_log_empty_gecode); } else { numberText = details.geocode; } labelText = numberText; // We have a real phone number as "nameView" so make it always LTR views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR); } else { nameText = details.name; numberText = displayNumber; labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText : numberFormattedLabel; } final boolean isChineseLocale = (DeviceUtils.isLocale(Locale.CHINA) || DeviceUtils .isLocale(Locale.CHINESE)); if (isChineseLocale) { Cursor cr = null; try { cr = views.labelView .getContext() .getContentResolver() .query(Uri.parse("content://com.magicmod.mmgeoprovider/CN/" + String.valueOf(details.number)), null, null, null, null); if (cr.moveToFirst()) { String location = cr.getString(0); views.locationView.setText(location); views.locationView.setVisibility(TextUtils.isEmpty(location) ? View.INVISIBLE : View.VISIBLE); } + if (cr != null && !cr.isClosed()) { + cr.close(); + } } catch (Exception e) { // TODO: handle exception } finally { if (cr != null && !cr.isClosed()) { cr.close(); } } } else { views.locationView.setText(details.geocode); views.locationView.setVisibility(TextUtils.isEmpty(details.geocode) ? View.INVISIBLE : View.VISIBLE); } views.nameView.setText(nameText); views.labelView.setText(labelText); views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE); } /** Sets the text of the header view for the details page of a phone call. */ public void setCallDetailsHeader(TextView nameView, PhoneCallDetails details) { final CharSequence nameText; final CharSequence displayNumber = mPhoneNumberHelper.getDisplayNumber(details.number, details.numberPresentation, mResources.getString(R.string.recentCalls_addToContact)); if (TextUtils.isEmpty(details.name)) { nameText = displayNumber; } else { nameText = details.name; } nameView.setText(nameText); } @NeededForTesting public void setCurrentTimeForTest(long currentTimeMillis) { mCurrentTimeMillisForTest = currentTimeMillis; } /** * Returns the current time in milliseconds since the epoch. * <p> * It can be injected in tests using {@link #setCurrentTimeForTest(long)}. */ private long getCurrentTimeMillis() { if (mCurrentTimeMillisForTest == null) { return System.currentTimeMillis(); } else { return mCurrentTimeMillisForTest; } } /** Sets the call count and date. */ private void setCallCountAndDate(PhoneCallDetailsViews views, Integer callCount, CharSequence dateText, Integer highlightColor) { // Combine the count (if present) and the date. final CharSequence text; if (callCount != null) { text = mResources.getString( R.string.call_log_item_count_and_date, callCount.intValue(), dateText); } else { text = dateText; } // Apply the highlight color if present. final CharSequence formattedText; if (highlightColor != null) { formattedText = addBoldAndColor(text, highlightColor); } else { formattedText = text; } views.callTypeAndDate.setText(formattedText); } /** Creates a SpannableString for the given text which is bold and in the given color. */ private CharSequence addBoldAndColor(CharSequence text, int color) { int flags = Spanned.SPAN_INCLUSIVE_INCLUSIVE; SpannableString result = new SpannableString(text); result.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), flags); result.setSpan(new ForegroundColorSpan(color), 0, text.length(), flags); return result; } }
true
true
public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details, boolean isHighlighted) { // Display up to a given number of icons. views.callTypeIcons.clear(); int count = details.callTypes.length; for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) { views.callTypeIcons.add(details.callTypes[index]); } views.callTypeIcons.requestLayout(); views.callTypeIcons.setVisibility(View.VISIBLE); // Show the total call count only if there are more than the maximum number of icons. final Integer callCount; if (count > MAX_CALL_TYPE_ICONS) { callCount = count; } else { callCount = null; } // The color to highlight the count and date in, if any. This is based on the first call. Integer highlightColor = isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null; // The date of this call, relative to the current time. CharSequence dateText = DateUtils.getRelativeTimeSpanString(details.date, getCurrentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); // Set the call count and date. setCallCountAndDate(views, callCount, dateText, highlightColor); CharSequence numberFormattedLabel = null; // Only show a label if the number is shown and it is not a SIP address. if (!TextUtils.isEmpty(details.number) && !PhoneNumberUtils.isUriNumber(details.number.toString())) { if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) { numberFormattedLabel = details.geocode; } else { numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType, details.numberLabel); } } final CharSequence nameText; final CharSequence numberText; final CharSequence labelText; final CharSequence displayNumber = mPhoneNumberHelper.getDisplayNumber(details.number, details.numberPresentation, details.formattedNumber); if (TextUtils.isEmpty(details.name)) { nameText = displayNumber; if (TextUtils.isEmpty(details.geocode) || mPhoneNumberUtilsWrapper.isVoicemailNumber(details.number)) { numberText = mResources.getString(R.string.call_log_empty_gecode); } else { numberText = details.geocode; } labelText = numberText; // We have a real phone number as "nameView" so make it always LTR views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR); } else { nameText = details.name; numberText = displayNumber; labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText : numberFormattedLabel; } final boolean isChineseLocale = (DeviceUtils.isLocale(Locale.CHINA) || DeviceUtils .isLocale(Locale.CHINESE)); if (isChineseLocale) { Cursor cr = null; try { cr = views.labelView .getContext() .getContentResolver() .query(Uri.parse("content://com.magicmod.mmgeoprovider/CN/" + String.valueOf(details.number)), null, null, null, null); if (cr.moveToFirst()) { String location = cr.getString(0); views.locationView.setText(location); views.locationView.setVisibility(TextUtils.isEmpty(location) ? View.INVISIBLE : View.VISIBLE); } } catch (Exception e) { // TODO: handle exception } finally { if (cr != null && !cr.isClosed()) { cr.close(); } } } else { views.locationView.setText(details.geocode); views.locationView.setVisibility(TextUtils.isEmpty(details.geocode) ? View.INVISIBLE : View.VISIBLE); } views.nameView.setText(nameText); views.labelView.setText(labelText); views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE); }
public void setPhoneCallDetails(PhoneCallDetailsViews views, PhoneCallDetails details, boolean isHighlighted) { // Display up to a given number of icons. views.callTypeIcons.clear(); int count = details.callTypes.length; for (int index = 0; index < count && index < MAX_CALL_TYPE_ICONS; ++index) { views.callTypeIcons.add(details.callTypes[index]); } views.callTypeIcons.requestLayout(); views.callTypeIcons.setVisibility(View.VISIBLE); // Show the total call count only if there are more than the maximum number of icons. final Integer callCount; if (count > MAX_CALL_TYPE_ICONS) { callCount = count; } else { callCount = null; } // The color to highlight the count and date in, if any. This is based on the first call. Integer highlightColor = isHighlighted ? mCallTypeHelper.getHighlightedColor(details.callTypes[0]) : null; // The date of this call, relative to the current time. CharSequence dateText = DateUtils.getRelativeTimeSpanString(details.date, getCurrentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE); // Set the call count and date. setCallCountAndDate(views, callCount, dateText, highlightColor); CharSequence numberFormattedLabel = null; // Only show a label if the number is shown and it is not a SIP address. if (!TextUtils.isEmpty(details.number) && !PhoneNumberUtils.isUriNumber(details.number.toString())) { if (details.numberLabel == ContactInfo.GEOCODE_AS_LABEL) { numberFormattedLabel = details.geocode; } else { numberFormattedLabel = Phone.getTypeLabel(mResources, details.numberType, details.numberLabel); } } final CharSequence nameText; final CharSequence numberText; final CharSequence labelText; final CharSequence displayNumber = mPhoneNumberHelper.getDisplayNumber(details.number, details.numberPresentation, details.formattedNumber); if (TextUtils.isEmpty(details.name)) { nameText = displayNumber; if (TextUtils.isEmpty(details.geocode) || mPhoneNumberUtilsWrapper.isVoicemailNumber(details.number)) { numberText = mResources.getString(R.string.call_log_empty_gecode); } else { numberText = details.geocode; } labelText = numberText; // We have a real phone number as "nameView" so make it always LTR views.nameView.setTextDirection(View.TEXT_DIRECTION_LTR); } else { nameText = details.name; numberText = displayNumber; labelText = TextUtils.isEmpty(numberFormattedLabel) ? numberText : numberFormattedLabel; } final boolean isChineseLocale = (DeviceUtils.isLocale(Locale.CHINA) || DeviceUtils .isLocale(Locale.CHINESE)); if (isChineseLocale) { Cursor cr = null; try { cr = views.labelView .getContext() .getContentResolver() .query(Uri.parse("content://com.magicmod.mmgeoprovider/CN/" + String.valueOf(details.number)), null, null, null, null); if (cr.moveToFirst()) { String location = cr.getString(0); views.locationView.setText(location); views.locationView.setVisibility(TextUtils.isEmpty(location) ? View.INVISIBLE : View.VISIBLE); } if (cr != null && !cr.isClosed()) { cr.close(); } } catch (Exception e) { // TODO: handle exception } finally { if (cr != null && !cr.isClosed()) { cr.close(); } } } else { views.locationView.setText(details.geocode); views.locationView.setVisibility(TextUtils.isEmpty(details.geocode) ? View.INVISIBLE : View.VISIBLE); } views.nameView.setText(nameText); views.labelView.setText(labelText); views.labelView.setVisibility(TextUtils.isEmpty(labelText) ? View.GONE : View.VISIBLE); }
diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java index 67c92c88..15bd28fc 100644 --- a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java +++ b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java @@ -1,282 +1,285 @@ /** * 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.nutch.indexer.more; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.TimeZone; import org.apache.avro.util.Utf8; import org.apache.commons.lang.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.nutch.indexer.IndexingException; import org.apache.nutch.indexer.IndexingFilter; import org.apache.nutch.indexer.NutchDocument; import org.apache.nutch.metadata.HttpHeaders; import org.apache.nutch.net.protocols.HttpDateFormat; import org.apache.nutch.storage.WebPage; import org.apache.nutch.storage.WebPage.Field; import org.apache.nutch.util.MimeUtil; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.MatchResult; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.oro.text.regex.Perl5Pattern; import org.apache.tika.mime.MimeType; /** * Add (or reset) a few metaData properties as respective fields (if they are * available), so that they can be displayed by more.jsp (called by search.jsp). * * content-type is indexed to support query by type: last-modifed is indexed to * support query by date: * * Still need to make content-length searchable! * * @author John Xing */ public class MoreIndexingFilter implements IndexingFilter { public static final Logger LOG = LoggerFactory.getLogger(MoreIndexingFilter.class); /** Get the MimeTypes resolver instance. */ private MimeUtil MIME; private static Collection<WebPage.Field> FIELDS = new HashSet<WebPage.Field>(); static { FIELDS.add(WebPage.Field.HEADERS); FIELDS.add(WebPage.Field.CONTENT_TYPE); } @Override public NutchDocument filter(NutchDocument doc, String url, WebPage page) throws IndexingException { addTime(doc, page, url); addLength(doc, page, url); addType(doc, page, url); resetTitle(doc, page, url); return doc; } // Add time related meta info. Add last-modified if present. Index date as // last-modified, or, if that's not present, use fetch time. private NutchDocument addTime(NutchDocument doc, WebPage page, String url) { long time = -1; Utf8 lastModified = page .getFromHeaders(new Utf8(HttpHeaders.LAST_MODIFIED)); // String lastModified = data.getMeta(Metadata.LAST_MODIFIED); if (lastModified != null) { // try parse last-modified time = getTime(lastModified.toString(), url); // use as time // store as string doc.add("lastModified", Long.toString(time)); } if (time == -1) { // if no last-modified // time = datum.getFetchTime(); // use fetch time time = page.getFetchTime(); // use fetch time } // add support for query syntax date: // query filter is implemented in DateQueryFilter.java SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String dateString = sdf.format(new Date(time)); // un-stored, indexed and un-tokenized doc.add("date", dateString); return doc; } private long getTime(String date, String url) { long time = -1; try { time = HttpDateFormat.toLong(date); } catch (ParseException e) { // try to parse it as date in alternative format try { Date parsedDate = DateUtils.parseDate(date, new String[] { "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", "EEE MMM dd HH:mm:ss zzz yyyy", "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss", "EEE, dd-MMM-yy HH:mm:ss zzz", "yyyy/MM/dd HH:mm:ss.SSS zzz", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm", "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz", "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy zzz" }); time = parsedDate.getTime(); // if (LOG.isWarnEnabled()) { // LOG.warn(url + ": parsed date: " + date +" to:"+time); // } } catch (Exception e2) { if (LOG.isWarnEnabled()) { LOG.warn(url + ": can't parse erroneous date: " + date); } } } return time; } // Add Content-Length private NutchDocument addLength(NutchDocument doc, WebPage page, String url) { Utf8 contentLength = page.getFromHeaders(new Utf8( HttpHeaders.CONTENT_LENGTH)); if (contentLength != null) doc.add("contentLength", contentLength.toString()); return doc; } /** * <p> * Add Content-Type and its primaryType and subType add contentType, * primaryType and subType to field "type" as un-stored, indexed and * un-tokenized, so that search results can be confined by contentType or its * primaryType or its subType. * </p> * <p> * For example, if contentType is application/vnd.ms-powerpoint, search can be * done with one of the following qualifiers * type:application/vnd.ms-powerpoint type:application type:vnd.ms-powerpoint * all case insensitive. The query filter is implemented in * {@link TypeQueryFilter}. * </p> * * @param doc * @param data * @param url * @return */ private NutchDocument addType(NutchDocument doc, WebPage page, String url) { MimeType mimeType = null; Utf8 contentType = page.getFromHeaders(new Utf8(HttpHeaders.CONTENT_TYPE)); if (contentType == null) { // Note by Jerome Charron on 20050415: // Content Type not solved by a previous plugin // Or unable to solve it... Trying to find it // Should be better to use the doc content too // (using MimeTypes.getMimeType(byte[], String), but I don't know // which field it is? // if (MAGIC) { // contentType = MIME.getMimeType(url, content); // } else { // contentType = MIME.getMimeType(url); // } mimeType = MIME.getMimeType(url); } else { mimeType = MIME.forName(MimeUtil.cleanMimeType(contentType.toString())); } // Checks if we solved the content-type. if (mimeType == null) { return doc; } String scontentType = mimeType.getName(); doc.add("type", scontentType); - String[] parts = getParts(scontentType); + // Check if we need to split the content type in sub parts + if (conf.getBoolean("moreIndexingFilter.indexMimeTypeParts", true)) { + String[] parts = getParts(contentType); - for (String part : parts) { - doc.add("type", part); + for(String part: parts) { + doc.add("type", part); + } } // leave this for future improvement // MimeTypeParameterList parameterList = mimeType.getParameters() return doc; } /** * Utility method for splitting mime type into type and subtype. * * @param mimeType * @return */ static String[] getParts(String mimeType) { return mimeType.split("/"); } // Reset title if we see non-standard HTTP header "Content-Disposition". // It's a good indication that content provider wants filename therein // be used as the title of this url. // Patterns used to extract filename from possible non-standard // HTTP header "Content-Disposition". Typically it looks like: // Content-Disposition: inline; filename="foo.ppt" private PatternMatcher matcher = new Perl5Matcher(); private Configuration conf; static Perl5Pattern patterns[] = { null, null }; static { Perl5Compiler compiler = new Perl5Compiler(); try { // order here is important patterns[0] = (Perl5Pattern) compiler .compile("\\bfilename=['\"](.+)['\"]"); patterns[1] = (Perl5Pattern) compiler.compile("\\bfilename=(\\S+)\\b"); } catch (MalformedPatternException e) { // just ignore } } private NutchDocument resetTitle(NutchDocument doc, WebPage page, String url) { Utf8 contentDisposition = page.getFromHeaders(new Utf8( HttpHeaders.CONTENT_DISPOSITION)); if (contentDisposition == null) return doc; MatchResult result; for (int i = 0; i < patterns.length; i++) { if (matcher.contains(contentDisposition.toString(), patterns[i])) { result = matcher.getMatch(); doc.add("title", result.group(1)); break; } } return doc; } public void addIndexBackendOptions(Configuration conf) { } public void setConf(Configuration conf) { this.conf = conf; MIME = new MimeUtil(conf); } public Configuration getConf() { return this.conf; } @Override public Collection<Field> getFields() { return FIELDS; } }
false
true
private NutchDocument addType(NutchDocument doc, WebPage page, String url) { MimeType mimeType = null; Utf8 contentType = page.getFromHeaders(new Utf8(HttpHeaders.CONTENT_TYPE)); if (contentType == null) { // Note by Jerome Charron on 20050415: // Content Type not solved by a previous plugin // Or unable to solve it... Trying to find it // Should be better to use the doc content too // (using MimeTypes.getMimeType(byte[], String), but I don't know // which field it is? // if (MAGIC) { // contentType = MIME.getMimeType(url, content); // } else { // contentType = MIME.getMimeType(url); // } mimeType = MIME.getMimeType(url); } else { mimeType = MIME.forName(MimeUtil.cleanMimeType(contentType.toString())); } // Checks if we solved the content-type. if (mimeType == null) { return doc; } String scontentType = mimeType.getName(); doc.add("type", scontentType); String[] parts = getParts(scontentType); for (String part : parts) { doc.add("type", part); } // leave this for future improvement // MimeTypeParameterList parameterList = mimeType.getParameters() return doc; }
private NutchDocument addType(NutchDocument doc, WebPage page, String url) { MimeType mimeType = null; Utf8 contentType = page.getFromHeaders(new Utf8(HttpHeaders.CONTENT_TYPE)); if (contentType == null) { // Note by Jerome Charron on 20050415: // Content Type not solved by a previous plugin // Or unable to solve it... Trying to find it // Should be better to use the doc content too // (using MimeTypes.getMimeType(byte[], String), but I don't know // which field it is? // if (MAGIC) { // contentType = MIME.getMimeType(url, content); // } else { // contentType = MIME.getMimeType(url); // } mimeType = MIME.getMimeType(url); } else { mimeType = MIME.forName(MimeUtil.cleanMimeType(contentType.toString())); } // Checks if we solved the content-type. if (mimeType == null) { return doc; } String scontentType = mimeType.getName(); doc.add("type", scontentType); // Check if we need to split the content type in sub parts if (conf.getBoolean("moreIndexingFilter.indexMimeTypeParts", true)) { String[] parts = getParts(contentType); for(String part: parts) { doc.add("type", part); } } // leave this for future improvement // MimeTypeParameterList parameterList = mimeType.getParameters() return doc; }
diff --git a/src/com/fsck/k9/Account.java b/src/com/fsck/k9/Account.java index 5038307..c43c2d3 100644 --- a/src/com/fsck/k9/Account.java +++ b/src/com/fsck/k9/Account.java @@ -1,1275 +1,1279 @@ package com.fsck.k9; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.Uri; import android.util.Log; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Store; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * Account stores all of the settings for a single account defined by the user. It is able to save * and delete itself given a Preferences to work with. Each account is defined by a UUID. */ public class Account implements BaseAccount { public static final String EXPUNGE_IMMEDIATELY = "EXPUNGE_IMMEDIATELY"; public static final String EXPUNGE_MANUALLY = "EXPUNGE_MANUALLY"; public static final String EXPUNGE_ON_POLL = "EXPUNGE_ON_POLL"; public static final int DELETE_POLICY_NEVER = 0; public static final int DELETE_POLICY_7DAYS = 1; public static final int DELETE_POLICY_ON_DELETE = 2; public static final int DELETE_POLICY_MARK_AS_READ = 3; public static final String TYPE_WIFI = "WIFI"; public static final String TYPE_MOBILE = "MOBILE"; public static final String TYPE_OTHER = "OTHER"; private static String[] networkTypes = { TYPE_WIFI, TYPE_MOBILE, TYPE_OTHER }; /** * <pre> * 0 - Never (DELETE_POLICY_NEVER) * 1 - After 7 days (DELETE_POLICY_7DAYS) * 2 - When I delete from inbox (DELETE_POLICY_ON_DELETE) * 3 - Mark as read (DELETE_POLICY_MARK_AS_READ) * </pre> */ private int mDeletePolicy; private String mUuid; private String mStoreUri; private String mLocalStoreUri; private String mTransportUri; private String mDescription; private String mAlwaysBcc; private int mAutomaticCheckIntervalMinutes; private int mDisplayCount; private int mChipColor; private int mLedColor; private long mLastAutomaticCheckTime; private boolean mNotifyNewMail; private boolean mNotifySelfNewMail; private String mDraftsFolderName; private String mSentFolderName; private String mTrashFolderName; private String mOutboxFolderName; private String mAutoExpandFolderName; private FolderMode mFolderDisplayMode; private FolderMode mFolderSyncMode; private FolderMode mFolderPushMode; private FolderMode mFolderTargetMode; private int mAccountNumber; private boolean mVibrate; private boolean mRing; private boolean mSaveAllHeaders; private boolean mPushPollOnConnect; private String mRingtoneUri; private boolean mNotifySync; private HideButtons mHideMessageViewButtons; private boolean mIsSignatureBeforeQuotedText; private String mExpungePolicy = EXPUNGE_IMMEDIATELY; private int mMaxPushFolders; private int mIdleRefreshMinutes; private boolean goToUnreadMessageSearch; private Map<String, Boolean> compressionMap = new ConcurrentHashMap<String, Boolean>(); private Searchable searchableFolders; private boolean subscribedFoldersOnly; private int maximumPolledMessageAge; // Tracks if we have sent a notification for this account for // current set of fetched messages private boolean mRingNotified; private List<Identity> identities; public enum FolderMode { NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS; } public enum HideButtons { NEVER, ALWAYS, KEYBOARD_AVAILABLE; } public enum Searchable { ALL, DISPLAYABLE, NONE } protected Account(Context context) { // TODO Change local store path to something readable / recognizable mUuid = UUID.randomUUID().toString(); mLocalStoreUri = "local://localhost/" + context.getDatabasePath(mUuid + ".db"); mAutomaticCheckIntervalMinutes = -1; mIdleRefreshMinutes = 24; mSaveAllHeaders = false; mPushPollOnConnect = true; mDisplayCount = -1; mAccountNumber = -1; mNotifyNewMail = true; mNotifySync = true; mVibrate = false; mRing = true; mNotifySelfNewMail = true; mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; mFolderSyncMode = FolderMode.FIRST_CLASS; mFolderPushMode = FolderMode.FIRST_CLASS; mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; mHideMessageViewButtons = HideButtons.NEVER; mRingtoneUri = "content://settings/system/notification_sound"; mIsSignatureBeforeQuotedText = false; mExpungePolicy = EXPUNGE_IMMEDIATELY; mAutoExpandFolderName = "INBOX"; mMaxPushFolders = 10; mChipColor = (new Random()).nextInt(0xffffff) + 0xff000000; mLedColor = mChipColor; goToUnreadMessageSearch = false; subscribedFoldersOnly = false; maximumPolledMessageAge = 10; searchableFolders = Searchable.ALL; identities = new ArrayList<Identity>(); Identity identity = new Identity(); identity.setSignatureUse(true); identity.setSignature(context.getString(R.string.default_signature)); identity.setDescription(context.getString(R.string.default_identity_description)); identities.add(identity); } protected Account(Preferences preferences, String uuid) { this.mUuid = uuid; loadAccount(preferences); } /** * Load stored settings for this account. */ private synchronized void loadAccount(Preferences preferences) { mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".storeUri", null)); mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null); mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".transportUri", null)); mDescription = preferences.getPreferences().getString(mUuid + ".description", null); mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc); mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid + ".automaticCheckIntervalMinutes", -1); mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid + ".idleRefreshMinutes", 24); mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid + ".saveAllHeaders", false); mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid + ".pushPollOnConnect", true); mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); + if (mDisplayCount < 0) + { + mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; + } mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid + ".lastAutomaticCheckTime", 0); mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail", false); mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck", false); mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0); mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName", "Drafts"); mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName", "Sent"); mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName", "Trash"); mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName", "Outbox"); mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY); mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10); goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch", false); subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly", false); maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid + ".maximumPolledMessageAge", -1); for (String type : networkTypes) { Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type, true); compressionMap.put(type, useCompression); } // Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were // opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code // should be deleted sometime soon if (mDraftsFolderName == null || mDraftsFolderName.equals("")) { mDraftsFolderName = "Drafts"; } if (mSentFolderName == null || mSentFolderName.equals("")) { mSentFolderName = "Sent"; } if (mTrashFolderName == null || mTrashFolderName.equals("")) { mTrashFolderName = "Trash"; } if (mOutboxFolderName == null || mOutboxFolderName.equals("")) { mOutboxFolderName = "Outbox"; } // End of 0.103 repair mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName", "INBOX"); mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0); Random random = new Random((long)mAccountNumber+4); mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor", (random.nextInt(0x70)) + (random.nextInt(0x70) * 0xff) + (random.nextInt(0x70) * 0xffff) + 0xff000000); mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor); mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false); mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true); try { mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum", HideButtons.NEVER.name())); } catch (Exception e) { mHideMessageViewButtons = HideButtons.NEVER; } mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone", "content://settings/system/notification_sound"); try { mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; } try { mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderSyncMode = FolderMode.FIRST_CLASS; } try { mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderPushMode = FolderMode.FIRST_CLASS; } try { mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; } try { searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders", Searchable.ALL.name())); } catch (Exception e) { searchableFolders = Searchable.ALL; } mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false); identities = loadIdentities(preferences.getPreferences()); } protected synchronized void delete(Preferences preferences) { String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(","); StringBuffer sb = new StringBuffer(); for (int i = 0, length = uuids.length; i < length; i++) { if (!uuids[i].equals(mUuid)) { if (sb.length() > 0) { sb.append(','); } sb.append(uuids[i]); } } String accountUuids = sb.toString(); SharedPreferences.Editor editor = preferences.getPreferences().edit(); editor.putString("accountUuids", accountUuids); editor.remove(mUuid + ".storeUri"); editor.remove(mUuid + ".localStoreUri"); editor.remove(mUuid + ".transportUri"); editor.remove(mUuid + ".description"); editor.remove(mUuid + ".name"); editor.remove(mUuid + ".email"); editor.remove(mUuid + ".alwaysBcc"); editor.remove(mUuid + ".automaticCheckIntervalMinutes"); editor.remove(mUuid + ".pushPollOnConnect"); editor.remove(mUuid + ".saveAllHeaders"); editor.remove(mUuid + ".idleRefreshMinutes"); editor.remove(mUuid + ".lastAutomaticCheckTime"); editor.remove(mUuid + ".notifyNewMail"); editor.remove(mUuid + ".notifySelfNewMail"); editor.remove(mUuid + ".deletePolicy"); editor.remove(mUuid + ".draftsFolderName"); editor.remove(mUuid + ".sentFolderName"); editor.remove(mUuid + ".trashFolderName"); editor.remove(mUuid + ".outboxFolderName"); editor.remove(mUuid + ".autoExpandFolderName"); editor.remove(mUuid + ".accountNumber"); editor.remove(mUuid + ".vibrate"); editor.remove(mUuid + ".ring"); editor.remove(mUuid + ".ringtone"); editor.remove(mUuid + ".lastFullSync"); editor.remove(mUuid + ".folderDisplayMode"); editor.remove(mUuid + ".folderSyncMode"); editor.remove(mUuid + ".folderPushMode"); editor.remove(mUuid + ".folderTargetMode"); editor.remove(mUuid + ".hideButtonsEnum"); editor.remove(mUuid + ".signatureBeforeQuotedText"); editor.remove(mUuid + ".expungePolicy"); editor.remove(mUuid + ".maxPushFolders"); editor.remove(mUuid + ".searchableFolders"); editor.remove(mUuid + ".chipColor"); editor.remove(mUuid + ".ledColor"); editor.remove(mUuid + ".goToUnreadMessageSearch"); editor.remove(mUuid + ".subscribedFoldersOnly"); editor.remove(mUuid + ".maximumPolledMessageAge"); for (String type : networkTypes) { editor.remove(mUuid + ".useCompression." + type); } deleteIdentities(preferences.getPreferences(), editor); editor.commit(); } public synchronized void save(Preferences preferences) { SharedPreferences.Editor editor = preferences.getPreferences().edit(); if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid)) { /* * When the account is first created we assign it a unique account number. The * account number will be unique to that account for the lifetime of the account. * So, we get all the existing account numbers, sort them ascending, loop through * the list and check if the number is greater than 1 + the previous number. If so * we use the previous number + 1 as the account number. This refills gaps. * mAccountNumber starts as -1 on a newly created account. It must be -1 for this * algorithm to work. * * I bet there is a much smarter way to do this. Anyone like to suggest it? */ Account[] accounts = preferences.getAccounts(); int[] accountNumbers = new int[accounts.length]; for (int i = 0; i < accounts.length; i++) { accountNumbers[i] = accounts[i].getAccountNumber(); } Arrays.sort(accountNumbers); for (int accountNumber : accountNumbers) { if (accountNumber > mAccountNumber + 1) { break; } mAccountNumber = accountNumber; } mAccountNumber++; String accountUuids = preferences.getPreferences().getString("accountUuids", ""); accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid; editor.putString("accountUuids", accountUuids); } editor.putString(mUuid + ".storeUri", Utility.base64Encode(mStoreUri)); editor.putString(mUuid + ".localStoreUri", mLocalStoreUri); editor.putString(mUuid + ".transportUri", Utility.base64Encode(mTransportUri)); editor.putString(mUuid + ".description", mDescription); editor.putString(mUuid + ".alwaysBcc", mAlwaysBcc); editor.putInt(mUuid + ".automaticCheckIntervalMinutes", mAutomaticCheckIntervalMinutes); editor.putInt(mUuid + ".idleRefreshMinutes", mIdleRefreshMinutes); editor.putBoolean(mUuid + ".saveAllHeaders", mSaveAllHeaders); editor.putBoolean(mUuid + ".pushPollOnConnect", mPushPollOnConnect); editor.putInt(mUuid + ".displayCount", mDisplayCount); editor.putLong(mUuid + ".lastAutomaticCheckTime", mLastAutomaticCheckTime); editor.putBoolean(mUuid + ".notifyNewMail", mNotifyNewMail); editor.putBoolean(mUuid + ".notifySelfNewMail", mNotifySelfNewMail); editor.putBoolean(mUuid + ".notifyMailCheck", mNotifySync); editor.putInt(mUuid + ".deletePolicy", mDeletePolicy); editor.putString(mUuid + ".draftsFolderName", mDraftsFolderName); editor.putString(mUuid + ".sentFolderName", mSentFolderName); editor.putString(mUuid + ".trashFolderName", mTrashFolderName); editor.putString(mUuid + ".outboxFolderName", mOutboxFolderName); editor.putString(mUuid + ".autoExpandFolderName", mAutoExpandFolderName); editor.putInt(mUuid + ".accountNumber", mAccountNumber); editor.putBoolean(mUuid + ".vibrate", mVibrate); editor.putBoolean(mUuid + ".ring", mRing); editor.putString(mUuid + ".hideButtonsEnum", mHideMessageViewButtons.name()); editor.putString(mUuid + ".ringtone", mRingtoneUri); editor.putString(mUuid + ".folderDisplayMode", mFolderDisplayMode.name()); editor.putString(mUuid + ".folderSyncMode", mFolderSyncMode.name()); editor.putString(mUuid + ".folderPushMode", mFolderPushMode.name()); editor.putString(mUuid + ".folderTargetMode", mFolderTargetMode.name()); editor.putBoolean(mUuid + ".signatureBeforeQuotedText", this.mIsSignatureBeforeQuotedText); editor.putString(mUuid + ".expungePolicy", mExpungePolicy); editor.putInt(mUuid + ".maxPushFolders", mMaxPushFolders); editor.putString(mUuid + ".searchableFolders", searchableFolders.name()); editor.putInt(mUuid + ".chipColor", mChipColor); editor.putInt(mUuid + ".ledColor", mLedColor); editor.putBoolean(mUuid + ".goToUnreadMessageSearch", goToUnreadMessageSearch); editor.putBoolean(mUuid + ".subscribedFoldersOnly", subscribedFoldersOnly); editor.putInt(mUuid + ".maximumPolledMessageAge", maximumPolledMessageAge); for (String type : networkTypes) { Boolean useCompression = compressionMap.get(type); if (useCompression != null) { editor.putBoolean(mUuid + ".useCompression." + type, useCompression); } } saveIdentities(preferences.getPreferences(), editor); editor.commit(); } //TODO: Shouldn't this live in MessagingController? // Why should everything be in MessagingController? This is an Account-specific operation. --danapple0 public AccountStats getStats(Context context) throws MessagingException { long startTime = System.currentTimeMillis(); AccountStats stats = new AccountStats(); int unreadMessageCount = 0; int flaggedMessageCount = 0; LocalStore localStore = getLocalStore(); if (K9.measureAccounts()) { stats.size = localStore.getSize(); } Account.FolderMode aMode = getFolderDisplayMode(); Preferences prefs = Preferences.getPreferences(context); long folderLoadStart = System.currentTimeMillis(); List<? extends Folder> folders = localStore.getPersonalNamespaces(false); long folderLoadEnd = System.currentTimeMillis(); long folderEvalStart = folderLoadEnd; for (Folder folder : folders) { LocalFolder localFolder = (LocalFolder)folder; //folder.refresh(prefs); Folder.FolderClass fMode = localFolder.getDisplayClass(prefs); if (folder.getName().equals(getTrashFolderName()) == false && folder.getName().equals(getDraftsFolderName()) == false && folder.getName().equals(getOutboxFolderName()) == false && folder.getName().equals(getSentFolderName()) == false && folder.getName().equals(getErrorFolderName()) == false) { if (aMode == Account.FolderMode.NONE) { continue; } if (aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) { continue; } if (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) { continue; } if (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS) { continue; } unreadMessageCount += folder.getUnreadMessageCount(); flaggedMessageCount += folder.getFlaggedMessageCount(); } } long folderEvalEnd = System.currentTimeMillis(); stats.unreadMessageCount = unreadMessageCount; stats.flaggedMessageCount = flaggedMessageCount; long endTime = System.currentTimeMillis(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Account.getStats() on " + getDescription() + " took " + (endTime - startTime) + " ms;" + " loading " + folders.size() + " took " + (folderLoadEnd - folderLoadStart) + " ms;" + " evaluating took " + (folderEvalEnd - folderEvalStart) + " ms"); return stats; } public void setChipColor(int color) { mChipColor = color; } public int getChipColor() { return mChipColor; } public void setLedColor(int color) { mLedColor = color; } public int getLedColor() { return mLedColor; } public String getUuid() { return mUuid; } public Uri getContentUri() { return Uri.parse("content://accounts/" + getUuid()); } public synchronized String getStoreUri() { return mStoreUri; } public synchronized void setStoreUri(String storeUri) { this.mStoreUri = storeUri; } public synchronized String getTransportUri() { return mTransportUri; } public synchronized void setTransportUri(String transportUri) { this.mTransportUri = transportUri; } public synchronized String getDescription() { return mDescription; } public synchronized void setDescription(String description) { this.mDescription = description; } public synchronized String getName() { return identities.get(0).getName(); } public synchronized void setName(String name) { identities.get(0).setName(name); } public synchronized boolean getSignatureUse() { return identities.get(0).getSignatureUse(); } public synchronized void setSignatureUse(boolean signatureUse) { identities.get(0).setSignatureUse(signatureUse); } public synchronized String getSignature() { return identities.get(0).getSignature(); } public synchronized void setSignature(String signature) { identities.get(0).setSignature(signature); } public synchronized String getEmail() { return identities.get(0).getEmail(); } public synchronized void setEmail(String email) { identities.get(0).setEmail(email); } public synchronized String getAlwaysBcc() { return mAlwaysBcc; } public synchronized void setAlwaysBcc(String alwaysBcc) { this.mAlwaysBcc = alwaysBcc; } public synchronized boolean isVibrate() { return mVibrate; } public synchronized void setVibrate(boolean vibrate) { mVibrate = vibrate; } /* Have we sent a new mail notification on this account */ public boolean isRingNotified() { return mRingNotified; } public void setRingNotified(boolean ringNotified) { mRingNotified = ringNotified; } public synchronized String getRingtone() { return mRingtoneUri; } public synchronized void setRingtone(String ringtoneUri) { mRingtoneUri = ringtoneUri; } public synchronized String getLocalStoreUri() { return mLocalStoreUri; } public synchronized void setLocalStoreUri(String localStoreUri) { this.mLocalStoreUri = localStoreUri; } /** * Returns -1 for never. */ public synchronized int getAutomaticCheckIntervalMinutes() { return mAutomaticCheckIntervalMinutes; } /** * @param automaticCheckIntervalMinutes or -1 for never. */ public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes) { int oldInterval = this.mAutomaticCheckIntervalMinutes; int newInterval = automaticCheckIntervalMinutes; this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes; return (oldInterval != newInterval); } public synchronized int getDisplayCount() { return mDisplayCount; } public synchronized void setDisplayCount(int displayCount) { if (displayCount != -1) { this.mDisplayCount = displayCount; } else { this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } } public synchronized long getLastAutomaticCheckTime() { return mLastAutomaticCheckTime; } public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime) { this.mLastAutomaticCheckTime = lastAutomaticCheckTime; } public synchronized boolean isNotifyNewMail() { return mNotifyNewMail; } public synchronized void setNotifyNewMail(boolean notifyNewMail) { this.mNotifyNewMail = notifyNewMail; } public synchronized int getDeletePolicy() { return mDeletePolicy; } public synchronized void setDeletePolicy(int deletePolicy) { this.mDeletePolicy = deletePolicy; } public synchronized String getDraftsFolderName() { return mDraftsFolderName; } public synchronized void setDraftsFolderName(String draftsFolderName) { mDraftsFolderName = draftsFolderName; } public synchronized String getSentFolderName() { return mSentFolderName; } public synchronized String getErrorFolderName() { return K9.ERROR_FOLDER_NAME; } public synchronized void setSentFolderName(String sentFolderName) { mSentFolderName = sentFolderName; } public synchronized String getTrashFolderName() { return mTrashFolderName; } public synchronized void setTrashFolderName(String trashFolderName) { mTrashFolderName = trashFolderName; } public synchronized String getOutboxFolderName() { return mOutboxFolderName; } public synchronized void setOutboxFolderName(String outboxFolderName) { mOutboxFolderName = outboxFolderName; } public synchronized String getAutoExpandFolderName() { return mAutoExpandFolderName; } public synchronized void setAutoExpandFolderName(String autoExpandFolderName) { mAutoExpandFolderName = autoExpandFolderName; } public synchronized int getAccountNumber() { return mAccountNumber; } public synchronized FolderMode getFolderDisplayMode() { return mFolderDisplayMode; } public synchronized boolean setFolderDisplayMode(FolderMode displayMode) { FolderMode oldDisplayMode = mFolderDisplayMode; mFolderDisplayMode = displayMode; return oldDisplayMode != displayMode; } public synchronized FolderMode getFolderSyncMode() { return mFolderSyncMode; } public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = mFolderSyncMode; mFolderSyncMode = syncMode; if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE) { return true; } return false; } public synchronized FolderMode getFolderPushMode() { return mFolderPushMode; } public synchronized boolean setFolderPushMode(FolderMode pushMode) { FolderMode oldPushMode = mFolderPushMode; mFolderPushMode = pushMode; return pushMode != oldPushMode; } public synchronized boolean isShowOngoing() { return mNotifySync; } public synchronized void setShowOngoing(boolean showOngoing) { this.mNotifySync = showOngoing; } public synchronized HideButtons getHideMessageViewButtons() { return mHideMessageViewButtons; } public synchronized void setHideMessageViewButtons(HideButtons hideMessageViewButtons) { mHideMessageViewButtons = hideMessageViewButtons; } public synchronized FolderMode getFolderTargetMode() { return mFolderTargetMode; } public synchronized void setFolderTargetMode(FolderMode folderTargetMode) { mFolderTargetMode = folderTargetMode; } public synchronized boolean isSignatureBeforeQuotedText() { return mIsSignatureBeforeQuotedText; } public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText) { this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText; } public synchronized boolean isNotifySelfNewMail() { return mNotifySelfNewMail; } public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail) { mNotifySelfNewMail = notifySelfNewMail; } public synchronized String getExpungePolicy() { return mExpungePolicy; } public synchronized void setExpungePolicy(String expungePolicy) { mExpungePolicy = expungePolicy; } public synchronized int getMaxPushFolders() { return mMaxPushFolders; } public synchronized boolean setMaxPushFolders(int maxPushFolders) { int oldMaxPushFolders = mMaxPushFolders; mMaxPushFolders = maxPushFolders; return oldMaxPushFolders != maxPushFolders; } public synchronized boolean isRing() { return mRing; } public synchronized void setRing(boolean ring) { mRing = ring; } public LocalStore getLocalStore() throws MessagingException { return Store.getLocalInstance(this, K9.app); } public Store getRemoteStore() throws MessagingException { return Store.getRemoteInstance(this); } @Override public synchronized String toString() { return mDescription; } public void setCompression(String networkType, boolean useCompression) { compressionMap.put(networkType, useCompression); } public boolean useCompression(String networkType) { Boolean useCompression = compressionMap.get(networkType); if (useCompression == null) { return true; } else { return useCompression; } } public boolean useCompression(int type) { String networkType = TYPE_OTHER; switch (type) { case ConnectivityManager.TYPE_MOBILE: networkType = TYPE_MOBILE; break; case ConnectivityManager.TYPE_WIFI: networkType = TYPE_WIFI; break; } return useCompression(networkType); } @Override public boolean equals(Object o) { if (o instanceof Account) { return ((Account)o).mUuid.equals(mUuid); } return super.equals(o); } @Override public int hashCode() { return mUuid.hashCode(); } private synchronized List<Identity> loadIdentities(SharedPreferences prefs) { List<Identity> newIdentities = new ArrayList<Identity>(); int ident = 0; boolean gotOne = false; do { gotOne = false; String name = prefs.getString(mUuid + ".name." + ident, null); String email = prefs.getString(mUuid + ".email." + ident, null); boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true); String signature = prefs.getString(mUuid + ".signature." + ident, null); String description = prefs.getString(mUuid + ".description." + ident, null); if (email != null) { Identity identity = new Identity(); identity.setName(name); identity.setEmail(email); identity.setSignatureUse(signatureUse); identity.setSignature(signature); identity.setDescription(description); newIdentities.add(identity); gotOne = true; } ident++; } while (gotOne); if (newIdentities.size() == 0) { String name = prefs.getString(mUuid + ".name", null); String email = prefs.getString(mUuid + ".email", null); boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true); String signature = prefs.getString(mUuid + ".signature", null); Identity identity = new Identity(); identity.setName(name); identity.setEmail(email); identity.setSignatureUse(signatureUse); identity.setSignature(signature); identity.setDescription(email); newIdentities.add(identity); } return newIdentities; } private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { int ident = 0; boolean gotOne = false; do { gotOne = false; String email = prefs.getString(mUuid + ".email." + ident, null); if (email != null) { editor.remove(mUuid + ".name." + ident); editor.remove(mUuid + ".email." + ident); editor.remove(mUuid + ".signatureUse." + ident); editor.remove(mUuid + ".signature." + ident); editor.remove(mUuid + ".description." + ident); gotOne = true; } ident++; } while (gotOne); } private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor) { deleteIdentities(prefs, editor); int ident = 0; for (Identity identity : identities) { editor.putString(mUuid + ".name." + ident, identity.getName()); editor.putString(mUuid + ".email." + ident, identity.getEmail()); editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse()); editor.putString(mUuid + ".signature." + ident, identity.getSignature()); editor.putString(mUuid + ".description." + ident, identity.getDescription()); ident++; } } public synchronized List<Identity> getIdentities() { return identities; } public synchronized void setIdentities(List<Identity> newIdentities) { identities = new ArrayList<Identity>(newIdentities); } public synchronized Identity getIdentity(int i) { if (i < identities.size()) { return identities.get(i); } return null; } public boolean isAnIdentity(Address[] addrs) { if (addrs == null) { return false; } for (Address addr : addrs) { if (findIdentity(addr) != null) { return true; } } return false; } public boolean isAnIdentity(Address addr) { return findIdentity(addr) != null; } public synchronized Identity findIdentity(Address addr) { for (Identity identity : identities) { String email = identity.getEmail(); if (email != null && email.equalsIgnoreCase(addr.getAddress())) { return identity; } } return null; } public Searchable getSearchableFolders() { return searchableFolders; } public void setSearchableFolders(Searchable searchableFolders) { this.searchableFolders = searchableFolders; } public int getIdleRefreshMinutes() { return mIdleRefreshMinutes; } public void setIdleRefreshMinutes(int idleRefreshMinutes) { mIdleRefreshMinutes = idleRefreshMinutes; } public boolean isPushPollOnConnect() { return mPushPollOnConnect; } public void setPushPollOnConnect(boolean pushPollOnConnect) { mPushPollOnConnect = pushPollOnConnect; } public boolean isSaveAllHeaders() { return mSaveAllHeaders; } public void setSaveAllHeaders(boolean saveAllHeaders) { mSaveAllHeaders = saveAllHeaders; } public boolean goToUnreadMessageSearch() { return goToUnreadMessageSearch; } public void setGoToUnreadMessageSearch(boolean goToUnreadMessageSearch) { this.goToUnreadMessageSearch = goToUnreadMessageSearch; } public boolean subscribedFoldersOnly() { return subscribedFoldersOnly; } public void setSubscribedFoldersOnly(boolean subscribedFoldersOnly) { this.subscribedFoldersOnly = subscribedFoldersOnly; } public int getMaximumPolledMessageAge() { return maximumPolledMessageAge; } public void setMaximumPolledMessageAge(int maximumPolledMessageAge) { this.maximumPolledMessageAge = maximumPolledMessageAge; } public Date getEarliestPollDate() { int age = getMaximumPolledMessageAge(); if (age < 0 == false) { Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR_OF_DAY, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (age < 28) { now.add(Calendar.DATE, age * -1); } else switch (age) { case 28: now.add(Calendar.MONTH, -1); break; case 56: now.add(Calendar.MONTH, -2); break; case 84: now.add(Calendar.MONTH, -3); break; case 168: now.add(Calendar.MONTH, -6); break; case 365: now.add(Calendar.YEAR, -1); break; } return now.getTime(); } else { return null; } } }
true
true
private synchronized void loadAccount(Preferences preferences) { mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".storeUri", null)); mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null); mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".transportUri", null)); mDescription = preferences.getPreferences().getString(mUuid + ".description", null); mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc); mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid + ".automaticCheckIntervalMinutes", -1); mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid + ".idleRefreshMinutes", 24); mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid + ".saveAllHeaders", false); mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid + ".pushPollOnConnect", true); mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid + ".lastAutomaticCheckTime", 0); mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail", false); mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck", false); mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0); mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName", "Drafts"); mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName", "Sent"); mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName", "Trash"); mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName", "Outbox"); mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY); mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10); goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch", false); subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly", false); maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid + ".maximumPolledMessageAge", -1); for (String type : networkTypes) { Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type, true); compressionMap.put(type, useCompression); } // Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were // opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code // should be deleted sometime soon if (mDraftsFolderName == null || mDraftsFolderName.equals("")) { mDraftsFolderName = "Drafts"; } if (mSentFolderName == null || mSentFolderName.equals("")) { mSentFolderName = "Sent"; } if (mTrashFolderName == null || mTrashFolderName.equals("")) { mTrashFolderName = "Trash"; } if (mOutboxFolderName == null || mOutboxFolderName.equals("")) { mOutboxFolderName = "Outbox"; } // End of 0.103 repair mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName", "INBOX"); mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0); Random random = new Random((long)mAccountNumber+4); mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor", (random.nextInt(0x70)) + (random.nextInt(0x70) * 0xff) + (random.nextInt(0x70) * 0xffff) + 0xff000000); mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor); mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false); mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true); try { mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum", HideButtons.NEVER.name())); } catch (Exception e) { mHideMessageViewButtons = HideButtons.NEVER; } mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone", "content://settings/system/notification_sound"); try { mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; } try { mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderSyncMode = FolderMode.FIRST_CLASS; } try { mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderPushMode = FolderMode.FIRST_CLASS; } try { mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; } try { searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders", Searchable.ALL.name())); } catch (Exception e) { searchableFolders = Searchable.ALL; } mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false); identities = loadIdentities(preferences.getPreferences()); }
private synchronized void loadAccount(Preferences preferences) { mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".storeUri", null)); mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null); mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid + ".transportUri", null)); mDescription = preferences.getPreferences().getString(mUuid + ".description", null); mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc); mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid + ".automaticCheckIntervalMinutes", -1); mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid + ".idleRefreshMinutes", 24); mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid + ".saveAllHeaders", false); mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid + ".pushPollOnConnect", true); mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT); if (mDisplayCount < 0) { mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT; } mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid + ".lastAutomaticCheckTime", 0); mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail", false); mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail", true); mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck", false); mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0); mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName", "Drafts"); mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName", "Sent"); mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName", "Trash"); mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName", "Outbox"); mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY); mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10); goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch", false); subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly", false); maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid + ".maximumPolledMessageAge", -1); for (String type : networkTypes) { Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type, true); compressionMap.put(type, useCompression); } // Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were // opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code // should be deleted sometime soon if (mDraftsFolderName == null || mDraftsFolderName.equals("")) { mDraftsFolderName = "Drafts"; } if (mSentFolderName == null || mSentFolderName.equals("")) { mSentFolderName = "Sent"; } if (mTrashFolderName == null || mTrashFolderName.equals("")) { mTrashFolderName = "Trash"; } if (mOutboxFolderName == null || mOutboxFolderName.equals("")) { mOutboxFolderName = "Outbox"; } // End of 0.103 repair mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName", "INBOX"); mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0); Random random = new Random((long)mAccountNumber+4); mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor", (random.nextInt(0x70)) + (random.nextInt(0x70) * 0xff) + (random.nextInt(0x70) * 0xffff) + 0xff000000); mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor); mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false); mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true); try { mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum", HideButtons.NEVER.name())); } catch (Exception e) { mHideMessageViewButtons = HideButtons.NEVER; } mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone", "content://settings/system/notification_sound"); try { mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS; } try { mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderSyncMode = FolderMode.FIRST_CLASS; } try { mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode", FolderMode.FIRST_CLASS.name())); } catch (Exception e) { mFolderPushMode = FolderMode.FIRST_CLASS; } try { mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode", FolderMode.NOT_SECOND_CLASS.name())); } catch (Exception e) { mFolderTargetMode = FolderMode.NOT_SECOND_CLASS; } try { searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders", Searchable.ALL.name())); } catch (Exception e) { searchableFolders = Searchable.ALL; } mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false); identities = loadIdentities(preferences.getPreferences()); }
diff --git a/bii/lexergenerator/src/main/java/regextodfaconverter/Regex.java b/bii/lexergenerator/src/main/java/regextodfaconverter/Regex.java index de06976c..75ad989f 100644 --- a/bii/lexergenerator/src/main/java/regextodfaconverter/Regex.java +++ b/bii/lexergenerator/src/main/java/regextodfaconverter/Regex.java @@ -1,402 +1,410 @@ /* * * Copyright 2012 lexergen. * This file is part of lexergen. * * lexergen 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. * * lexergen 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 lexergen. If not, see <http://www.gnu.org/licenses/>. * * lexergen: * A tool to chunk source code into tokens for further processing in a compiler chain. * * Projectgroup: bi, bii * * Authors: Daniel Rotar * * Module: Softwareprojekt Übersetzerbau 2012 * * Created: Apr. 2012 * Version: 1.0 * */ package regextodfaconverter; import java.util.ArrayList; /** * Stellt grundlegende Funktionen zum Arbeiten mit regulären Ausdrücken bereit. * * @author Daniel Rotar * */ public class Regex { /** * Die Zeichen für Grundoperationen. */ private static char[] BASIC_META_CHARS = { '(', ')', '|', '*' }; /** * Die Zeichen für erweiterten Operationen. */ private static char[] EXTENDED_META_CHARS = { '[', ']', '{', '}', '?', '+', '-', '^', '$', '.' }; /** * Das Escape-Zeichen. */ private static char ESCAPE_META_CHAR = '\\'; // ASCII control characters: character code 0-31 // ASCII printable characters: character code 32-127 // The extended ASCII codes: character code 128-255 /** * Das erste Zeichen aus dem ASCII Zeichensatz, das im Alphabet enthalten * sein soll. */ private static int FIRST_ASCII_CHAR = 33; /** * Das letzte Zeichen aus dem ASCII Zeichensatz, das im Alphabet enthalten * sein soll. */ private static int LAST_ASCII_CHAR = 126; /** * Reduziert den angebenen regulären Ausdruck auf die Grundoperationen und * klammert den Ausdruck korrekt und vollständig. * * @param regex * Der zu reduzierende und zu klammernde reguläre Ausdruck. * @return Ein äquivalenter reduzierter und geklammerte regulärer Ausdruck. * @throws RegexInvalidException * Wenn der angegebene regulärer Ausdruck ungültig ist oder * nicht unterstützt wird. */ public static String reduceRegexAndAddMissingParenthesis(String regex) throws RegexInvalidException { return addMissingParenthesis(reduceRegex(regex)); } /** * Reduziert den angebenen regulären Ausdruck auf die Grundoperationen. * * @param regex * Der zu reduzierende und reguläre Ausdruck. * @return Ein äquivalenter reduzierterregulärer Ausdruck. * @throws RegexInvalidException * Wenn der angegebene regulärer Ausdruck ungültig ist oder * nicht unterstützt wird. */ public static String reduceRegex(String regex) throws RegexInvalidException { String output = regex; output = replaceDots(output); // TODO: Weitere erweiterte Operationen unterstützen... return output; } /** * Klammert den angebenen regulären Ausdruck korrekt und vollständig. Der * eingegebene reguläre Ausdruck darf dabei nur die Grundoperationen * enthalten. * * @param regex * Der zu klammernde reguläre Ausdruck (darf nur aus * Grundoperationen enthalten). * @return Ein äquivalenter geklammerte regulärer Ausdruck. * @throws RegexInvalidException * Wenn der angegebene regulärer Ausdruck ungültig ist oder * nicht unterstützt wird. */ public static String addMissingParenthesis(String regex) throws RegexInvalidException { if (regex.length() == 0) { return ""; } // Vorbereitungen treffen: // Sicherstellen, das der angegebene reguläre Ausdruck nur noch // Grundoperationen enthält. if (!containsOnlyBasicOperations(regex)) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck darf nur die Grundoperationen enthalten!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen beginnt (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(0))) && (!isEscapeMetaCharacter(regex.charAt(0))) && (regex.charAt(0) != '(')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck fängt mit einem ungütligen Zeichen an!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen endet (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(regex.length() - 1))) && (regex.charAt(regex.length() - 1) != '*') && (regex.charAt(regex.length() - 1) != ')')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck endet mit einem ungütligen Zeichen!"); } // Hier beginnt die "richtige" Verarbeitung ArrayList<String> regexTasks = new ArrayList<String>(); // ArrayList befüllen for (int i = 0; i < regex.length(); i++) { char c = regex.charAt(i); if (isBasicMetaCharacter(c)) { if (c == '(') { // Der regex enthält bereits einen geklammerten Ausdruck! // Geklammerten Regex rekursiv auflösen. int toClose = 1; StringBuilder subRegex = new StringBuilder(); while (toClose != 0) { i++; if (i == regex.length()) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } if (regex.charAt(i) == '(') { subRegex.append(regex.charAt(i)); toClose++; } else if (regex.charAt(i) == ')') { toClose--; if (toClose > 0) { subRegex.append(regex.charAt(i)); } + } else if (regex.charAt(i) == '\\') { + if (i+1 == regex.length()) { + throw new RegexInvalidException( + "Der angegebene reguläre Ausdruck ist ungültig geklammert"); + } + subRegex.append(regex.charAt(i)); + i++; + subRegex.append(regex.charAt(i)); } else { subRegex.append(regex.charAt(i)); } } regexTasks.add(addMissingParenthesis(subRegex.toString())); } else if (c == ')') { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } else if (c == '|' || c == '*') { regexTasks.add("" + c); } else { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: f-i1-e"); } } else if (isEscapeMetaCharacter(c)) { regexTasks.add("(" + c + "" + regex.charAt(i + 1) + ")"); i++; } else if (isCharInAlphabet(c)) { regexTasks.add("(" + c + ")"); } else { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck enthält ungültige Zeichen: '" + c + "'"); } } // ArrayList abarbeiten, bis nur noch ein eintrag übrig ist. if (regexTasks.size() == 0) { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: r-0"); } else { // closure for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("*")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "*)"); regexTasks.remove(i); i--; } } // concat for (int i = 0; i < regexTasks.size(); i++) { if (i + 1 < regexTasks.size()) { // '*' kann nicht mehr kommen, da bereits vollständig // abgearbeitet. if ((!regexTasks.get(i).equals("|")) && (!regexTasks.get(i + 1).equals("|"))) { regexTasks.set(i, "(" + regexTasks.get(i) + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); i--; } } } // union for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("|")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "|" + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); regexTasks.remove(i); i = i - 2; } } return regexTasks.get(0); } } /** * Gibt an, ob der angegebene reguläre Ausdruck nur die Grundoperationen * enthält. * * @param regex * @return */ public static boolean containsOnlyBasicOperations(String regex) { for (int i = 0; i < regex.length(); i++) { if (isExtendedMetaCharacter(regex.charAt(i))) { return false; } if (isEscapeMetaCharacter(regex.charAt(i))) { // Nach einem Escape-Char darf nur ein Meta-Zeichen kommen i++; if (regex.length() == i) { return false; } else { if (!isMetaCharacter(regex.charAt(i))) { return false; } } } } return true; } /** * Ersetzt jeden Punkt-Operator (".") durch einen äquivalenten minimalen * * @param regex * Der zu reduzierende reguläre Ausdruck. * @return Der reduzierte reguläre Ausdruck. */ private static String replaceDots(String regex) { StringBuilder sb = new StringBuilder("("); for (int i = FIRST_ASCII_CHAR; i <= LAST_ASCII_CHAR; i++) { char c = (char) i; if (isMetaCharacter(c)) { sb.append("|\\" + c); } else { sb.append("|" + c); } } sb.append(")"); sb.delete(1, 2); // erstes "|" entfernen. String replaceWith = sb.toString(); return regex.replace(".", replaceWith); } /** * Ersetzt jedes vorkommen von "[...]" mit einem entsprechenden reduzierten * regulären Ausdruck: Fall1: [first] wird ersetz durch (f|i|r|s|t). Fall2: * [a-d] wird ersetzt durch (a|b|c|d). Fall3: [a-dA-D] wird ersetzt durch * (a|b|c|d|A|B|C|D). Fall4: [^a] wird ersetzt durch eine (...|...|...|...) * (jedes Zeichen aus dem Alphabet außer dem angegebenen Zeichen oder einem * der reservierten Zeichen. Fall5: [-a-c], [a-c-] wird ersetzt durch * (-|a|b|c) bzw. (a|b|c|-). * * @param regex * @return * @throws RegexInvalidException */ private static String replaceBrackets(String regex) throws RegexInvalidException { // TODO: replaceBrackets implementieren. return regex; } /** * Gibt an ob es sich bei dem angegebenen Zeichen um ein Metazeichen * handelt. * * @param c * Das zu überprüfende Zeichen * @return true, wenn es sich um ein Metazeichen handelt, sonst false. */ protected static boolean isMetaCharacter(char c) { return isBasicMetaCharacter(c) || isExtendedMetaCharacter(c) || isEscapeMetaCharacter(c); } /** * Gibt an ob es sich bei dem angegebenen Zeichen um ein Basis-Metazeichen * handelt. * * @param c * Das zu überprüfende Zeichen * @return true, wenn es sich um ein Basis-Metazeichen handelt, sonst false. */ protected static boolean isBasicMetaCharacter(char c) { for (char rc : BASIC_META_CHARS) { if (rc == c) { return true; } } return false; } /** * Gibt an ob es sich bei dem angegebenen Zeichen um ein erweitertes * Metazeichen handelt. * * @param c * Das zu überprüfende Zeichen * @return true, wenn es sich um ein erweitertes Metazeichen handelt, sonst * false. */ protected static boolean isExtendedMetaCharacter(char c) { for (char rc : EXTENDED_META_CHARS) { if (rc == c) { return true; } } return false; } /** * Gibt an ob es sich bei dem angegebenen Zeichen um ein Escape-Metazeichen * handelt. * * @param c * Das zu überprüfende Zeichen * @return true, wenn es sich um ein Escape-Metazeichen handelt, sonst * false. */ protected static boolean isEscapeMetaCharacter(char c) { if (ESCAPE_META_CHAR == c) { return true; } return false; } /** * Gibt an ob das angegebene Zeichen Teil des Alpabeths ist und kein * Metazeichen ist. * * @param c * Das zu überprüfende Zeichen * @return true, wenn das engegebene Zeichen im Alphabet liegt und kein * Metazeichen ist. */ protected static boolean isCharInAlphabet(char c) { return c >= FIRST_ASCII_CHAR && c <= LAST_ASCII_CHAR && (!isMetaCharacter(c)); } }
true
true
public static String addMissingParenthesis(String regex) throws RegexInvalidException { if (regex.length() == 0) { return ""; } // Vorbereitungen treffen: // Sicherstellen, das der angegebene reguläre Ausdruck nur noch // Grundoperationen enthält. if (!containsOnlyBasicOperations(regex)) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck darf nur die Grundoperationen enthalten!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen beginnt (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(0))) && (!isEscapeMetaCharacter(regex.charAt(0))) && (regex.charAt(0) != '(')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck fängt mit einem ungütligen Zeichen an!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen endet (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(regex.length() - 1))) && (regex.charAt(regex.length() - 1) != '*') && (regex.charAt(regex.length() - 1) != ')')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck endet mit einem ungütligen Zeichen!"); } // Hier beginnt die "richtige" Verarbeitung ArrayList<String> regexTasks = new ArrayList<String>(); // ArrayList befüllen for (int i = 0; i < regex.length(); i++) { char c = regex.charAt(i); if (isBasicMetaCharacter(c)) { if (c == '(') { // Der regex enthält bereits einen geklammerten Ausdruck! // Geklammerten Regex rekursiv auflösen. int toClose = 1; StringBuilder subRegex = new StringBuilder(); while (toClose != 0) { i++; if (i == regex.length()) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } if (regex.charAt(i) == '(') { subRegex.append(regex.charAt(i)); toClose++; } else if (regex.charAt(i) == ')') { toClose--; if (toClose > 0) { subRegex.append(regex.charAt(i)); } } else { subRegex.append(regex.charAt(i)); } } regexTasks.add(addMissingParenthesis(subRegex.toString())); } else if (c == ')') { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } else if (c == '|' || c == '*') { regexTasks.add("" + c); } else { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: f-i1-e"); } } else if (isEscapeMetaCharacter(c)) { regexTasks.add("(" + c + "" + regex.charAt(i + 1) + ")"); i++; } else if (isCharInAlphabet(c)) { regexTasks.add("(" + c + ")"); } else { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck enthält ungültige Zeichen: '" + c + "'"); } } // ArrayList abarbeiten, bis nur noch ein eintrag übrig ist. if (regexTasks.size() == 0) { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: r-0"); } else { // closure for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("*")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "*)"); regexTasks.remove(i); i--; } } // concat for (int i = 0; i < regexTasks.size(); i++) { if (i + 1 < regexTasks.size()) { // '*' kann nicht mehr kommen, da bereits vollständig // abgearbeitet. if ((!regexTasks.get(i).equals("|")) && (!regexTasks.get(i + 1).equals("|"))) { regexTasks.set(i, "(" + regexTasks.get(i) + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); i--; } } } // union for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("|")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "|" + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); regexTasks.remove(i); i = i - 2; } } return regexTasks.get(0); } }
public static String addMissingParenthesis(String regex) throws RegexInvalidException { if (regex.length() == 0) { return ""; } // Vorbereitungen treffen: // Sicherstellen, das der angegebene reguläre Ausdruck nur noch // Grundoperationen enthält. if (!containsOnlyBasicOperations(regex)) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck darf nur die Grundoperationen enthalten!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen beginnt (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(0))) && (!isEscapeMetaCharacter(regex.charAt(0))) && (regex.charAt(0) != '(')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck fängt mit einem ungütligen Zeichen an!"); } // Überprüfen, ob der angegebene reguläre Ausdruck mit einem gültigen // Zeichen endet (um bei weiteren Berechnungen diesen Fall nicht // abfangen zu müssen) if ((!isCharInAlphabet(regex.charAt(regex.length() - 1))) && (regex.charAt(regex.length() - 1) != '*') && (regex.charAt(regex.length() - 1) != ')')) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck endet mit einem ungütligen Zeichen!"); } // Hier beginnt die "richtige" Verarbeitung ArrayList<String> regexTasks = new ArrayList<String>(); // ArrayList befüllen for (int i = 0; i < regex.length(); i++) { char c = regex.charAt(i); if (isBasicMetaCharacter(c)) { if (c == '(') { // Der regex enthält bereits einen geklammerten Ausdruck! // Geklammerten Regex rekursiv auflösen. int toClose = 1; StringBuilder subRegex = new StringBuilder(); while (toClose != 0) { i++; if (i == regex.length()) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } if (regex.charAt(i) == '(') { subRegex.append(regex.charAt(i)); toClose++; } else if (regex.charAt(i) == ')') { toClose--; if (toClose > 0) { subRegex.append(regex.charAt(i)); } } else if (regex.charAt(i) == '\\') { if (i+1 == regex.length()) { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } subRegex.append(regex.charAt(i)); i++; subRegex.append(regex.charAt(i)); } else { subRegex.append(regex.charAt(i)); } } regexTasks.add(addMissingParenthesis(subRegex.toString())); } else if (c == ')') { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck ist ungültig geklammert"); } else if (c == '|' || c == '*') { regexTasks.add("" + c); } else { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: f-i1-e"); } } else if (isEscapeMetaCharacter(c)) { regexTasks.add("(" + c + "" + regex.charAt(i + 1) + ")"); i++; } else if (isCharInAlphabet(c)) { regexTasks.add("(" + c + ")"); } else { throw new RegexInvalidException( "Der angegebene reguläre Ausdruck enthält ungültige Zeichen: '" + c + "'"); } } // ArrayList abarbeiten, bis nur noch ein eintrag übrig ist. if (regexTasks.size() == 0) { throw new RegexInvalidException( "Unbekannter Ausnahmefehler. Fehlercode: r-0"); } else { // closure for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("*")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "*)"); regexTasks.remove(i); i--; } } // concat for (int i = 0; i < regexTasks.size(); i++) { if (i + 1 < regexTasks.size()) { // '*' kann nicht mehr kommen, da bereits vollständig // abgearbeitet. if ((!regexTasks.get(i).equals("|")) && (!regexTasks.get(i + 1).equals("|"))) { regexTasks.set(i, "(" + regexTasks.get(i) + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); i--; } } } // union for (int i = 0; i < regexTasks.size(); i++) { if (regexTasks.get(i).equals("|")) { regexTasks.set(i - 1, "(" + regexTasks.get(i - 1) + "|" + regexTasks.get(i + 1) + ")"); regexTasks.remove(i + 1); regexTasks.remove(i); i = i - 2; } } return regexTasks.get(0); } }
diff --git a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java index 945d2f2c2..98091d956 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java +++ b/gdx/src/com/badlogic/gdx/graphics/g2d/tiled/TiledLoader.java @@ -1,450 +1,453 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g2d.tiled; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Stack; import java.util.StringTokenizer; import java.util.zip.DataFormatException; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.XmlReader; /** Loads a Tiled Map from a tmx file * @author David Fraska */ public class TiledLoader { /** Loads a Tiled Map from a tmx file * @param tmxFile the map's tmx file */ public static TiledMap createMap (FileHandle tmxFile) { final TiledMap map; map = new TiledMap(); map.tmxFile = tmxFile; try { new XmlReader() { Stack<String> currBranch = new Stack<String>(); boolean awaitingData = false; TiledLayer currLayer; int currLayerWidth = 0, currLayerHeight = 0; TileSet currTileSet; TiledObjectGroup currObjectGroup; TiledObject currObject; int currTile; class Property { String parentType, name, value; } Property currProperty; String encoding, dataString, compression; byte[] data; int dataCounter = 0, row, col; @Override protected void open (String name) { currBranch.push(name); if ("layer".equals(name)) { currLayer = new TiledLayer(); return; } if ("tileset".equals(name)) { currTileSet = new TileSet(); return; } if ("data".equals(name)) { dataString = ""; // clear the string for new data awaitingData = true; return; } if ("objectgroup".equals(name)) { currObjectGroup = new TiledObjectGroup(); return; } if ("object".equals(name)) { currObject = new TiledObject(); return; } if ("property".equals(name)) { currProperty = new Property(); currProperty.parentType = currBranch.get(currBranch.size() - 3); return; } } @Override protected void attribute (String name, String value) { String element = currBranch.peek(); if ("layer".equals(element)) { if ("width".equals(name)) { currLayerWidth = Integer.parseInt(value); } else if ("height".equals(name)) { currLayerHeight = Integer.parseInt(value); } if (currLayerWidth != 0 && currLayerHeight != 0) { currLayer.tiles = new int[currLayerHeight][currLayerWidth]; } + if ("name".equals(name)) { + currLayer.name = value; + } return; } if ("tileset".equals(element)) { if ("firstgid".equals(name)) { currTileSet.firstgid = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { currTileSet.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { currTileSet.tileHeight = Integer.parseInt(value); return; } if ("name".equals(name)) { currTileSet.name = value; return; } if ("spacing".equals(name)) { currTileSet.spacing = Integer.parseInt(value); return; } if ("margin".equals(name)) { currTileSet.margin = Integer.parseInt(value); return; } return; } if ("image".equals(element)) { if ("source".equals(name)) { currTileSet.imageName = value; return; } return; } if ("data".equals(element)) { if ("encoding".equals(name)) { encoding = value; return; } if ("compression".equals(name)) { compression = value; return; } return; } if ("objectgroup".equals(element)) { if ("name".equals(name)) { currObjectGroup.name = value; return; } if ("height".equals(name)) { currObjectGroup.height = Integer.parseInt(value); return; } if ("width".equals(name)) { currObjectGroup.width = Integer.parseInt(value); return; } return; } if ("object".equals(element)) { if ("name".equals(name)) { currObject.name = value; return; } if ("type".equals(name)) { currObject.type = value; return; } if ("x".equals(name)) { currObject.x = Integer.parseInt(value); return; } if ("y".equals(name)) { currObject.y = Integer.parseInt(value); return; } if ("width".equals(name)) { currObject.width = Integer.parseInt(value); return; } if ("height".equals(name)) { currObject.height = Integer.parseInt(value); return; } if ("gid".equals(name)) { currObject.gid = Integer.parseInt(value); return; } return; } if ("map".equals(element)) { if ("orientation".equals(name)) { map.orientation = value; return; } if ("width".equals(name)) { map.width = Integer.parseInt(value); return; } if ("height".equals(name)) { map.height = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { map.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { map.tileHeight = Integer.parseInt(value); return; } return; } if ("tile".equals(element)) { if (awaitingData) { // Actually getting tile data if ("gid".equals(name)) { col = dataCounter % currLayerWidth; row = dataCounter / currLayerWidth; if (row < currLayerHeight) { currLayer.tiles[row][col] = Integer.parseInt(value); } else { Gdx.app.log("TiledLoader", "Warning: extra XML gid values ignored! Your map is likely corrupt!"); } dataCounter++; } } else { // Not getting tile data, must be a tile Id (for properties) if ("id".equals(name)) { currTile = Integer.parseInt(value); } } return; } if ("property".equals(element)) { if ("name".equals(name)) { currProperty.name = value; return; } if ("value".equals(name)) { currProperty.value = value; return; } return; } } @Override protected void text (String text) { if (awaitingData) { dataString = dataString.concat(text); } } @Override protected void close () { String element = currBranch.pop(); if ("layer".equals(element)) { map.layers.add(currLayer); currLayer = null; return; } if ("tileset".equals(element)) { map.tileSets.add(currTileSet); currTileSet = null; return; } if ("object".equals(element)) { currObjectGroup.objects.add(currObject); currObject = null; return; } if ("objectgroup".equals(element)) { map.objectGroups.add(currObjectGroup); currObjectGroup = null; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; return; } if ("data".equals(element)) { // decode and uncompress the data if ("base64".equals(encoding)) { if (dataString == null | "".equals(dataString.trim())) return; data = Base64Coder.decode(dataString.trim()); if ("gzip".equals(compression)) { unGZip(); } else if ("zlib".equals(compression)) { unZlib(); } else if (compression == null) { arrangeData(); } } else if ("csv".equals(encoding) && compression == null) { fromCSV(); } else if (encoding == null && compression == null) { // startElement() handles most of this dataCounter = 0;// reset counter in case another layer comes through } else { throw new GdxRuntimeException("Unsupported encoding and/or compression format"); } awaitingData = false; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; } } private void putProperty (Property property) { if ("tile".equals(property.parentType)) { map.setTileProperty(currTile + currTileSet.firstgid, property.name, property.value); return; } if ("map".equals(property.parentType)) { map.properties.put(property.name, property.value); return; } if ("layer".equals(property.parentType)) { currLayer.properties.put(property.name, property.value); return; } if ("objectgroup".equals(property.parentType)) { currObjectGroup.properties.put(property.name, property.value); return; } if ("object".equals(property.parentType)) { currObject.properties.put(property.name, property.value); return; } } private void fromCSV () { StringTokenizer st = new StringTokenizer(dataString.trim(), ","); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = Integer.parseInt(st.nextToken().trim()); } } } private void arrangeData () { int byteCounter = 0; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = unsignedByteToInt(data[byteCounter++]) | unsignedByteToInt(data[byteCounter++]) << 8 | unsignedByteToInt(data[byteCounter++]) << 16 | unsignedByteToInt(data[byteCounter++]) << 24; } } } private void unZlib () { Inflater zlib = new Inflater(); byte[] readTemp = new byte[4]; zlib.setInput(data, 0, data.length); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { zlib.inflate(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (DataFormatException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } private void unGZip () { GZIPInputStream GZIS = null; try { GZIS = new GZIPInputStream(new ByteArrayInputStream(data), data.length); } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } // Read the GZIS data into an array, 4 bytes = 1 GID byte[] readTemp = new byte[4]; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { GZIS.read(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } }.parse(tmxFile); } catch (IOException e) { throw new GdxRuntimeException("Error Parsing TMX file", e); } return map; } static int unsignedByteToInt (byte b) { return (int)b & 0xFF; } }
true
true
public static TiledMap createMap (FileHandle tmxFile) { final TiledMap map; map = new TiledMap(); map.tmxFile = tmxFile; try { new XmlReader() { Stack<String> currBranch = new Stack<String>(); boolean awaitingData = false; TiledLayer currLayer; int currLayerWidth = 0, currLayerHeight = 0; TileSet currTileSet; TiledObjectGroup currObjectGroup; TiledObject currObject; int currTile; class Property { String parentType, name, value; } Property currProperty; String encoding, dataString, compression; byte[] data; int dataCounter = 0, row, col; @Override protected void open (String name) { currBranch.push(name); if ("layer".equals(name)) { currLayer = new TiledLayer(); return; } if ("tileset".equals(name)) { currTileSet = new TileSet(); return; } if ("data".equals(name)) { dataString = ""; // clear the string for new data awaitingData = true; return; } if ("objectgroup".equals(name)) { currObjectGroup = new TiledObjectGroup(); return; } if ("object".equals(name)) { currObject = new TiledObject(); return; } if ("property".equals(name)) { currProperty = new Property(); currProperty.parentType = currBranch.get(currBranch.size() - 3); return; } } @Override protected void attribute (String name, String value) { String element = currBranch.peek(); if ("layer".equals(element)) { if ("width".equals(name)) { currLayerWidth = Integer.parseInt(value); } else if ("height".equals(name)) { currLayerHeight = Integer.parseInt(value); } if (currLayerWidth != 0 && currLayerHeight != 0) { currLayer.tiles = new int[currLayerHeight][currLayerWidth]; } return; } if ("tileset".equals(element)) { if ("firstgid".equals(name)) { currTileSet.firstgid = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { currTileSet.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { currTileSet.tileHeight = Integer.parseInt(value); return; } if ("name".equals(name)) { currTileSet.name = value; return; } if ("spacing".equals(name)) { currTileSet.spacing = Integer.parseInt(value); return; } if ("margin".equals(name)) { currTileSet.margin = Integer.parseInt(value); return; } return; } if ("image".equals(element)) { if ("source".equals(name)) { currTileSet.imageName = value; return; } return; } if ("data".equals(element)) { if ("encoding".equals(name)) { encoding = value; return; } if ("compression".equals(name)) { compression = value; return; } return; } if ("objectgroup".equals(element)) { if ("name".equals(name)) { currObjectGroup.name = value; return; } if ("height".equals(name)) { currObjectGroup.height = Integer.parseInt(value); return; } if ("width".equals(name)) { currObjectGroup.width = Integer.parseInt(value); return; } return; } if ("object".equals(element)) { if ("name".equals(name)) { currObject.name = value; return; } if ("type".equals(name)) { currObject.type = value; return; } if ("x".equals(name)) { currObject.x = Integer.parseInt(value); return; } if ("y".equals(name)) { currObject.y = Integer.parseInt(value); return; } if ("width".equals(name)) { currObject.width = Integer.parseInt(value); return; } if ("height".equals(name)) { currObject.height = Integer.parseInt(value); return; } if ("gid".equals(name)) { currObject.gid = Integer.parseInt(value); return; } return; } if ("map".equals(element)) { if ("orientation".equals(name)) { map.orientation = value; return; } if ("width".equals(name)) { map.width = Integer.parseInt(value); return; } if ("height".equals(name)) { map.height = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { map.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { map.tileHeight = Integer.parseInt(value); return; } return; } if ("tile".equals(element)) { if (awaitingData) { // Actually getting tile data if ("gid".equals(name)) { col = dataCounter % currLayerWidth; row = dataCounter / currLayerWidth; if (row < currLayerHeight) { currLayer.tiles[row][col] = Integer.parseInt(value); } else { Gdx.app.log("TiledLoader", "Warning: extra XML gid values ignored! Your map is likely corrupt!"); } dataCounter++; } } else { // Not getting tile data, must be a tile Id (for properties) if ("id".equals(name)) { currTile = Integer.parseInt(value); } } return; } if ("property".equals(element)) { if ("name".equals(name)) { currProperty.name = value; return; } if ("value".equals(name)) { currProperty.value = value; return; } return; } } @Override protected void text (String text) { if (awaitingData) { dataString = dataString.concat(text); } } @Override protected void close () { String element = currBranch.pop(); if ("layer".equals(element)) { map.layers.add(currLayer); currLayer = null; return; } if ("tileset".equals(element)) { map.tileSets.add(currTileSet); currTileSet = null; return; } if ("object".equals(element)) { currObjectGroup.objects.add(currObject); currObject = null; return; } if ("objectgroup".equals(element)) { map.objectGroups.add(currObjectGroup); currObjectGroup = null; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; return; } if ("data".equals(element)) { // decode and uncompress the data if ("base64".equals(encoding)) { if (dataString == null | "".equals(dataString.trim())) return; data = Base64Coder.decode(dataString.trim()); if ("gzip".equals(compression)) { unGZip(); } else if ("zlib".equals(compression)) { unZlib(); } else if (compression == null) { arrangeData(); } } else if ("csv".equals(encoding) && compression == null) { fromCSV(); } else if (encoding == null && compression == null) { // startElement() handles most of this dataCounter = 0;// reset counter in case another layer comes through } else { throw new GdxRuntimeException("Unsupported encoding and/or compression format"); } awaitingData = false; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; } } private void putProperty (Property property) { if ("tile".equals(property.parentType)) { map.setTileProperty(currTile + currTileSet.firstgid, property.name, property.value); return; } if ("map".equals(property.parentType)) { map.properties.put(property.name, property.value); return; } if ("layer".equals(property.parentType)) { currLayer.properties.put(property.name, property.value); return; } if ("objectgroup".equals(property.parentType)) { currObjectGroup.properties.put(property.name, property.value); return; } if ("object".equals(property.parentType)) { currObject.properties.put(property.name, property.value); return; } } private void fromCSV () { StringTokenizer st = new StringTokenizer(dataString.trim(), ","); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = Integer.parseInt(st.nextToken().trim()); } } } private void arrangeData () { int byteCounter = 0; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = unsignedByteToInt(data[byteCounter++]) | unsignedByteToInt(data[byteCounter++]) << 8 | unsignedByteToInt(data[byteCounter++]) << 16 | unsignedByteToInt(data[byteCounter++]) << 24; } } } private void unZlib () { Inflater zlib = new Inflater(); byte[] readTemp = new byte[4]; zlib.setInput(data, 0, data.length); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { zlib.inflate(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (DataFormatException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } private void unGZip () { GZIPInputStream GZIS = null; try { GZIS = new GZIPInputStream(new ByteArrayInputStream(data), data.length); } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } // Read the GZIS data into an array, 4 bytes = 1 GID byte[] readTemp = new byte[4]; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { GZIS.read(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } }.parse(tmxFile); } catch (IOException e) { throw new GdxRuntimeException("Error Parsing TMX file", e); } return map; }
public static TiledMap createMap (FileHandle tmxFile) { final TiledMap map; map = new TiledMap(); map.tmxFile = tmxFile; try { new XmlReader() { Stack<String> currBranch = new Stack<String>(); boolean awaitingData = false; TiledLayer currLayer; int currLayerWidth = 0, currLayerHeight = 0; TileSet currTileSet; TiledObjectGroup currObjectGroup; TiledObject currObject; int currTile; class Property { String parentType, name, value; } Property currProperty; String encoding, dataString, compression; byte[] data; int dataCounter = 0, row, col; @Override protected void open (String name) { currBranch.push(name); if ("layer".equals(name)) { currLayer = new TiledLayer(); return; } if ("tileset".equals(name)) { currTileSet = new TileSet(); return; } if ("data".equals(name)) { dataString = ""; // clear the string for new data awaitingData = true; return; } if ("objectgroup".equals(name)) { currObjectGroup = new TiledObjectGroup(); return; } if ("object".equals(name)) { currObject = new TiledObject(); return; } if ("property".equals(name)) { currProperty = new Property(); currProperty.parentType = currBranch.get(currBranch.size() - 3); return; } } @Override protected void attribute (String name, String value) { String element = currBranch.peek(); if ("layer".equals(element)) { if ("width".equals(name)) { currLayerWidth = Integer.parseInt(value); } else if ("height".equals(name)) { currLayerHeight = Integer.parseInt(value); } if (currLayerWidth != 0 && currLayerHeight != 0) { currLayer.tiles = new int[currLayerHeight][currLayerWidth]; } if ("name".equals(name)) { currLayer.name = value; } return; } if ("tileset".equals(element)) { if ("firstgid".equals(name)) { currTileSet.firstgid = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { currTileSet.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { currTileSet.tileHeight = Integer.parseInt(value); return; } if ("name".equals(name)) { currTileSet.name = value; return; } if ("spacing".equals(name)) { currTileSet.spacing = Integer.parseInt(value); return; } if ("margin".equals(name)) { currTileSet.margin = Integer.parseInt(value); return; } return; } if ("image".equals(element)) { if ("source".equals(name)) { currTileSet.imageName = value; return; } return; } if ("data".equals(element)) { if ("encoding".equals(name)) { encoding = value; return; } if ("compression".equals(name)) { compression = value; return; } return; } if ("objectgroup".equals(element)) { if ("name".equals(name)) { currObjectGroup.name = value; return; } if ("height".equals(name)) { currObjectGroup.height = Integer.parseInt(value); return; } if ("width".equals(name)) { currObjectGroup.width = Integer.parseInt(value); return; } return; } if ("object".equals(element)) { if ("name".equals(name)) { currObject.name = value; return; } if ("type".equals(name)) { currObject.type = value; return; } if ("x".equals(name)) { currObject.x = Integer.parseInt(value); return; } if ("y".equals(name)) { currObject.y = Integer.parseInt(value); return; } if ("width".equals(name)) { currObject.width = Integer.parseInt(value); return; } if ("height".equals(name)) { currObject.height = Integer.parseInt(value); return; } if ("gid".equals(name)) { currObject.gid = Integer.parseInt(value); return; } return; } if ("map".equals(element)) { if ("orientation".equals(name)) { map.orientation = value; return; } if ("width".equals(name)) { map.width = Integer.parseInt(value); return; } if ("height".equals(name)) { map.height = Integer.parseInt(value); return; } if ("tilewidth".equals(name)) { map.tileWidth = Integer.parseInt(value); return; } if ("tileheight".equals(name)) { map.tileHeight = Integer.parseInt(value); return; } return; } if ("tile".equals(element)) { if (awaitingData) { // Actually getting tile data if ("gid".equals(name)) { col = dataCounter % currLayerWidth; row = dataCounter / currLayerWidth; if (row < currLayerHeight) { currLayer.tiles[row][col] = Integer.parseInt(value); } else { Gdx.app.log("TiledLoader", "Warning: extra XML gid values ignored! Your map is likely corrupt!"); } dataCounter++; } } else { // Not getting tile data, must be a tile Id (for properties) if ("id".equals(name)) { currTile = Integer.parseInt(value); } } return; } if ("property".equals(element)) { if ("name".equals(name)) { currProperty.name = value; return; } if ("value".equals(name)) { currProperty.value = value; return; } return; } } @Override protected void text (String text) { if (awaitingData) { dataString = dataString.concat(text); } } @Override protected void close () { String element = currBranch.pop(); if ("layer".equals(element)) { map.layers.add(currLayer); currLayer = null; return; } if ("tileset".equals(element)) { map.tileSets.add(currTileSet); currTileSet = null; return; } if ("object".equals(element)) { currObjectGroup.objects.add(currObject); currObject = null; return; } if ("objectgroup".equals(element)) { map.objectGroups.add(currObjectGroup); currObjectGroup = null; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; return; } if ("data".equals(element)) { // decode and uncompress the data if ("base64".equals(encoding)) { if (dataString == null | "".equals(dataString.trim())) return; data = Base64Coder.decode(dataString.trim()); if ("gzip".equals(compression)) { unGZip(); } else if ("zlib".equals(compression)) { unZlib(); } else if (compression == null) { arrangeData(); } } else if ("csv".equals(encoding) && compression == null) { fromCSV(); } else if (encoding == null && compression == null) { // startElement() handles most of this dataCounter = 0;// reset counter in case another layer comes through } else { throw new GdxRuntimeException("Unsupported encoding and/or compression format"); } awaitingData = false; return; } if ("property".equals(element)) { putProperty(currProperty); currProperty = null; } } private void putProperty (Property property) { if ("tile".equals(property.parentType)) { map.setTileProperty(currTile + currTileSet.firstgid, property.name, property.value); return; } if ("map".equals(property.parentType)) { map.properties.put(property.name, property.value); return; } if ("layer".equals(property.parentType)) { currLayer.properties.put(property.name, property.value); return; } if ("objectgroup".equals(property.parentType)) { currObjectGroup.properties.put(property.name, property.value); return; } if ("object".equals(property.parentType)) { currObject.properties.put(property.name, property.value); return; } } private void fromCSV () { StringTokenizer st = new StringTokenizer(dataString.trim(), ","); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = Integer.parseInt(st.nextToken().trim()); } } } private void arrangeData () { int byteCounter = 0; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { currLayer.tiles[row][col] = unsignedByteToInt(data[byteCounter++]) | unsignedByteToInt(data[byteCounter++]) << 8 | unsignedByteToInt(data[byteCounter++]) << 16 | unsignedByteToInt(data[byteCounter++]) << 24; } } } private void unZlib () { Inflater zlib = new Inflater(); byte[] readTemp = new byte[4]; zlib.setInput(data, 0, data.length); for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { zlib.inflate(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (DataFormatException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } private void unGZip () { GZIPInputStream GZIS = null; try { GZIS = new GZIPInputStream(new ByteArrayInputStream(data), data.length); } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } // Read the GZIS data into an array, 4 bytes = 1 GID byte[] readTemp = new byte[4]; for (int row = 0; row < currLayerHeight; row++) { for (int col = 0; col < currLayerWidth; col++) { try { GZIS.read(readTemp, 0, 4); currLayer.tiles[row][col] = unsignedByteToInt(readTemp[0]) | unsignedByteToInt(readTemp[1]) << 8 | unsignedByteToInt(readTemp[2]) << 16 | unsignedByteToInt(readTemp[3]) << 24; } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data.", e); } } } } }.parse(tmxFile); } catch (IOException e) { throw new GdxRuntimeException("Error Parsing TMX file", e); } return map; }
diff --git a/jsf-ri/src/com/sun/faces/context/flash/ELFlash.java b/jsf-ri/src/com/sun/faces/context/flash/ELFlash.java index 10f3bf8fd..30d424153 100644 --- a/jsf-ri/src/com/sun/faces/context/flash/ELFlash.java +++ b/jsf-ri/src/com/sun/faces/context/flash/ELFlash.java @@ -1,889 +1,889 @@ /* * $Id: ELFlash.java,v 1.6 2005/12/16 21:32:36 edburns Exp $ */ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * https://javaserverfaces.dev.java.net/CDDL.html or * legal/CDDLv1.0.txt. * See the License for the specific language governing * permission and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * [Name of File] [ver.__] [Date] * * Copyright 2005 Sun Microsystems Inc. All Rights Reserved */ package com.sun.faces.context.flash; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.faces.application.FacesMessage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.Flash; import javax.faces.event.PhaseId; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; /** * * <p>A Map implementation that provides semantics identical to the <a * target="_" * href="http://api.rubyonrails.com/classes/ActionController/Flash.html"> * "flash" concept in Ruby on Rails</a>.</p> * * <p>Usage</p> * * <p>See {@link FlashELResolver} for usage instructions.</p> * * <p>Methods on this Map have different effects depending on the * current lifecycle phase when the method is invoked. During all * lifecycle phases earlier than invoke-application, methods on this Map * are directed to an internal Map that is cleared at the end of the * current lifecycle run. For invoke-application and beyond, all * operations are directed to an internal Map that will be accessible * for all lifecycle phases on the <b>next</b> request on this session, * up to, but not including, invoke-application.</p> * * @author edburns */ public class ELFlash extends Flash { private Map<String,Map<String, Object>> innerMap = null; /** Creates a new instance of ELFlash */ private ELFlash() { // We only need exactly two entries. innerMap = new ConcurrentHashMap<String,Map<String, Object>>(2); } /** * <p>Returns the flash <code>Map</code> for this session. This is * a convenience method that calls * <code>FacesContext.getCurrentInstance()</code> and then calls the * overloaded <code>getFlash()</code> that takes a * <code>FacesContext</code> with it.</p> * * @return The flash <code>Map</code> for this session. */ public static Map<String,Object> getFlash() { FacesContext context = FacesContext.getCurrentInstance(); return getFlash(context.getExternalContext(), true); } /** * * @param extContext the <code>ExternalContext</code> for this request. * * @param create <code>true</code> to create a new instance for this request if * necessary; <code>false</code> to return <code>null</code> if there's no * instance in the current <code>session</code>. * * @return The flash <code>Map</code> for this session. */ public static Flash getFlash(ExternalContext extContext, boolean create) { Map<String, Object> appMap = extContext.getApplicationMap(); ELFlash flash = (ELFlash) appMap.get(Constants.FLASH_ATTRIBUTE_NAME); if (null == flash && create) { synchronized (extContext.getContext()) { if (null == (flash = (ELFlash) appMap.get(Constants.FLASH_ATTRIBUTE_NAME))) { flash = new ELFlash(); appMap.put(Constants.FLASH_ATTRIBUTE_NAME, flash); } } } return flash; } public static ELFlash getELFlash() { return (ELFlash) getFlash(); } public boolean isKeepMessages() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); Map<String, Object> requestMap = extContext.getRequestMap(); Map<String, Object> cookieMap = extContext.getRequestCookieMap(); Object response = extContext.getResponse(); Boolean value = (Boolean) requestMap.get(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE); if (null == value) { if (response instanceof HttpServletResponse) { Cookie redirectCookie = (Cookie) cookieMap.get(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE); if (null != redirectCookie) { value = Boolean.TRUE; HttpServletResponse servletResponse = (HttpServletResponse) response; redirectCookie.setMaxAge(0); servletResponse.addCookie(redirectCookie); } else { value = Boolean.FALSE; } requestMap.put(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE, value); } } return (value != null && value); } public void setKeepMessages(boolean newValue) { FacesContext context = FacesContext.getCurrentInstance(); Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Boolean newBoolean = newValue ? Boolean.TRUE : Boolean.FALSE; Boolean oldBoolean = (!requestMap.containsKey(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE)) ? null : (Boolean) requestMap.get(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE); // If the value changed from null to true or from false to true, // set a cookie if ((null == oldBoolean && newValue) || (Boolean.FALSE == oldBoolean && newValue)) { ExternalContext extContext = context.getExternalContext(); HttpServletResponse servletResponse; //PortletRequest portletRequest = null; Object response = extContext.getResponse(); if (response instanceof HttpServletResponse) { servletResponse = (HttpServletResponse) response; Cookie cookie = new Cookie(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE, "t"); cookie.setMaxAge(-1); servletResponse.addCookie(cookie); } else { /***** * portletRequest = (PortletRequest) request; * // You can't add a cookie in portlet. * // http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *********/ } } requestMap.put(Constants.FLASH_KEEP_ALL_REQUEST_SCOPED_DATA_ATTRIBUTE, newBoolean); } public boolean isRedirect() { boolean result; FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); Map<String, Object> requestMap = extContext.getRequestMap(); Map<String, Object> cookieMap = extContext.getRequestCookieMap(); Object response = extContext.getResponse(); Boolean value = (Boolean) requestMap.get(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME); if (value == null) { if (response instanceof HttpServletResponse) { Cookie redirectCookie = (Cookie) cookieMap.get(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME); if (null != redirectCookie) { value = Boolean.TRUE; HttpServletResponse servletResponse = (HttpServletResponse) response; redirectCookie.setMaxAge(0); servletResponse.addCookie(redirectCookie); } else { value = Boolean.FALSE; } requestMap.put(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME, value); } } result = (value != null && value); return result; } public void setRedirect(boolean newValue) { FacesContext context = FacesContext.getCurrentInstance(); Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Boolean newBoolean = newValue ? Boolean.TRUE : Boolean.FALSE; Boolean oldBoolean = (!requestMap.containsKey(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME)) ? null : (Boolean) requestMap.get(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME); // If the value changed from null to true or from false to true, // set a cookie if ((null == oldBoolean && newValue) || (Boolean.FALSE == oldBoolean && newValue)) { ExternalContext extContext = context.getExternalContext(); HttpServletResponse servletResponse; //PortletRequest portletRequest = null; Object response = extContext.getResponse(); if (response instanceof HttpServletResponse) { servletResponse = (HttpServletResponse) response; Cookie cookie = new Cookie(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME, "t"); cookie.setMaxAge(-1); servletResponse.addCookie(cookie); } else { /***** * portletRequest = (PortletRequest) request; * // You can't add a cookie in portlet. * // http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *********/ } } requestMap.put(Constants.REDIRECT_AFTER_POST_ATTRIBUTE_NAME, newBoolean); } /** * * <p>The following datum are moved from request scope into the flash * to be made available on a subsequent call to * {@link #restoreAllMessages}.</p> * * <ul> * * <li><p>All request scoped attributes</p></li> * * <li><p>All <code>FacesMessage</code> instances queued on the * <code>FacesContext</code></p></li> * * </ul> * @param context Context for request */ void saveAllMessages(FacesContext context) { ExternalContext extContext = context.getExternalContext(); Map<String, Object> requestMap = extContext.getRequestMap(); Boolean thisRequestIsGetAfterRedirectAfterPost; if (null != (thisRequestIsGetAfterRedirectAfterPost = (Boolean) requestMap.get(Constants.THIS_REQUEST_IS_GET_AFTER_REDIRECT_AFTER_POST_ATTRIBUTE_NAME)) && thisRequestIsGetAfterRedirectAfterPost) { return; } Iterator<String> messageClientIds = context.getClientIdsWithMessages(); List<FacesMessage> facesMessages; Map<String, List<FacesMessage>> allFacesMessages = null; Iterator<FacesMessage> messageIter; String curMessageId; // Save all the FacesMessages into a Map, which we store in the flash. // Step 1, go through the FacesMessage instances for each clientId // in the messageClientIds list. while (messageClientIds.hasNext()) { curMessageId = messageClientIds.next(); // Get the messages for this clientId messageIter = context.getMessages(curMessageId); facesMessages = new ArrayList<FacesMessage>(); while (messageIter.hasNext()) { facesMessages.add(messageIter.next()); } // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(curMessageId, facesMessages); } facesMessages = null; // Step 2, go through the FacesMessages that do not have a client // id associated with them. messageIter = context.getMessages(null); while (messageIter.hasNext()) { // Make sure to overwrite the previous facesMessages list facesMessages = new ArrayList<FacesMessage>(); facesMessages.add(messageIter.next()); } if (null != facesMessages) { // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(null, facesMessages); } boolean isRedirect = this.isRedirect(); if (null != allFacesMessages) { if (isRedirect) { - this.getMapForCookie(context).put(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, + this.getThisRequestMap(context).put(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } else { this.putNext(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } } } void restoreAllMessages(FacesContext context) { Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Map<String, List<FacesMessage>> allFacesMessages; List<FacesMessage> facesMessages; Map<String,Object> map; if (null != (map = getMapForCookie(context))) { //noinspection unchecked if (null != (allFacesMessages = (Map<String, List<FacesMessage>>) map.get(Constants.FACES_MESSAGES_ATTRIBUTE_NAME))) { for (Map.Entry<String, List<FacesMessage>> cur : allFacesMessages.entrySet()) { if (null != (facesMessages = allFacesMessages.get(cur.getKey()))) { for (FacesMessage curMessage : facesMessages) { context.addMessage(cur.getKey(), curMessage); } } } requestMap.put(Constants.THIS_REQUEST_IS_GET_AFTER_REDIRECT_AFTER_POST_ATTRIBUTE_NAME, Boolean.TRUE); } map.remove(Constants.FACES_MESSAGES_ATTRIBUTE_NAME); } } /** * <p>Returns the correct Map considering the current lifecycle phase.</p> * * <p>If the current lifecycle phase is * render-response, call {@link #getNextRequestMap} and return the boolResult. * Otherwise, call {@link #getThisRequestMap} and return the boolResult.</p> * * @return the "correct" map for the current lifecycle phase. */ protected Map<String,Object> getPhaseMap() { Map<String,Object> result; FacesContext context = FacesContext.getCurrentInstance(); PhaseId currentPhase = context.getCurrentPhaseId(); // If we're in render-response phase..., // or this is an initial request (not a postback), // or this is the get from the redirect after post... if (currentPhase == PhaseId.RENDER_RESPONSE || (!context.isPostback()) || this.isRedirect()) { // make operations go to the next request Map. result = getNextRequestMap(context); } else { // Otherwise, make operations go this request Map. result = getThisRequestMap(context); } return result; } /** * @param context for the request * @return the Map flash for the next postback. This Map is used by the * flash for all operations during the render-response lifecycle phase. * During all other lifecycle phases, operations go instead to the Map * returned by {@link #getThisRequestMap}. * */ private Map<String,Object> getNextRequestMap(FacesContext context) { return getMapForSequenceId(context, Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME); } /** * @param context for the request * @return the Map flash for this postback. This Map is used by the flash * for all operations during all lifecycle phases except render-response. * During render-response, any flash operations go instead to the Map returned * by {@link #getNextRequestMap}. */ private Map<String,Object> getThisRequestMap(FacesContext context) { return getMapForSequenceId(context, Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME); } /** * <p>This is a private helper method for {@link #getNextRequestMap} and * {@link #getThisRequestMap}. * * @param context Context of the request * @param attrName Name of the attribute to get the sequence for. * * @return the sequence Map given the sequence identifier. */ private Map<String,Object> getMapForSequenceId(FacesContext context, String attrName) { Object sequenceId = context.getExternalContext(). getRequestMap().get(attrName); if (null == sequenceId) { return null; } Map<String,Object> result = innerMap.get(sequenceId.toString()); if (null == result) { result = new HashMap<String,Object>(); innerMap.put(sequenceId.toString(), result); } return result; } private Map<String,Object> getMapForCookie(FacesContext context) { String cookieName = getCookieValue(context.getExternalContext()); Map<String,Object> result = null; if (null != cookieName) { result = innerMap.get(cookieName); } return result; } /** * <p>Called by the {@link #doPostPhaseActions(javax.faces.context.FacesContext)} for the * render-response phase to clear out the flash for the appropriate * sequence. * @param sequence Sequence to clear */ void expireEntriesForSequence(String sequence) { Map<String, Object> toExpire = innerMap.get(sequence); if (null != toExpire) { toExpire.clear(); innerMap.remove(sequence); } } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public Object remove(Object key) { return getPhaseMap().remove(key); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public boolean containsKey(Object key) { return getPhaseMap().containsKey(key); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public boolean containsValue(Object value) { return getPhaseMap().containsValue(value); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public boolean equals(Object obj) { return obj instanceof Map && getPhaseMap().equals(obj); } /** * <p>This operation takes special care to handle the "keep" operation on * the flash. Consider the expression #{flash.keep.foo}. A set operation * on this expression will simply end up calling the {@link #put} method. * During a get operation on this expression, we first look in the Map for * the currently posting back request. If no value is found, we look in * the request scope for the current request. If a value is found there, we * place it in the map for the next request. We return the value.</p> * * <p>In the case of a non "keep" operation, this method simply returns * the value from the Map for the currently posting back request.</p> */ public Object get(Object key) { FacesContext context = FacesContext.getCurrentInstance(); Map<String,Object> map = this.isRedirect() ? getMapForCookie(context) : getThisRequestMap(context); Object requestValue; Object result = null; if (null != key) { if (key.equals("keepMessages")) { result = this.isKeepMessages(); } if (key.equals("redirect")) { result = this.isRedirect(); } } if (null == result) { // For gets, look in the postbackSequenceMap. if (null != map) { result = map.get(key); } // If not found in the postbackSequenceMap and we're doing a "keep" promotion... if (null == result && FlashELResolver.isDoKeep()) { // See if we have a value in the request scope. if (null != (requestValue = FacesContext.getCurrentInstance().getExternalContext(). getRequestMap().get(key))) { // get the value from the request scope result = requestValue; } } // If this resolution is for a keep promotion... if (FlashELResolver.isDoKeep()) { FlashELResolver.setDoKeep(false); // Do the promotion. getNextRequestMap(context).put((String) key, result); } } return result; } @Override public void keep(String key) { FlashELResolver.setDoKeep(true); this.get(key); } @Override public void putNow(String key, Object value) { FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put(key, value); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public void putAll(Map<? extends String, ?> t) { getPhaseMap().putAll(t); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public Object put(String key, Object value) { Boolean boolResult = null; Object result; if (null != key) { if (key.equals("keepMessages")) { if (null != value && value.toString().equals("true")) { this.setKeepMessages(boolResult = true); } else { this.setKeepMessages(boolResult = false); } } if (key.equals("redirect")) { if (null != value && value.toString().equals("true")) { this.setRedirect(boolResult = true); } else { this.setRedirect(boolResult = false); } } } if (null == boolResult) { result = getPhaseMap().put(key, value); } else { result = boolResult; } return result; } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> * @param key key to put * @param value value to put * @return object put */ public Object putNext(String key, Object value) { FacesContext context = FacesContext.getCurrentInstance(); return getNextRequestMap(context).put(key, value); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public java.util.Collection<Object> values() { return getPhaseMap().values(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public String toString() { return getPhaseMap().toString(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public int size() { return getPhaseMap().size(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public void clear() { getPhaseMap().clear(); } /** * @throws CloneNotSupportedException */ @SuppressWarnings({"CloneDoesntCallSuperClone"}) protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public java.util.Set<java.util.Map.Entry<String, Object>> entrySet() { return getPhaseMap().entrySet(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public int hashCode() { return getPhaseMap().hashCode(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public boolean isEmpty() { return getPhaseMap().isEmpty(); } /** * <p>Get the correct map as descibed above and perform this operation on * it.</p> */ public java.util.Set<String> keySet() { return getPhaseMap().keySet(); } /** * <p>Perform actions that need to happen on the * <code>afterPhase</code> event.</p> * * <p>For after restore-view, if this is a postback, we extract the * sequenceId from the request and store it in the request * scope.</p> * * <p>For after render-response, we clear out the flash for the * postback, while leaving the current one intact. </p> */ @Override public void doPostPhaseActions(FacesContext context) { ExternalContext extContext = context.getExternalContext(); ELFlash elFlash = ELFlash.getELFlash(); if (PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId())) { expireEntries(context); } // If this requset is ending normally... if (PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId())) { // and the user requested we save all request scoped data... if (elFlash != null && elFlash.isKeepMessages()) { // save it all. elFlash.saveAllMessages(context); } } // Otherwise, if this request is ending early... else if ((context.getResponseComplete() || context.getRenderResponse()) && elFlash.isRedirect()) { // and the user requested we save all request scoped data... if (elFlash.isKeepMessages()) { // save it all. addCookie(extContext, elFlash); elFlash.saveAllMessages(context); } } } /** * <p>Perform actions that need to happen on the * <code>beforePhase</code> event.</p> * * <p>For all phases, store the current phaseId in request scope.</p> * * <p>For before restore-view, create a sequenceId for this request * and store it in request scope.</p> * * <p>For before render-response, store the sequenceId for this * request in the response.</p> * */ public void doPrePhaseActions(FacesContext context) { ExternalContext extContext = context.getExternalContext(); Object response = extContext.getResponse(); Map<String, Object> requestMap = extContext.getRequestMap(); String thisRequestSequenceString; String postbackSequenceString = null; ELFlash elFlash = (ELFlash) ELFlash.getFlash(extContext, true); // If we're on before-restore-view... if (PhaseId.RESTORE_VIEW.equals(context.getCurrentPhaseId())) { thisRequestSequenceString = Long.toString(sequenceNumber.incrementAndGet()); // Put the sequence number for the request/response pair // that is starting with *this particular request* in the request scope // so the ELFlash can access it. requestMap.put(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString); // Make sure to restore all request scoped data if (null != elFlash && elFlash.isKeepMessages()) { elFlash.restoreAllMessages(context); } if (context.isPostback()) { // to a servlet JSF app... if (response instanceof HttpServletResponse) { // extract the sequence number from the cookie or portletSession // for the request/response pair for which this request is a postback. postbackSequenceString = getCookieValue(extContext); } else { /****** * PortletRequest portletRequest = null; * portletRequest = (PortletRequest) request; * // You can't retrieve a cookie in portlet. * // http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie * postbackSequenceString = (String) * portletRequest.getPortletSession(). * getAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, * PortletSession.PORTLET_SCOPE); *******/ } if (null != postbackSequenceString) { // Store the sequenceNumber in the request so the // after-render-response event can flush the flash // of entries from that sequence requestMap.put(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, postbackSequenceString); } } } if (PhaseId.RENDER_RESPONSE.equals(context.getCurrentPhaseId())) { // Set the REQUEST_ID cookie to be the sequence number addCookie(extContext, elFlash); } } // ------------------------------------- Methods from old PhaseListener Impl private static final AtomicInteger sequenceNumber = new AtomicInteger(0); static String getCookieValue(ExternalContext extContext) { String result = null; Cookie cookie = (Cookie) extContext.getRequestCookieMap(). get(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME); if (null != cookie) { result = cookie.getValue(); } return result; } private void addCookie(ExternalContext extContext, Flash flash) { // Do not update the cookie if redirect after post if (flash.isRedirect()) { return; } String thisRequestSequenceString; HttpServletResponse servletResponse; //PortletRequest portletRequest; Object thisRequestSequenceStringObj, response = extContext.getResponse(); thisRequestSequenceStringObj = extContext.getRequestMap(). get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME); if (null == thisRequestSequenceStringObj) { return; } thisRequestSequenceString = thisRequestSequenceStringObj.toString(); if (response instanceof HttpServletResponse) { servletResponse = (HttpServletResponse) response; Cookie cookie = new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString); cookie.setMaxAge(-1); servletResponse.addCookie(cookie); } else { /***** * portletRequest = (PortletRequest) request; * // You can't add a cookie in portlet. * // http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *********/ } } private void expireEntries(FacesContext context) { ExternalContext extContext = context.getExternalContext(); String postbackSequenceString; // Clear out the flash for the postback. if (null != (postbackSequenceString = (String) extContext.getRequestMap(). get(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME))) { ELFlash flash = (ELFlash)ELFlash.getFlash(extContext, false); if (null != flash) { flash.expireEntriesForSequence(postbackSequenceString); } } } }
true
true
void saveAllMessages(FacesContext context) { ExternalContext extContext = context.getExternalContext(); Map<String, Object> requestMap = extContext.getRequestMap(); Boolean thisRequestIsGetAfterRedirectAfterPost; if (null != (thisRequestIsGetAfterRedirectAfterPost = (Boolean) requestMap.get(Constants.THIS_REQUEST_IS_GET_AFTER_REDIRECT_AFTER_POST_ATTRIBUTE_NAME)) && thisRequestIsGetAfterRedirectAfterPost) { return; } Iterator<String> messageClientIds = context.getClientIdsWithMessages(); List<FacesMessage> facesMessages; Map<String, List<FacesMessage>> allFacesMessages = null; Iterator<FacesMessage> messageIter; String curMessageId; // Save all the FacesMessages into a Map, which we store in the flash. // Step 1, go through the FacesMessage instances for each clientId // in the messageClientIds list. while (messageClientIds.hasNext()) { curMessageId = messageClientIds.next(); // Get the messages for this clientId messageIter = context.getMessages(curMessageId); facesMessages = new ArrayList<FacesMessage>(); while (messageIter.hasNext()) { facesMessages.add(messageIter.next()); } // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(curMessageId, facesMessages); } facesMessages = null; // Step 2, go through the FacesMessages that do not have a client // id associated with them. messageIter = context.getMessages(null); while (messageIter.hasNext()) { // Make sure to overwrite the previous facesMessages list facesMessages = new ArrayList<FacesMessage>(); facesMessages.add(messageIter.next()); } if (null != facesMessages) { // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(null, facesMessages); } boolean isRedirect = this.isRedirect(); if (null != allFacesMessages) { if (isRedirect) { this.getMapForCookie(context).put(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } else { this.putNext(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } } }
void saveAllMessages(FacesContext context) { ExternalContext extContext = context.getExternalContext(); Map<String, Object> requestMap = extContext.getRequestMap(); Boolean thisRequestIsGetAfterRedirectAfterPost; if (null != (thisRequestIsGetAfterRedirectAfterPost = (Boolean) requestMap.get(Constants.THIS_REQUEST_IS_GET_AFTER_REDIRECT_AFTER_POST_ATTRIBUTE_NAME)) && thisRequestIsGetAfterRedirectAfterPost) { return; } Iterator<String> messageClientIds = context.getClientIdsWithMessages(); List<FacesMessage> facesMessages; Map<String, List<FacesMessage>> allFacesMessages = null; Iterator<FacesMessage> messageIter; String curMessageId; // Save all the FacesMessages into a Map, which we store in the flash. // Step 1, go through the FacesMessage instances for each clientId // in the messageClientIds list. while (messageClientIds.hasNext()) { curMessageId = messageClientIds.next(); // Get the messages for this clientId messageIter = context.getMessages(curMessageId); facesMessages = new ArrayList<FacesMessage>(); while (messageIter.hasNext()) { facesMessages.add(messageIter.next()); } // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(curMessageId, facesMessages); } facesMessages = null; // Step 2, go through the FacesMessages that do not have a client // id associated with them. messageIter = context.getMessages(null); while (messageIter.hasNext()) { // Make sure to overwrite the previous facesMessages list facesMessages = new ArrayList<FacesMessage>(); facesMessages.add(messageIter.next()); } if (null != facesMessages) { // Add the list to the map if (null == allFacesMessages) { allFacesMessages = new HashMap<String, List<FacesMessage>>(); } allFacesMessages.put(null, facesMessages); } boolean isRedirect = this.isRedirect(); if (null != allFacesMessages) { if (isRedirect) { this.getThisRequestMap(context).put(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } else { this.putNext(Constants.FACES_MESSAGES_ATTRIBUTE_NAME, allFacesMessages); } } }
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/movie/MoviePosterImageAdapter.java b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/movie/MoviePosterImageAdapter.java index 2d7335fa..08e694bd 100644 --- a/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/movie/MoviePosterImageAdapter.java +++ b/serenity-app/src/main/java/us/nineworlds/serenity/ui/browser/movie/MoviePosterImageAdapter.java @@ -1,277 +1,283 @@ /** * The MIT License (MIT) * Copyright (c) 2013 David Carver * 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 us.nineworlds.serenity.ui.browser.movie; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.android.youtube.player.YouTubeApiServiceUtil; import com.google.android.youtube.player.YouTubeInitializationResult; import com.jess.ui.TwoWayAbsListView; import com.jess.ui.TwoWayGridView; import us.nineworlds.plex.rest.PlexappFactory; import us.nineworlds.plex.rest.model.impl.MediaContainer; import us.nineworlds.serenity.core.model.DBMetaData; import us.nineworlds.serenity.core.model.VideoContentInfo; import us.nineworlds.serenity.core.model.impl.MovieMediaContainer; import us.nineworlds.serenity.core.services.YouTubeTrailerSearchIntentService; import us.nineworlds.serenity.core.util.DBMetaDataSource; import us.nineworlds.serenity.core.util.SimpleXmlRequest; import us.nineworlds.serenity.ui.activity.SerenityMultiViewVideoActivity; import us.nineworlds.serenity.ui.adapters.AbstractPosterImageGalleryAdapter; import us.nineworlds.serenity.ui.listeners.GridSubtitleHandler; import us.nineworlds.serenity.ui.listeners.TrailerGridHandler; import us.nineworlds.serenity.ui.listeners.TrailerHandler; import us.nineworlds.serenity.ui.util.ImageUtils; import us.nineworlds.serenity.widgets.SerenityGallery; import us.nineworlds.serenity.R; import us.nineworlds.serenity.SerenityApplication; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Messenger; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; /** * * @author dcarver * */ public class MoviePosterImageAdapter extends AbstractPosterImageGalleryAdapter { protected static AbstractPosterImageGalleryAdapter notifyAdapter; protected static ProgressDialog pd; private static SerenityMultiViewVideoActivity movieContext; private DBMetaDataSource datasource; public MoviePosterImageAdapter(Context c, String key, String category) { super(c, key, category); movieContext = (SerenityMultiViewVideoActivity) c; notifyAdapter = this; } @Override public View getView(int position, View convertView, ViewGroup parent) { + if (position > posterList.size()) { + position = posterList.size() - 1; + } + if (position < 0) { + position = 0; + } View galleryCellView = null; if (convertView != null) { galleryCellView = convertView; galleryCellView.findViewById(R.id.posterInprogressIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.posterWatchedIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.infoGraphicMeta).setVisibility( View.GONE); } else { galleryCellView = context.getLayoutInflater().inflate( R.layout.poster_indicator_view, null); } VideoContentInfo pi = posterList.get(position); gridViewMetaData(galleryCellView, pi); ImageView mpiv = (ImageView) galleryCellView .findViewById(R.id.posterImageView); mpiv.setBackgroundResource(R.drawable.gallery_item_background); mpiv.setScaleType(ImageView.ScaleType.FIT_XY); int width = 0; int height = 0; width = ImageUtils.getDPI(130, context); height = ImageUtils.getDPI(200, context); mpiv.setMaxHeight(height); mpiv.setMaxWidth(width); if (!movieContext.isGridViewActive()) { mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new SerenityGallery.LayoutParams( width, height)); } else { width = ImageUtils.getDPI(120, context); height = ImageUtils.getDPI(180, context); mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new TwoWayAbsListView.LayoutParams( width, height)); } shrinkPosterAnimation(mpiv, movieContext.isGridViewActive()); SerenityApplication.displayImage(pi.getImageURL(), mpiv); setWatchedStatus(galleryCellView, pi); return galleryCellView; } /** * @param galleryCellView * @param pi */ protected void gridViewMetaData(View galleryCellView, VideoContentInfo pi) { if (movieContext.isGridViewActive()) { checkDataBaseForTrailer(pi); if (pi.hasTrailer() == false) { if (YouTubeInitializationResult.SUCCESS .equals(YouTubeApiServiceUtil .isYouTubeApiServiceAvailable(context))) { fetchTrailer(pi, galleryCellView); } } else { View v = galleryCellView.findViewById(R.id.infoGraphicMeta); v.setVisibility(View.VISIBLE); v.findViewById(R.id.trailerIndicator).setVisibility( View.VISIBLE); } if (pi.getAvailableSubtitles() != null) { View v = galleryCellView.findViewById(R.id.infoGraphicMeta); v.setVisibility(View.VISIBLE); v.findViewById(R.id.subtitleIndicator).setVisibility( View.VISIBLE); } else { fetchSubtitle(pi, galleryCellView); } } } /** * @param pi */ protected void checkDataBaseForTrailer(VideoContentInfo pi) { datasource = new DBMetaDataSource(context); datasource.open(); DBMetaData metaData = datasource.findMetaDataByPlexId(pi.id()); if (metaData != null) { pi.setTrailer(true); pi.setTrailerId(metaData.getYouTubeID()); } datasource.close(); } public void fetchTrailer(VideoContentInfo mpi, View view) { TrailerHandler trailerHandler = new TrailerGridHandler(mpi, context, view); Messenger messenger = new Messenger(trailerHandler); Intent intent = new Intent(context, YouTubeTrailerSearchIntentService.class); intent.putExtra("videoTitle", mpi.getTitle()); intent.putExtra("year", mpi.getYear()); intent.putExtra("MESSENGER", messenger); context.startService(intent); } public void fetchSubtitle(VideoContentInfo mpi, View view) { PlexappFactory factory = SerenityApplication.getPlexFactory(); String url = factory.getMovieMetadataURL("/library/metadata/" + mpi.id()); SimpleXmlRequest<MediaContainer> xmlRequest = new SimpleXmlRequest<MediaContainer>( Request.Method.GET, url, MediaContainer.class, new GridSubtitleHandler(mpi, context, view), new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(xmlRequest); } @Override protected void fetchDataFromService() { pd = ProgressDialog.show(context, "", context.getString(R.string.retrieving_movies)); final PlexappFactory factory = SerenityApplication.getPlexFactory(); String url = factory.getSectionsURL(key, category); SimpleXmlRequest<MediaContainer> request = new SimpleXmlRequest<MediaContainer>( Request.Method.GET, url, MediaContainer.class, new MoviePosterResponseListener(), new MoviePosterResponseErrorListener()); queue.add(request); } private class MoviePosterResponseErrorListener implements Response.ErrorListener { @Override public void onErrorResponse(VolleyError error) { if (pd != null) { pd.dismiss(); } } } /** * @author dcarver * */ private class MoviePosterResponseListener implements Response.Listener<MediaContainer> { @Override public void onResponse(MediaContainer response) { try { MediaContainer mc = response; populatePosters(mc); } catch (Exception e) { Log.e(getClass().getName(), "Error populating posters.", e); } if (pd.isShowing()) { pd.dismiss(); } } /** * @param mc */ protected void populatePosters(MediaContainer mc) { MovieMediaContainer movies = new MovieMediaContainer(mc); posterList = movies.createVideos(); notifyAdapter.notifyDataSetChanged(); if (!movieContext.isGridViewActive()) { SerenityGallery posterGallery = (SerenityGallery) movieContext .findViewById(R.id.moviePosterGallery); posterGallery.requestFocusFromTouch(); } else { TwoWayGridView gridView = (TwoWayGridView) movieContext .findViewById(R.id.movieGridView); gridView.requestFocusFromTouch(); } } } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { View galleryCellView = null; if (convertView != null) { galleryCellView = convertView; galleryCellView.findViewById(R.id.posterInprogressIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.posterWatchedIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.infoGraphicMeta).setVisibility( View.GONE); } else { galleryCellView = context.getLayoutInflater().inflate( R.layout.poster_indicator_view, null); } VideoContentInfo pi = posterList.get(position); gridViewMetaData(galleryCellView, pi); ImageView mpiv = (ImageView) galleryCellView .findViewById(R.id.posterImageView); mpiv.setBackgroundResource(R.drawable.gallery_item_background); mpiv.setScaleType(ImageView.ScaleType.FIT_XY); int width = 0; int height = 0; width = ImageUtils.getDPI(130, context); height = ImageUtils.getDPI(200, context); mpiv.setMaxHeight(height); mpiv.setMaxWidth(width); if (!movieContext.isGridViewActive()) { mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new SerenityGallery.LayoutParams( width, height)); } else { width = ImageUtils.getDPI(120, context); height = ImageUtils.getDPI(180, context); mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new TwoWayAbsListView.LayoutParams( width, height)); } shrinkPosterAnimation(mpiv, movieContext.isGridViewActive()); SerenityApplication.displayImage(pi.getImageURL(), mpiv); setWatchedStatus(galleryCellView, pi); return galleryCellView; }
public View getView(int position, View convertView, ViewGroup parent) { if (position > posterList.size()) { position = posterList.size() - 1; } if (position < 0) { position = 0; } View galleryCellView = null; if (convertView != null) { galleryCellView = convertView; galleryCellView.findViewById(R.id.posterInprogressIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.posterWatchedIndicator) .setVisibility(View.INVISIBLE); galleryCellView.findViewById(R.id.infoGraphicMeta).setVisibility( View.GONE); } else { galleryCellView = context.getLayoutInflater().inflate( R.layout.poster_indicator_view, null); } VideoContentInfo pi = posterList.get(position); gridViewMetaData(galleryCellView, pi); ImageView mpiv = (ImageView) galleryCellView .findViewById(R.id.posterImageView); mpiv.setBackgroundResource(R.drawable.gallery_item_background); mpiv.setScaleType(ImageView.ScaleType.FIT_XY); int width = 0; int height = 0; width = ImageUtils.getDPI(130, context); height = ImageUtils.getDPI(200, context); mpiv.setMaxHeight(height); mpiv.setMaxWidth(width); if (!movieContext.isGridViewActive()) { mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new SerenityGallery.LayoutParams( width, height)); } else { width = ImageUtils.getDPI(120, context); height = ImageUtils.getDPI(180, context); mpiv.setLayoutParams(new RelativeLayout.LayoutParams(width, height)); galleryCellView.setLayoutParams(new TwoWayAbsListView.LayoutParams( width, height)); } shrinkPosterAnimation(mpiv, movieContext.isGridViewActive()); SerenityApplication.displayImage(pi.getImageURL(), mpiv); setWatchedStatus(galleryCellView, pi); return galleryCellView; }
diff --git a/src/com/gtalkstatus/android/GTalkStatusUpdater.java b/src/com/gtalkstatus/android/GTalkStatusUpdater.java index feb5283..d47f5cc 100644 --- a/src/com/gtalkstatus/android/GTalkStatusUpdater.java +++ b/src/com/gtalkstatus/android/GTalkStatusUpdater.java @@ -1,221 +1,221 @@ /*************************************************************************** * Copyright 2010 Scott Ferguson * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ package com.gtalkstatus.android; import android.content.Intent; import android.content.ServiceConnection; import android.content.Context; import android.widget.Toast; import android.app.Service; import android.os.IBinder; import android.content.ComponentName; import android.os.IBinder; import android.os.Bundle; import android.util.Log; import android.app.PendingIntent; import java.lang.CharSequence; import java.lang.IllegalStateException; import java.lang.NullPointerException; import org.jivesoftware.smack.XMPPException; import com.android.music.IMediaPlaybackService; public class GTalkStatusUpdater extends Service { public static final String LOG_NAME = "GTalkStatusUpdater"; @Override public void onCreate() { super.onCreate(); } public int onStartCommand(Intent aIntent, int aFlags, int aStartId) { onStart(aIntent, aStartId); return 2; } @Override public void onStart(Intent aIntent, int aStartId) { Log.d(LOG_NAME, aIntent.getAction()); if (aIntent.getAction().equals("com.android.music.playbackcomplete")) { // The song has ended, stop the service stopSelf(); } else if (aIntent.getAction().equals("com.android.music.playstatechanged") || aIntent.getAction().equals("com.android.music.metachanged") || aIntent.getAction().equals("com.android.music.queuechanged")) { bindService(new Intent().setClassName("com.android.music", "com.android.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); } else if ((aIntent.getAction().equals("com.htc.music.playstatechanged") && aIntent.getIntExtra("id", -1) != -1) || aIntent.getAction().equals("com.htc.music.metachanged")) { /** EXPERIMENTAL HTC MUSIC PLAYER SUPPORT **/ bindService(new Intent().setClassName("com.htc.music", "com.htc.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { com.htc.music.IMediaPlaybackService s = com.htc.music.IMediaPlaybackService.Stub.asInterface(aService); IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); - } else if (aIntent.getAction().equals("com.gtalkstatus.android.updaterintent")) { + } else if (aIntent.getAction().equals("com.gtalkstatus.android.statusupdate")) { Log.d(LOG_NAME, "Found Generic Intent"); Bundle extras = aIntent.getExtras(); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = extras.getString("track"); String currentArtist = extras.getString("artist"); Log.d(LOG_NAME, extras.getString("state")); if (extras.getString("state").equals("is_playing")) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "XMPPException"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_NAME, e.toString()); throw new RuntimeException(e); } } } public IBinder onBind(Intent aIntent) { return null; } }
true
true
public void onStart(Intent aIntent, int aStartId) { Log.d(LOG_NAME, aIntent.getAction()); if (aIntent.getAction().equals("com.android.music.playbackcomplete")) { // The song has ended, stop the service stopSelf(); } else if (aIntent.getAction().equals("com.android.music.playstatechanged") || aIntent.getAction().equals("com.android.music.metachanged") || aIntent.getAction().equals("com.android.music.queuechanged")) { bindService(new Intent().setClassName("com.android.music", "com.android.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); } else if ((aIntent.getAction().equals("com.htc.music.playstatechanged") && aIntent.getIntExtra("id", -1) != -1) || aIntent.getAction().equals("com.htc.music.metachanged")) { /** EXPERIMENTAL HTC MUSIC PLAYER SUPPORT **/ bindService(new Intent().setClassName("com.htc.music", "com.htc.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { com.htc.music.IMediaPlaybackService s = com.htc.music.IMediaPlaybackService.Stub.asInterface(aService); IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); } else if (aIntent.getAction().equals("com.gtalkstatus.android.updaterintent")) { Log.d(LOG_NAME, "Found Generic Intent"); Bundle extras = aIntent.getExtras(); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = extras.getString("track"); String currentArtist = extras.getString("artist"); Log.d(LOG_NAME, extras.getString("state")); if (extras.getString("state").equals("is_playing")) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "XMPPException"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_NAME, e.toString()); throw new RuntimeException(e); } } }
public void onStart(Intent aIntent, int aStartId) { Log.d(LOG_NAME, aIntent.getAction()); if (aIntent.getAction().equals("com.android.music.playbackcomplete")) { // The song has ended, stop the service stopSelf(); } else if (aIntent.getAction().equals("com.android.music.playstatechanged") || aIntent.getAction().equals("com.android.music.metachanged") || aIntent.getAction().equals("com.android.music.queuechanged")) { bindService(new Intent().setClassName("com.android.music", "com.android.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); } else if ((aIntent.getAction().equals("com.htc.music.playstatechanged") && aIntent.getIntExtra("id", -1) != -1) || aIntent.getAction().equals("com.htc.music.metachanged")) { /** EXPERIMENTAL HTC MUSIC PLAYER SUPPORT **/ bindService(new Intent().setClassName("com.htc.music", "com.htc.music.MediaPlaybackService"), new ServiceConnection() { public void onServiceConnected(ComponentName aName, IBinder aService) { com.htc.music.IMediaPlaybackService s = com.htc.music.IMediaPlaybackService.Stub.asInterface(aService); IMediaPlaybackService service = IMediaPlaybackService.Stub.asInterface(aService); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = service.getTrackName(); String currentArtist = service.getArtistName(); if (service.isPlaying()) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "No connection to XMPP server!"); GTalkStatusNotifier.notify(GTalkStatusApplication.getInstance(), GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } unbindService(this); } public void onServiceDisconnected(ComponentName aName) { GTalkStatusApplication.getInstance().getConnector().setStatus("", 0); } }, 0); } else if (aIntent.getAction().equals("com.gtalkstatus.android.statusupdate")) { Log.d(LOG_NAME, "Found Generic Intent"); Bundle extras = aIntent.getExtras(); try { // We disconnect from XMPP if we don't need to keep the connection alive. // Reconnect if necessary. if (! GTalkStatusApplication.getInstance().getConnector().isConnected()) { GTalkStatusApplication.getInstance().updateConnection(); } String currentTrack = extras.getString("track"); String currentArtist = extras.getString("artist"); Log.d(LOG_NAME, extras.getString("state")); if (extras.getString("state").equals("is_playing")) { String statusMessage = "\u266B " + currentArtist + " - " + currentTrack; GTalkStatusApplication.getInstance().getConnector().setStatus(statusMessage); } else { GTalkStatusApplication.getInstance().getConnector().disconnect(); stopSelf(); } } catch (IllegalStateException e) { GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (NullPointerException e) { Log.w(LOG_NAME, "Service was never connected!"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (XMPPException e) { Log.w(LOG_NAME, "XMPPException"); GTalkStatusNotifier.notify(this, GTalkStatusNotifier.ERROR); stopSelf(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_NAME, e.toString()); throw new RuntimeException(e); } } }
diff --git a/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java b/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java index a10d803bb..933d59eba 100644 --- a/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java +++ b/tests/org.jboss.tools.hibernate.ui.bot.test/src/org/jboss/tools/hb/ui/bot/test/console/CreateConsoleConfigurationTest.java @@ -1,130 +1,130 @@ package org.jboss.tools.hb.ui.bot.test.console; import static org.eclipse.swtbot.swt.finder.waits.Conditions.shellCloses; import java.util.List; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.hb.ui.bot.common.ConfigurationFile; import org.jboss.tools.hb.ui.bot.common.Tree; import org.jboss.tools.hb.ui.bot.test.HibernateBaseTest; import org.jboss.tools.ui.bot.ext.config.Annotations.DB; import org.jboss.tools.ui.bot.ext.config.Annotations.Require; import org.jboss.tools.ui.bot.ext.config.TestConfigurator; import org.jboss.tools.ui.bot.ext.gen.ActionItem; import org.jboss.tools.ui.bot.ext.helper.DatabaseHelper; import org.jboss.tools.ui.bot.ext.types.EntityType; import org.jboss.tools.ui.bot.ext.types.IDELabel; import org.junit.Test; /** * Create Hibernate Console UI Bot Test * @author jpeterka * */ @Require(db = @DB, clearProjects = true) public class CreateConsoleConfigurationTest extends HibernateBaseTest { final String prjName = "configurationtest"; @Test public void createConsoleConfigurationTest() { emptyErrorLog(); importTestProject("/resources/prj/" + prjName); createConfigurationFile(); createHibernateConsole(); expandDatabaseInConsole(); checkErrorLog(); } private void createConfigurationFile() { ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false); } private void createHibernateConsole() { open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL); eclipse.createNew(EntityType.HIBERNATE_CONSOLE); // Hibernate Console Dialog has no title SWTBotShell shell = bot.waitForShell(""); createMainTab(shell); createOptionTab(shell); createClasspathTab(shell); createMappingsTab(shell); createCommonTab(shell); bot.button(IDELabel.Button.FINISH).click(); bot.waitUntil(shellCloses(shell)); util.waitForNonIgnoredJobs(); } private void createMainTab(SWTBotShell shell) { bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate(); bot.textWithLabel("Name:").setText(prjName); bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml"); } private void createOptionTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate(); String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType); bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect); } private void createClasspathTab(SWTBotShell shell) { - shell.activate(); + shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate(); } private void createMappingsTab(SWTBotShell shell) { - shell.activate(); + shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate(); } private void createCommonTab(SWTBotShell shell) { - shell.activate(); + shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate(); } private void expandDatabaseInConsole() { SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot(); SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database"); db.expand(); // expand PUBLIC node or whatever SWTBotTreeItem pub = db.getItems()[0]; final int limit = 10; // 10s final int sleep = 1000; int counter = 0; while(counter < limit) { if (pub.widget.isDisposed()) { pub = db.getItems()[0]; bot.sleep(sleep); } if (pub.getText().equals("<Reading schema error: Getting database metadata >")) { fail("Can't load data, DB not accessible"); } if (pub.getText().equals("Pending...") && counter < limit) { bot.sleep(sleep); counter++; log.info("Waiting for database loading..."); } else { log.info("DB loaded"); break; } } List<String> tables = Tree.getSubNodes(viewBot, pub); assertTrue("Table must contain tables", tables.size()> 0); for (String s : tables) { log.info("Table:" + s); } } }
false
true
private void createConfigurationFile() { ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false); } private void createHibernateConsole() { open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL); eclipse.createNew(EntityType.HIBERNATE_CONSOLE); // Hibernate Console Dialog has no title SWTBotShell shell = bot.waitForShell(""); createMainTab(shell); createOptionTab(shell); createClasspathTab(shell); createMappingsTab(shell); createCommonTab(shell); bot.button(IDELabel.Button.FINISH).click(); bot.waitUntil(shellCloses(shell)); util.waitForNonIgnoredJobs(); } private void createMainTab(SWTBotShell shell) { bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate(); bot.textWithLabel("Name:").setText(prjName); bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml"); } private void createOptionTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate(); String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType); bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect); } private void createClasspathTab(SWTBotShell shell) { shell.activate(); bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate(); } private void createMappingsTab(SWTBotShell shell) { shell.activate(); bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate(); } private void createCommonTab(SWTBotShell shell) { shell.activate(); bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate(); } private void expandDatabaseInConsole() { SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot(); SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database"); db.expand(); // expand PUBLIC node or whatever SWTBotTreeItem pub = db.getItems()[0]; final int limit = 10; // 10s final int sleep = 1000; int counter = 0; while(counter < limit) { if (pub.widget.isDisposed()) { pub = db.getItems()[0]; bot.sleep(sleep); } if (pub.getText().equals("<Reading schema error: Getting database metadata >")) { fail("Can't load data, DB not accessible"); } if (pub.getText().equals("Pending...") && counter < limit) { bot.sleep(sleep); counter++; log.info("Waiting for database loading..."); } else { log.info("DB loaded"); break; } } List<String> tables = Tree.getSubNodes(viewBot, pub); assertTrue("Table must contain tables", tables.size()> 0); for (String s : tables) { log.info("Table:" + s); } } }
private void createConfigurationFile() { ConfigurationFile.create(new String[]{prjName,"src"},"hibernate.cfg.xml",false); } private void createHibernateConsole() { open.viewOpen(ActionItem.View.GeneralProjectExplorer.LABEL); eclipse.createNew(EntityType.HIBERNATE_CONSOLE); // Hibernate Console Dialog has no title SWTBotShell shell = bot.waitForShell(""); createMainTab(shell); createOptionTab(shell); createClasspathTab(shell); createMappingsTab(shell); createCommonTab(shell); bot.button(IDELabel.Button.FINISH).click(); bot.waitUntil(shellCloses(shell)); util.waitForNonIgnoredJobs(); } private void createMainTab(SWTBotShell shell) { bot.cTabItem(IDELabel.HBConsoleWizard.MAIN_TAB).activate(); bot.textWithLabel("Name:").setText(prjName); bot.textWithLabelInGroup("","Configuration file:").setText(prjName + "/src/hibernate.cfg.xml"); } private void createOptionTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.OPTIONS_TAB).activate(); String dialect = DatabaseHelper.getDialect(TestConfigurator.currentConfig.getDB().dbType); bot.comboBoxWithLabelInGroup("", IDELabel.HBConsoleWizard.DATABASE_DIALECT).setSelection(dialect); } private void createClasspathTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.CLASSPATH_TAB).activate(); } private void createMappingsTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.MAPPINGS_TAB).activate(); } private void createCommonTab(SWTBotShell shell) { shell.setFocus(); bot.cTabItem(IDELabel.HBConsoleWizard.COMMON_TAB).activate(); } private void expandDatabaseInConsole() { SWTBot viewBot = open.viewOpen(ActionItem.View.HibernateHibernateConfigurations.LABEL).bot(); SWTBotTreeItem db = Tree.select(viewBot, prjName,"Database"); db.expand(); // expand PUBLIC node or whatever SWTBotTreeItem pub = db.getItems()[0]; final int limit = 10; // 10s final int sleep = 1000; int counter = 0; while(counter < limit) { if (pub.widget.isDisposed()) { pub = db.getItems()[0]; bot.sleep(sleep); } if (pub.getText().equals("<Reading schema error: Getting database metadata >")) { fail("Can't load data, DB not accessible"); } if (pub.getText().equals("Pending...") && counter < limit) { bot.sleep(sleep); counter++; log.info("Waiting for database loading..."); } else { log.info("DB loaded"); break; } } List<String> tables = Tree.getSubNodes(viewBot, pub); assertTrue("Table must contain tables", tables.size()> 0); for (String s : tables) { log.info("Table:" + s); } } }
diff --git a/contact/src/com/chethan/contact/PeopleFragment.java b/contact/src/com/chethan/contact/PeopleFragment.java index 6db6ce2..1df7045 100644 --- a/contact/src/com/chethan/contact/PeopleFragment.java +++ b/contact/src/com/chethan/contact/PeopleFragment.java @@ -1,155 +1,155 @@ package com.chethan.contact; import java.util.ArrayList; import com.chethan.services.ContactService; import com.chethan.utils.Utils; import android.R.integer; import android.graphics.AvoidXfermode.Mode; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnDragListener; import android.view.View.OnGenericMotionListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.AbsListView; import android.widget.AbsoluteLayout; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; public class PeopleFragment extends Fragment { public static ContactService contactService; private ArrayList<String> contactNameList = new ArrayList<String>(); private int contactListPosition = 0; private TextView contact_2; private TextView contact_1; private TextView contact; private TextView contact1; private TextView contact2; private TextView alphabetTextView; public static final PeopleFragment newInstance(ContactService service) { PeopleFragment f = new PeopleFragment(); contactService=service; return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.people_all, container, false); final View singleContact = (View)view.findViewById(R.id.single_contact); android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.getWidthForContact(getActivity()), android.widget.FrameLayout.LayoutParams.WRAP_CONTENT); singleContact.setLayoutParams(params); final TextView textView = (TextView)view.findViewById(R.id.alphabets); android.widget.LinearLayout.LayoutParams alphabets_params = new LinearLayout.LayoutParams(Utils.getWidthForAlphabets(getActivity()), android.widget.FrameLayout.LayoutParams.MATCH_PARENT); textView.setLayoutParams(alphabets_params); contact_2 = (TextView)view.findViewById(R.id.SingleContactName_2); contact_1 = (TextView)view.findViewById(R.id.SingleContactName_1); contact = (TextView)view.findViewById(R.id.SingleContactName); contact1 = (TextView)view.findViewById(R.id.SingleContactName1); contact2 = (TextView)view.findViewById(R.id.SingleContactName2); alphabetTextView = (TextView)view.findViewById(R.id.alphabets); contactNameList = contactService.getContactNameList(); scroll(); view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { + float step = (Utils.getScreenHeight(getActivity())/contactNameList.size()); switch (arg1.getAction()) { case MotionEvent.ACTION_MOVE: if(arg1.getY()>(singleContact.getY()+singleContact.getHeight())){ - singleContact.setTranslationY(singleContact.getY()+10); + singleContact.setTranslationY(singleContact.getY()+step); contactListPosition++; scroll(); }else if(arg1.getY()<(singleContact.getY())){ - singleContact.setTranslationY(singleContact.getY()-10); + singleContact.setTranslationY(singleContact.getY()-step); contactListPosition--; scroll(); } else{ singleContact.setTranslationY(arg1.getY()-singleContact.getHeight()/2); - float step = (Utils.getScreenHeight(getActivity())/contactNameList.size()); contactListPosition = (int)(arg1.getY()/step); scroll(); } break; default: break; } return true; } }); return view; } private void scroll(){ if(contactListPosition>=contactNameList.size()) contactListPosition=contactNameList.size()-1; if(contactListPosition<0) contactListPosition=0; int position = contactListPosition; // contactListPosition=position; if(position>2 && position<contactNameList.size()){ contact_2.setText(contactNameList.get(position-2)); }else{ contact_2.setText(""); } if(position>1 && position<contactNameList.size()){ contact_1.setText(contactNameList.get(position-1)); }else{ contact_1.setText(""); } if(position>=0 && position<contactNameList.size()){ contact.setText(contactNameList.get(position)); } if(position+1<contactNameList.size()){ contact1.setText(contactNameList.get(position+1)); }else{ contact1.setText(""); } if(position+2<contactNameList.size()){ contact2.setText(contactNameList.get(position+2)); }else { contact2.setText(""); } highlightAlphabets(); } private void highlightAlphabets(){ String textToHighlight = contactNameList.get(contactListPosition).substring(0, 1); // String.replaceAll(textToHighlight,<font color="red">textToHighlight</font>); Spannable WordtoSpan = new SpannableString("A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ"); WordtoSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#00B4FF")), WordtoSpan.toString().indexOf(textToHighlight), WordtoSpan.toString().indexOf(textToHighlight)+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); alphabetTextView.setText(WordtoSpan); // Textview.setText(Html.fromHtml(String)); } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.people_all, container, false); final View singleContact = (View)view.findViewById(R.id.single_contact); android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.getWidthForContact(getActivity()), android.widget.FrameLayout.LayoutParams.WRAP_CONTENT); singleContact.setLayoutParams(params); final TextView textView = (TextView)view.findViewById(R.id.alphabets); android.widget.LinearLayout.LayoutParams alphabets_params = new LinearLayout.LayoutParams(Utils.getWidthForAlphabets(getActivity()), android.widget.FrameLayout.LayoutParams.MATCH_PARENT); textView.setLayoutParams(alphabets_params); contact_2 = (TextView)view.findViewById(R.id.SingleContactName_2); contact_1 = (TextView)view.findViewById(R.id.SingleContactName_1); contact = (TextView)view.findViewById(R.id.SingleContactName); contact1 = (TextView)view.findViewById(R.id.SingleContactName1); contact2 = (TextView)view.findViewById(R.id.SingleContactName2); alphabetTextView = (TextView)view.findViewById(R.id.alphabets); contactNameList = contactService.getContactNameList(); scroll(); view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { switch (arg1.getAction()) { case MotionEvent.ACTION_MOVE: if(arg1.getY()>(singleContact.getY()+singleContact.getHeight())){ singleContact.setTranslationY(singleContact.getY()+10); contactListPosition++; scroll(); }else if(arg1.getY()<(singleContact.getY())){ singleContact.setTranslationY(singleContact.getY()-10); contactListPosition--; scroll(); } else{ singleContact.setTranslationY(arg1.getY()-singleContact.getHeight()/2); float step = (Utils.getScreenHeight(getActivity())/contactNameList.size()); contactListPosition = (int)(arg1.getY()/step); scroll(); } break; default: break; } return true; } }); return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.people_all, container, false); final View singleContact = (View)view.findViewById(R.id.single_contact); android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.getWidthForContact(getActivity()), android.widget.FrameLayout.LayoutParams.WRAP_CONTENT); singleContact.setLayoutParams(params); final TextView textView = (TextView)view.findViewById(R.id.alphabets); android.widget.LinearLayout.LayoutParams alphabets_params = new LinearLayout.LayoutParams(Utils.getWidthForAlphabets(getActivity()), android.widget.FrameLayout.LayoutParams.MATCH_PARENT); textView.setLayoutParams(alphabets_params); contact_2 = (TextView)view.findViewById(R.id.SingleContactName_2); contact_1 = (TextView)view.findViewById(R.id.SingleContactName_1); contact = (TextView)view.findViewById(R.id.SingleContactName); contact1 = (TextView)view.findViewById(R.id.SingleContactName1); contact2 = (TextView)view.findViewById(R.id.SingleContactName2); alphabetTextView = (TextView)view.findViewById(R.id.alphabets); contactNameList = contactService.getContactNameList(); scroll(); view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { float step = (Utils.getScreenHeight(getActivity())/contactNameList.size()); switch (arg1.getAction()) { case MotionEvent.ACTION_MOVE: if(arg1.getY()>(singleContact.getY()+singleContact.getHeight())){ singleContact.setTranslationY(singleContact.getY()+step); contactListPosition++; scroll(); }else if(arg1.getY()<(singleContact.getY())){ singleContact.setTranslationY(singleContact.getY()-step); contactListPosition--; scroll(); } else{ singleContact.setTranslationY(arg1.getY()-singleContact.getHeight()/2); contactListPosition = (int)(arg1.getY()/step); scroll(); } break; default: break; } return true; } }); return view; }
diff --git a/src/credentials/idemix/IdemixCredentials.java b/src/credentials/idemix/IdemixCredentials.java index 77af760..17e81c5 100644 --- a/src/credentials/idemix/IdemixCredentials.java +++ b/src/credentials/idemix/IdemixCredentials.java @@ -1,331 +1,332 @@ /** * IdemixCredentials.java * * 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/>. * * Copyright (C) Pim Vullers, Radboud University Nijmegen, May 2012. */ package credentials.idemix; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.ru.irma.api.tests.idemix.TestSetup; import net.sourceforge.scuba.smartcards.CardService; import net.sourceforge.scuba.smartcards.CardServiceException; import service.IdemixService; import service.IdemixSmartcard; import service.ProtocolCommand; import service.ProtocolResponses; import com.ibm.zurich.idmx.issuance.Issuer; import com.ibm.zurich.idmx.issuance.Message; import com.ibm.zurich.idmx.showproof.Proof; import com.ibm.zurich.idmx.showproof.Verifier; import com.ibm.zurich.idmx.utils.SystemParameters; import credentials.Attributes; import credentials.BaseCredentials; import credentials.CredentialsException; import credentials.Nonce; import credentials.idemix.spec.IdemixIssueSpecification; import credentials.idemix.spec.IdemixVerifySpecification; import credentials.keys.PrivateKey; import credentials.spec.IssueSpecification; import credentials.spec.VerifySpecification; /** * An Idemix specific implementation of the credentials interface. */ public class IdemixCredentials extends BaseCredentials { IdemixService service = null; public IdemixCredentials() { // TODO } public IdemixCredentials(CardService cs) { super(cs); } /** * Issue a credential to the user according to the provided specification * containing the specified values. * * @param specification * of the issuer and the credential to be issued. * @param values * to be stored in the credential. * @throws CredentialsException * if the issuance process fails. */ @Override public void issue(IssueSpecification specification, PrivateKey sk, Attributes values) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(specification); IdemixPrivateKey isk = castIdemixPrivateKey(sk); setupService(spec); // Initialise the issuer Issuer issuer = new Issuer(isk.getIssuerKeyPair(), spec.getIssuanceSpec(), null, null, spec.getValues(values)); // Initialise the recipient try { service.open(); + // FIXME: Change this! service.sendPin(TestSetup.DEFAULT_PIN); service.setIssuanceSpecification(spec.getIssuanceSpec()); service.setAttributes(spec.getIssuanceSpec(), spec.getValues(values)); } catch (CardServiceException e) { throw new CredentialsException( "Failed to issue the credential (SCUBA)"); } // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } Message msgToIssuer1 = service.round1(msgToRecipient1); if (msgToIssuer1 == null) { throw new CredentialsException("Failed to issue the credential (1)"); } Message msgToRecipient2 = issuer.round2(msgToIssuer1); if (msgToRecipient2 == null) { throw new CredentialsException("Failed to issue the credential (2)"); } service.round3(msgToRecipient2); } /** * Get a blank IssueSpecification matching this Credentials provider. * TODO: Proper implementation or remove it. * * @return a blank specification matching this provider. */ public IssueSpecification issueSpecification() { return null; } /** * Verify a number of attributes listed in the specification. * * @param specification * of the credential and attributes to be verified. * @return the attributes disclosed during the verification process or null * if verification failed * @throws CredentialsException */ public Attributes verify(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); setupService(spec); // Get a nonce from the verifier BigInteger nonce = Verifier.getNonce(spec.getProofSpec() .getGroupParams().getSystemParams()); // Initialise the prover try { service.open(); } catch (CardServiceException e) { throw new CredentialsException( "Failed to verify the attributes (SCUBA)"); } // Construct the proof Proof proof = service.buildProof(nonce, spec.getProofSpec()); // Initialise the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, nonce); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } return attributes; } /** * Get a blank VerifySpecification matching this Credentials provider. TODO: * proper implementation or remove it * * @return a blank specification matching this provider. */ @Override public VerifySpecification verifySpecification() { return null; } @Override public List<ProtocolCommand> requestProofCommands( VerifySpecification specification, Nonce nonce) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); return IdemixSmartcard.buildProofCommands(n.getNonce(), spec.getProofSpec(), spec.getIdemixId()); } @Override public Attributes verifyProofResponses(VerifySpecification specification, Nonce nonce, ProtocolResponses responses) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); IdemixNonce n = castNonce(nonce); // Create the proof Proof proof = IdemixSmartcard.processBuildProofResponses(responses, spec.getProofSpec()); // Initialize the verifier and verify the proof Verifier verifier = new Verifier(spec.getProofSpec(), proof, n.getNonce()); if (!verifier.verify()) { return null; } // Return the attributes that have been revealed during the proof Attributes attributes = new Attributes(); HashMap<String, BigInteger> values = verifier.getRevealedValues(); Iterator<String> i = values.keySet().iterator(); while (i.hasNext()) { String id = i.next(); attributes.add(id, values.get(id).toByteArray()); } return attributes; } /** * First part of issuance protocol. Not yet included in the interface as * this is subject to change. Most notably * - How do we integrate the issuer in this, I would guess the only state * in fact the nonce, so we could handle that a bit cleaner. Carrying around * the issuer object may not be the best solution * - We need to deal with the selectApplet and sendPinCommands better. * @throws CredentialsException */ public List<ProtocolCommand> requestIssueRound1Commands( IssueSpecification ispec, Attributes attributes, Issuer issuer) throws CredentialsException { ArrayList<ProtocolCommand> commands = new ArrayList<ProtocolCommand>(); IdemixIssueSpecification spec = castIssueSpecification(ispec); commands.addAll(IdemixSmartcard.setIssuanceSpecificationCommands( spec.getIssuanceSpec(), spec.getIdemixId())); commands.addAll(IdemixSmartcard.setAttributesCommands( spec.getIssuanceSpec(), spec.getValues(attributes))); // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } commands.addAll(IdemixSmartcard.round1Commands(spec.getIssuanceSpec(), msgToRecipient1)); return commands; } /** * Second part of issuing. Just like the first part still in flux. Note how * we can immediately process the responses as well as create new commands. * * @throws CredentialsException */ public List<ProtocolCommand> requestIssueRound3Commands(IssueSpecification ispec, Attributes attributes, Issuer issuer, ProtocolResponses responses) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(ispec); Message msgToIssuer = IdemixSmartcard.processRound1Responses(responses); Message msgToRecipient2 = issuer.round2(msgToIssuer); return IdemixSmartcard.round3Commands(spec.getIssuanceSpec(), msgToRecipient2); } @Override public Nonce generateNonce(VerifySpecification specification) throws CredentialsException { IdemixVerifySpecification spec = castVerifySpecification(specification); SystemParameters sp = spec.getProofSpec().getGroupParams() .getSystemParams(); BigInteger nonce = Verifier.getNonce(sp); return new IdemixNonce(nonce); } private static IdemixVerifySpecification castVerifySpecification( VerifySpecification spec) throws CredentialsException { if (!(spec instanceof IdemixVerifySpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixVerifySpecification) spec; } private static IdemixIssueSpecification castIssueSpecification( IssueSpecification spec) throws CredentialsException { if (!(spec instanceof IdemixIssueSpecification)) { throw new CredentialsException( "specification is not an IdemixVerifySpecification"); } return (IdemixIssueSpecification) spec; } private static IdemixNonce castNonce(Nonce nonce) throws CredentialsException { if (!(nonce instanceof IdemixNonce)) { throw new CredentialsException("nonce is not an IdemixNonce"); } return (IdemixNonce) nonce; } private IdemixPrivateKey castIdemixPrivateKey(PrivateKey sk) throws CredentialsException { if (!(sk instanceof IdemixPrivateKey)) { throw new CredentialsException( "PrivateKey is not an IdemixPrivateKey"); } return (IdemixPrivateKey) sk; } private void setupService(IdemixVerifySpecification spec) { service = new IdemixService(cs, spec.getIdemixId()); } private void setupService(IdemixIssueSpecification spec) { service = new IdemixService(cs, spec.getIdemixId()); } }
true
true
public void issue(IssueSpecification specification, PrivateKey sk, Attributes values) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(specification); IdemixPrivateKey isk = castIdemixPrivateKey(sk); setupService(spec); // Initialise the issuer Issuer issuer = new Issuer(isk.getIssuerKeyPair(), spec.getIssuanceSpec(), null, null, spec.getValues(values)); // Initialise the recipient try { service.open(); service.sendPin(TestSetup.DEFAULT_PIN); service.setIssuanceSpecification(spec.getIssuanceSpec()); service.setAttributes(spec.getIssuanceSpec(), spec.getValues(values)); } catch (CardServiceException e) { throw new CredentialsException( "Failed to issue the credential (SCUBA)"); } // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } Message msgToIssuer1 = service.round1(msgToRecipient1); if (msgToIssuer1 == null) { throw new CredentialsException("Failed to issue the credential (1)"); } Message msgToRecipient2 = issuer.round2(msgToIssuer1); if (msgToRecipient2 == null) { throw new CredentialsException("Failed to issue the credential (2)"); } service.round3(msgToRecipient2); }
public void issue(IssueSpecification specification, PrivateKey sk, Attributes values) throws CredentialsException { IdemixIssueSpecification spec = castIssueSpecification(specification); IdemixPrivateKey isk = castIdemixPrivateKey(sk); setupService(spec); // Initialise the issuer Issuer issuer = new Issuer(isk.getIssuerKeyPair(), spec.getIssuanceSpec(), null, null, spec.getValues(values)); // Initialise the recipient try { service.open(); // FIXME: Change this! service.sendPin(TestSetup.DEFAULT_PIN); service.setIssuanceSpecification(spec.getIssuanceSpec()); service.setAttributes(spec.getIssuanceSpec(), spec.getValues(values)); } catch (CardServiceException e) { throw new CredentialsException( "Failed to issue the credential (SCUBA)"); } // Issue the credential Message msgToRecipient1 = issuer.round0(); if (msgToRecipient1 == null) { throw new CredentialsException("Failed to issue the credential (0)"); } Message msgToIssuer1 = service.round1(msgToRecipient1); if (msgToIssuer1 == null) { throw new CredentialsException("Failed to issue the credential (1)"); } Message msgToRecipient2 = issuer.round2(msgToIssuer1); if (msgToRecipient2 == null) { throw new CredentialsException("Failed to issue the credential (2)"); } service.round3(msgToRecipient2); }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java index 1ef34cce9..fb0e835d3 100755 --- a/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java @@ -1,583 +1,583 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * 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 General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.java.codegen; import static com.sun.tools.javac.code.Flags.FINAL; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CaseClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CaseItem; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CatchClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ElseClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.FinallyClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ForIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.IsCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.KeyValueIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MatchCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SatisfiesCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchCaseList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Throw; import com.redhat.ceylon.compiler.typechecker.tree.Tree.TryCatchStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.TryClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Variable; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * This transformer deals with statements only */ public class StatementTransformer extends AbstractTransformer { // Used to hold the name of the variable associated with the fail-block if the innermost for-loop // Is null if we're currently in a while-loop or not in any loop at all private Name currentForFailVariable = null; public static StatementTransformer getInstance(Context context) { StatementTransformer trans = context.get(StatementTransformer.class); if (trans == null) { trans = new StatementTransformer(context); context.put(StatementTransformer.class, trans); } return trans; } private StatementTransformer(Context context) { super(context); } public JCBlock transform(Tree.Block block) { return block == null ? null : at(block).Block(0, transformStmts(block.getStatements())); } @SuppressWarnings("unchecked") List<JCStatement> transformStmts(java.util.List<Tree.Statement> list) { CeylonVisitor v = new CeylonVisitor(gen()); for (Tree.Statement stmt : list) stmt.visit(v); return (List<JCStatement>) v.getResult().toList(); } List<JCStatement> transform(Tree.IfStatement stmt) { Tree.Block thenPart = stmt.getIfClause().getBlock(); Tree.Block elsePart = stmt.getElseClause() != null ? stmt.getElseClause().getBlock() : null; return transformCondition(stmt.getIfClause().getCondition(), JCTree.IF, thenPart, elsePart); } List<JCStatement> transform(Tree.WhileStatement stmt) { Name tempForFailVariable = currentForFailVariable; currentForFailVariable = null; Tree.Block thenPart = stmt.getWhileClause().getBlock(); List<JCStatement> res = transformCondition(stmt.getWhileClause().getCondition(), JCTree.WHILELOOP, thenPart, null); currentForFailVariable = tempForFailVariable; return res; } private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); String tmpVarName = aliasName(name); Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, NO_PRIMITIVES | WANT_RAW_TYPE); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = makeUnquotedIdent(tmpVarName); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); - tmpVarTypeExpr = makeJavaType(tmpVarType); + tmpVarTypeExpr = makeJavaType(tmpVarType, NO_PRIMITIVES); } else if(cond instanceof Tree.IsCondition){ tmpVarExpr = unboxType(at(cond).TypeCast(rawToTypeExpr, tmpVarExpr), toType); tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); - tmpVarTypeExpr = makeJavaType(tmpVarType); + tmpVarTypeExpr = makeJavaType(tmpVarType, NO_PRIMITIVES); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution removeVariableSubst(origVarName.toString(), prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression testExpr = make().Assign(makeUnquotedIdent(tmpVarName), expr); // Use the assignment in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, testExpr, makeNull()); } else { // nonempty and is test = makeTypeTest(testExpr, expr, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } } List<JCStatement> transform(Tree.ForStatement stmt) { Name tempForFailVariable = currentForFailVariable; at(stmt); List<JCStatement> outer = List.<JCStatement> nil(); if (stmt.getElseClause() != null) { // boolean $doforelse$X = true; JCVariableDecl failtest_decl = make().VarDef(make().Modifiers(0), names().fromString(aliasName("doforelse")), make().TypeIdent(TypeTags.BOOLEAN), make().Literal(TypeTags.BOOLEAN, 1)); outer = outer.append(failtest_decl); currentForFailVariable = failtest_decl.getName(); } else { currentForFailVariable = null; } // java.lang.Object $elem$X; String elem_name = aliasName("elem"); JCVariableDecl elem_decl = make().VarDef(make().Modifiers(0), names().fromString(elem_name), make().Type(syms().objectType), null); outer = outer.append(elem_decl); ForIterator iterDecl = stmt.getForClause().getForIterator(); Variable variable; Variable variable2; if (iterDecl instanceof ValueIterator) { variable = ((ValueIterator) iterDecl).getVariable(); variable2 = null; } else if (iterDecl instanceof KeyValueIterator) { variable = ((KeyValueIterator) iterDecl).getKeyVariable(); variable2 = ((KeyValueIterator) iterDecl).getValueVariable(); } else { throw new RuntimeException("Unknown ForIterator"); } String loop_var_name = variable.getIdentifier().getText(); Expression specifierExpression = iterDecl.getSpecifierExpression().getExpression(); ProducedType sequence_element_type; if(variable2 == null) sequence_element_type = variable.getType().getTypeModel(); else{ // Entry<V1,V2> sequence_element_type = typeFact().getEntryType(variable.getType().getTypeModel(), variable2.getType().getTypeModel()); } ProducedType iter_type = typeFact().getIteratorType(sequence_element_type); JCExpression iter_type_expr = makeJavaType(iter_type, CeylonTransformer.TYPE_ARGUMENT); JCExpression cast_elem = at(stmt).TypeCast(makeJavaType(sequence_element_type, CeylonTransformer.NO_PRIMITIVES), makeUnquotedIdent(elem_name)); List<JCAnnotation> annots = makeJavaTypeAnnotations(variable.getDeclarationModel()); // ceylon.language.Iterator<T> $V$iter$X = ITERABLE.getIterator(); // We don't need to unerase here as anything remotely a sequence will be erased to Iterable, which has getIterator() JCExpression containment = expressionGen().transformExpression(specifierExpression, BoxingStrategy.BOXED, null); JCVariableDecl iter_decl = at(stmt).VarDef(make().Modifiers(0), names().fromString(aliasName(loop_var_name + "$iter")), iter_type_expr, at(stmt).Apply(null, makeSelect(containment, "getIterator"), List.<JCExpression> nil())); String iter_id = iter_decl.getName().toString(); // final U n = $elem$X; // or // final U n = $elem$X.getKey(); JCExpression loop_var_init; ProducedType loop_var_type; if (variable2 == null) { loop_var_type = sequence_element_type; loop_var_init = cast_elem; } else { loop_var_type = actualType(variable); loop_var_init = at(stmt).Apply(null, makeSelect(cast_elem, Util.getGetterName("key")), List.<JCExpression> nil()); } JCVariableDecl item_decl = at(stmt).VarDef(make().Modifiers(FINAL, annots), names().fromString(loop_var_name), makeJavaType(loop_var_type), unboxType(loop_var_init, loop_var_type)); List<JCStatement> for_loop = List.<JCStatement> of(item_decl); if (variable2 != null) { // final V n = $elem$X.getElement(); ProducedType item_type2 = actualType(variable2); JCExpression item_type_expr2 = makeJavaType(item_type2); JCExpression loop_var_init2 = at(stmt).Apply(null, makeSelect(cast_elem, Util.getGetterName("item")), List.<JCExpression> nil()); String loop_var_name2 = variable2.getIdentifier().getText(); JCVariableDecl item_decl2 = at(stmt).VarDef(make().Modifiers(FINAL, annots), names().fromString(loop_var_name2), item_type_expr2, unboxType(loop_var_init2, item_type2)); for_loop = for_loop.append(item_decl2); } // The user-supplied contents of the loop for_loop = for_loop.appendList(transformStmts(stmt.getForClause().getBlock().getStatements())); // $elem$X = $V$iter$X.next() JCExpression iter_elem = make().Apply(null, makeSelect(iter_id, "next"), List.<JCExpression> nil()); JCExpression elem_assign = make().Assign(makeUnquotedIdent(elem_name), iter_elem); // !(($elem$X = $V$iter$X.next()) instanceof Finished) JCExpression instof = make().TypeTest(elem_assign, make().Type(syms().ceylonFinishedType)); JCExpression cond = make().Unary(JCTree.NOT, instof); // No step necessary List<JCExpressionStatement> step = List.<JCExpressionStatement>nil(); // for (.ceylon.language.Iterator<T> $V$iter$X = ITERABLE.iterator(); !(($elem$X = $V$iter$X.next()) instanceof Finished); ) { outer = outer.append(at(stmt).ForLoop( List.<JCStatement>of(iter_decl), cond, step, at(stmt).Block(0, for_loop))); if (stmt.getElseClause() != null) { // The user-supplied contents of fail block List<JCStatement> failblock = transformStmts(stmt.getElseClause().getBlock().getStatements()); // if ($doforelse$X) ... JCIdent failtest_id = at(stmt).Ident(currentForFailVariable); outer = outer.append(at(stmt).If(failtest_id, at(stmt).Block(0, failblock), null)); } currentForFailVariable = tempForFailVariable; return outer; } // FIXME There is a similar implementation in ClassGen! public JCStatement transform(AttributeDeclaration decl) { Name atrrName = names().fromString(decl.getIdentifier().getText()); ProducedType t = actualType(decl); JCExpression initialValue = null; if (decl.getSpecifierOrInitializerExpression() != null) { initialValue = expressionGen().transformExpression(decl.getSpecifierOrInitializerExpression().getExpression(), Util.getBoxingStrategy(decl.getDeclarationModel()), decl.getDeclarationModel().getType()); } JCExpression type = makeJavaType(t); List<JCAnnotation> annots = makeJavaTypeAnnotations(decl.getDeclarationModel()); int modifiers = transformLocalFieldDeclFlags(decl); return at(decl).VarDef(at(decl).Modifiers(modifiers, annots), atrrName, type, initialValue); } List<JCStatement> transform(Tree.Break stmt) { // break; JCStatement brk = at(stmt).Break(null); if (currentForFailVariable != null) { JCIdent failtest_id = at(stmt).Ident(currentForFailVariable); List<JCStatement> list = List.<JCStatement> of(at(stmt).Exec(at(stmt).Assign(failtest_id, make().Literal(TypeTags.BOOLEAN, 0)))); list = list.append(brk); return list; } else { return List.<JCStatement> of(brk); } } JCStatement transform(Tree.Continue stmt) { // continue; return at(stmt).Continue(null); } JCStatement transform(Tree.Return ret) { Tree.Expression expr = ret.getExpression(); JCExpression returnExpr = null; at(ret); if (expr != null) { // we can cast to TypedDeclaration here because return with expressions are only in Method or Value TypedDeclaration declaration = (TypedDeclaration)ret.getDeclaration(); // make sure we use the best declaration for boxing and type declaration = nonWideningTypeDecl(declaration); returnExpr = expressionGen().transformExpression(expr.getTerm(), Util.getBoxingStrategy(declaration), declaration.getType()); } return at(ret).Return(returnExpr); } public JCStatement transform(Throw t) { at(t); Expression expr = t.getExpression(); final JCExpression exception; if (expr == null) {// bare "throw;" stmt exception = make().NewClass(null, null, makeIdent(syms().ceylonExceptionType), List.<JCExpression>of(makeNull(), makeNull()), null); } else { // we must unerase the exception to Throwable ProducedType exceptionType = expr.getTypeModel().getSupertype(t.getUnit().getExceptionDeclaration()); exception = gen().expressionGen().transformExpression(expr, BoxingStrategy.UNBOXED, exceptionType); } return make().Throw(exception); } public JCStatement transform(TryCatchStatement t) { // TODO Support resources -- try(Usage u = ...) { ... TryClause tryClause = t.getTryClause(); at(tryClause); JCBlock tryBlock = transform(tryClause.getBlock()); final ListBuffer<JCCatch> catches = ListBuffer.<JCCatch>lb(); for (CatchClause catchClause : t.getCatchClauses()) { at(catchClause); java.util.List<ProducedType> exceptionTypes; Variable variable = catchClause.getCatchVariable().getVariable(); ProducedType exceptionType = variable.getDeclarationModel().getType(); if (typeFact().isUnion(exceptionType)) { exceptionTypes = exceptionType.getDeclaration().getCaseTypes(); } else { exceptionTypes = List.<ProducedType>of(exceptionType); } for (ProducedType type : exceptionTypes) { // catch blocks for each exception in the union JCVariableDecl param = make().VarDef(make().Modifiers(Flags.FINAL), names().fromString(variable.getIdentifier().getText()), makeJavaType(type, CATCH), null); catches.add(make().Catch(param, transform(catchClause.getBlock()))); } } final JCBlock finallyBlock; FinallyClause finallyClause = t.getFinallyClause(); if (finallyClause != null) { at(finallyClause); finallyBlock = transform(finallyClause.getBlock()); } else { finallyBlock = null; } return at(t).Try(tryBlock, catches.toList(), finallyBlock); } private int transformLocalFieldDeclFlags(Tree.AttributeDeclaration cdecl) { int result = 0; result |= cdecl.getDeclarationModel().isVariable() ? 0 : FINAL; return result; } /** * Transforms a Ceylon switch to a Java {@code if/else if} chain. * @param stmt The Ceylon switch * @return The Java tree */ JCStatement transform(SwitchStatement stmt) { SwitchClause switchClause = stmt.getSwitchClause(); JCExpression selectorExpr = expressionGen().transformExpression(switchClause.getExpression(), BoxingStrategy.UNBOXED, switchClause.getExpression().getTypeModel()); String selectorAlias = aliasName("sel"); JCVariableDecl selector = makeVar(selectorAlias, make().Type(syms().objectType), selectorExpr); SwitchCaseList caseList = stmt.getSwitchCaseList(); JCStatement last = null; ElseClause elseClause = caseList.getElseClause(); if (elseClause != null) { last = transform(elseClause.getBlock()); } else { // To avoid possible javac warnings about uninitialized vars we // need to have an 'else' clause, even if the ceylon code doesn't // require one. // This exception could be thrown for example if an enumerated // type is recompiled after having a subclass added, but the // switch is not recompiled. last = make().Throw( make().NewClass(null, List.<JCExpression>nil(), makeIdent(syms().ceylonEnumeratedTypeErrorType), List.<JCExpression>of(make().Literal( "Supposedly exhaustive switch was not exhaustive")), null)); } java.util.List<CaseClause> caseClauses = caseList.getCaseClauses(); for (int ii = caseClauses.size() - 1; ii >= 0; ii--) {// reverse order CaseClause caseClause = caseClauses.get(ii); CaseItem caseItem = caseClause.getCaseItem(); if (caseItem instanceof IsCase) { last = transformCaseIs(selectorAlias, caseClause, (IsCase)caseItem, last); } else if (caseItem instanceof SatisfiesCase) { // TODO Support for 'case (satisfies ...)' is not implemented yet return make().Exec(makeErroneous(caseItem, "switch/satisfies not implemented yet")); } else if (caseItem instanceof MatchCase) { last = transformCaseMatch(selectorAlias, caseClause, (MatchCase)caseItem, last); } else { return make().Exec(makeErroneous(caseItem, "unknown switch case clause: "+caseItem)); } } return at(stmt).Block(0, List.of(selector, last)); } private JCStatement transformCaseMatch(String selectorAlias, CaseClause caseClause, MatchCase matchCase, JCStatement last) { at(matchCase); JCExpression tests = null; java.util.List<Tree.Expression> expressions = matchCase.getExpressionList().getExpressions(); for(Tree.Expression expr : expressions){ JCExpression transformedExpression = expressionGen().transformExpression(expr); JCBinary test = make().Binary(JCTree.EQ, makeUnquotedIdent(selectorAlias), transformedExpression); if(tests == null) tests = test; else tests = make().Binary(JCTree.OR, tests, test); } return at(caseClause).If(tests, transform(caseClause.getBlock()), last); } /** * Transform a "case(is ...)" * @param selectorAlias * @param caseClause * @param isCase * @param last * @return */ private JCStatement transformCaseIs(String selectorAlias, CaseClause caseClause, IsCase isCase, JCStatement last) { at(isCase); ProducedType type = isCase.getType().getTypeModel(); JCExpression cond = makeTypeTest(makeUnquotedIdent(selectorAlias), type); JCExpression toTypeExpr = makeJavaType(type); String name = isCase.getVariable().getIdentifier().getText(); String tmpVarName = selectorAlias; Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(type, NO_PRIMITIVES | WANT_RAW_TYPE); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = makeUnquotedIdent(tmpVarName); tmpVarExpr = unboxType(at(isCase).TypeCast(rawToTypeExpr, tmpVarExpr), type); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(isCase).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); JCBlock block = transform(caseClause.getBlock()); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(block.getStatements()); block = at(isCase).Block(0, stats); // Deactivate the above variable substitution removeVariableSubst(origVarName.toString(), prevSubst); last = make().If(cond, block, last); return last; } }
false
true
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); String tmpVarName = aliasName(name); Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, NO_PRIMITIVES | WANT_RAW_TYPE); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = makeUnquotedIdent(tmpVarName); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType); } else if(cond instanceof Tree.IsCondition){ tmpVarExpr = unboxType(at(cond).TypeCast(rawToTypeExpr, tmpVarExpr), toType); tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution removeVariableSubst(origVarName.toString(), prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression testExpr = make().Assign(makeUnquotedIdent(tmpVarName), expr); // Use the assignment in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, testExpr, makeNull()); } else { // nonempty and is test = makeTypeTest(testExpr, expr, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); String tmpVarName = aliasName(name); Name origVarName = names().fromString(name); Name substVarName = names().fromString(aliasName(name)); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, NO_PRIMITIVES | WANT_RAW_TYPE); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = makeUnquotedIdent(tmpVarName); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType, NO_PRIMITIVES); } else if(cond instanceof Tree.IsCondition){ tmpVarExpr = unboxType(at(cond).TypeCast(rawToTypeExpr, tmpVarExpr), toType); tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType, NO_PRIMITIVES); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = addVariableSubst(origVarName.toString(), substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution removeVariableSubst(origVarName.toString(), prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression testExpr = make().Assign(makeUnquotedIdent(tmpVarName), expr); // Use the assignment in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, testExpr, makeNull()); } else { // nonempty and is test = makeTypeTest(testExpr, expr, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
diff --git a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/AbstractViewerTag.java b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/AbstractViewerTag.java index 5a3deacf..5705fca3 100644 --- a/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/AbstractViewerTag.java +++ b/plugins/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/taglib/AbstractViewerTag.java @@ -1,554 +1,554 @@ /************************************************************************************* * Copyright (c) 2004 Actuate 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: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.taglib; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.JspWriter; import org.eclipse.birt.report.resource.BirtResources; import org.eclipse.birt.report.resource.ResourceConstants; import org.eclipse.birt.report.taglib.component.ParameterField; import org.eclipse.birt.report.taglib.util.BirtTagUtil; import org.eclipse.birt.report.utility.DataUtil; import org.eclipse.birt.report.utility.ParameterAccessor; /** * Abstract class for viewer tag. List base attributes for a viewer tag. * */ public abstract class AbstractViewerTag extends AbstractBaseTag { private static final long serialVersionUID = -7188886543126605745L; /** * Locale information */ protected Locale locale; /** * Report parameters */ protected Map parameters; /** * Then entry to initialize tag * * @throws Exception */ public void __init( ) { super.__init( ); parameters = new HashMap( ); } /** * validate the tag * * @see org.eclipse.birt.report.taglib.AbstractBaseTag#__validate() */ public boolean __validate( ) throws Exception { String hasHostPage = (String) pageContext.getAttribute( ATTR_HOSTPAGE ); if ( hasHostPage != null && "true".equalsIgnoreCase( hasHostPage ) ) //$NON-NLS-1$ { return false; } // get Locale this.locale = BirtTagUtil.getLocale( (HttpServletRequest) pageContext .getRequest( ), viewer.getLocale( ) ); // Set locale information BirtResources.setLocale( this.locale ); // Validate viewer id if ( viewer.getId( ) == null || viewer.getId( ).length( ) <= 0 ) { throw new JspTagException( BirtResources .getMessage( ResourceConstants.TAGLIB_NO_ATTR_ID ) ); } if ( !__validateViewerId( ) ) { throw new JspTagException( BirtResources .getMessage( ResourceConstants.TAGLIB_INVALID_ATTR_ID ) ); } // validate the viewer id if unique if ( pageContext.findAttribute( viewer.getId( ) ) != null ) { throw new JspTagException( BirtResources .getMessage( ResourceConstants.TAGLIB_ATTR_ID_DUPLICATE ) ); } // Report design or document should be specified if ( viewer.getReportDesign( ) == null && viewer.getReportDocument( ) == null ) { throw new JspTagException( BirtResources .getMessage( ResourceConstants.TAGLIB_NO_REPORT_SOURCE ) ); } // If preview reportlet, report document file should be specified. if ( viewer.getReportletId( ) != null && viewer.getReportDocument( ) == null ) { throw new JspTagException( BirtResources .getMessage( ResourceConstants.TAGLIB_NO_REPORT_DOCUMENT ) ); } return true; } /** * Validate the viewer id. Viewer id only can include number, letter and * underline * * @return */ protected boolean __validateViewerId( ) { Pattern p = Pattern.compile( "^\\w+$" ); //$NON-NLS-1$ Matcher m = p.matcher( viewer.getId( ) ); return m.find( ); } /** * Handle event before doEndTag */ protected void __beforeEndTag( ) { super.__beforeEndTag( ); viewer.setParameters( parameters ); // Save viewer id pageContext.setAttribute( viewer.getId( ), viewer.getId( ) ); // Save has HostPage if ( viewer.isHostPage( ) ) pageContext.setAttribute( ATTR_HOSTPAGE, "true" ); //$NON-NLS-1$ } /** * Handle use IFrame to preview report. Each IFrame should have an unique * id. * * @param src * @param target * @throws Exception */ protected void __handleIFrame( String src, String target ) throws Exception { JspWriter writer = pageContext.getOut( ); // prepare parameters String paramContainerId = "params_" + viewer.getId( ); //$NON-NLS-1$ writer .write( "<div id=\"" + paramContainerId + "\" style='display:none'>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ Iterator it = viewer.getParameters( ).values( ).iterator( ); while ( it.hasNext( ) ) { ParameterField param = (ParameterField) it.next( ); // get parameter name String encParamName = ParameterAccessor .htmlEncode( param.getName( ) ); Object[] values; Object valueObj = param.getValue( ); // support multi-value parameter if ( valueObj != null && valueObj instanceof Object[] ) { values = (Object[]) valueObj; } else { values = new Object[1]; values[0] = valueObj; } for ( int i = 0; i < values.length; i++ ) { // parse parameter object as standard format String paramValue = DataUtil.getDisplayValue( values[i] ); // set NULL parameter if ( paramValue == null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISNULL + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ continue; } // set Parameter value writer .write( "<input type = 'hidden' name=\"" + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + paramValue + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // if value is string/string[], check whether set isLocale flag if ( valueObj != null && param.isLocale( ) && ( valueObj instanceof String || valueObj instanceof String[] ) ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISLOCALE + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter pattern format if ( param.getPattern( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + encParamName + "_format\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getPattern( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter display text if ( param.getDisplayText( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PREFIX_DISPLAY_TEXT + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getDisplayText( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } } writer.write( "</div>\n" ); //$NON-NLS-1$ // create form String formId = "form_" + viewer.getId( ); //$NON-NLS-1$ writer.write( "<form id=\"" + formId + "\" method=\"post\"></form>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "<script type=\"text/javascript\">\n" ); //$NON-NLS-1$ writer.write( "function loadViewer" + viewer.getId( ) + "(){\n" ); //$NON-NLS-1$//$NON-NLS-2$ writer .write( "var formObj = document.getElementById( \"" + formId + "\" );\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "var paramContainer = document.getElementById(\"" //$NON-NLS-1$ + paramContainerId + "\");\n" ); //$NON-NLS-1$ writer .write( "var oParams = paramContainer.getElementsByTagName('input');\n" ); //$NON-NLS-1$ writer.write( "if( oParams )\n" ); //$NON-NLS-1$ writer.write( "{\n" ); //$NON-NLS-1$ writer.write( " for( var i=0;i<oParams.length;i++ ) \n" ); //$NON-NLS-1$ writer.write( " {\n" ); //$NON-NLS-1$ - writer.write( " var param = document.createElement( \"INPUT\" );\n" ); //$NON-NLS-1$ - writer.write( " formObj.appendChild( param );\n" ); //$NON-NLS-1$ - writer.write( " param.TYPE = \"HIDDEN\";\n" ); //$NON-NLS-1$ + writer.write( " var param = document.createElement( \"INPUT\" );\n" ); //$NON-NLS-1$ + writer.write( " param.type = \"HIDDEN\";\n" ); //$NON-NLS-1$ writer.write( " param.name= oParams[i].name;\n" ); //$NON-NLS-1$ writer.write( " param.value= oParams[i].value;\n" ); //$NON-NLS-1$ + writer.write( " formObj.appendChild( param );\n" ); //$NON-NLS-1$ writer.write( " }\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "formObj.action = \"" + src + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ if ( target != null ) writer.write( "formObj.target = \"" + target + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "formObj.submit( );\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "</script>\n" ); //$NON-NLS-1$ // write IFrame object writer.write( __handleIFrameDefinition( ) ); writer.write( "<script type=\"text/javascript\">" ); //$NON-NLS-1$ writer.write( "loadViewer" + viewer.getId( ) + "();" ); //$NON-NLS-1$//$NON-NLS-2$ writer.write( "</script>\n" ); //$NON-NLS-1$ } /** * Handle IFrame definition * * @return */ protected String __handleIFrameDefinition( ) { // create IFrame object String iframe = "<iframe name=\"" + viewer.getId( ) //$NON-NLS-1$ + "\" frameborder=\"" + viewer.getFrameborder( ) + "\" "; //$NON-NLS-1$ //$NON-NLS-2$ if ( viewer.getScrolling( ) != null ) iframe += " scrolling = \"" + viewer.getScrolling( ) + "\" "; //$NON-NLS-1$ //$NON-NLS-2$ iframe += __handleAppearance( ) + "></iframe>\r\n"; //$NON-NLS-1$ return iframe; } /** * IFrame Appearance style * * @return */ protected String __handleAppearance( ) { String style = " style='"; //$NON-NLS-1$ // position if ( viewer.getPosition( ) != null ) style += "position:" + viewer.getPosition( ) + ";"; //$NON-NLS-1$//$NON-NLS-2$ // height if ( viewer.getHeight( ) >= 0 ) style += "height:" + viewer.getHeight( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$ // width if ( viewer.getWidth( ) >= 0 ) style += "width:" + viewer.getWidth( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$ // top if ( viewer.getTop( ) != null ) style += "top:" + viewer.getTop( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$ // left if ( viewer.getLeft( ) != null ) style = style + "left:" + viewer.getLeft( ) + "px;"; //$NON-NLS-1$//$NON-NLS-2$ // style if ( viewer.getStyle( ) != null ) style += viewer.getStyle( ) + ";"; //$NON-NLS-1$ style += "' "; //$NON-NLS-1$ return style; } /** * Add parameter into list * * @param field */ public void addParameter( ParameterField field ) { if ( field != null ) parameters.put( field.getName( ), field ); } /** * @param id * the id to set */ public void setId( String id ) { viewer.setId( id ); } /** * @param baseURL * the baseURL to set */ public void setBaseURL( String baseURL ) { viewer.setBaseURL( baseURL ); } /** * @param isHostPage * the isHostPage to set */ public void setIsHostPage( String isHostPage ) { viewer.setHostPage( Boolean.valueOf( isHostPage ).booleanValue( ) ); } /** * @param scrolling * the scrolling to set */ public void setScrolling( String scrolling ) { viewer.setScrolling( scrolling ); } /** * @param position * the position to set */ public void setPosition( String position ) { viewer.setPosition( position ); } /** * @param style * the style to set */ public void setStyle( String style ) { viewer.setStyle( style ); } /** * @param height * the height to set */ public void setHeight( String height ) { viewer.setHeight( Integer.parseInt( height ) ); } /** * @param width * the width to set */ public void setWidth( String width ) { viewer.setWidth( Integer.parseInt( width ) ); } /** * @param left * the left to set */ public void setLeft( String left ) { viewer.setLeft( "" + Integer.parseInt( left ) ); //$NON-NLS-1$ } /** * @param top * the top to set */ public void setTop( String top ) { viewer.setTop( "" + Integer.parseInt( top ) ); //$NON-NLS-1$ } /** * @param frameborder * the frameborder to set */ public void setFrameborder( String frameborder ) { viewer.setFrameborder( frameborder ); } /** * @param reportDesign * the reportDesign to set */ public void setReportDesign( String reportDesign ) { viewer.setReportDesign( reportDesign ); } /** * @param reportDocument * the reportDocument to set */ public void setReportDocument( String reportDocument ) { viewer.setReportDocument( reportDocument ); } /** * @param bookmark * the bookmark to set */ public void setBookmark( String bookmark ) { viewer.setBookmark( bookmark ); } /** * @param reportletId * the reportletId to set */ public void setReportletId( String reportletId ) { viewer.setReportletId( reportletId ); } /** * @param locale * the locale to set */ public void setLocale( String locale ) { viewer.setLocale( locale ); } /** * @param format * the format to set */ public void setFormat( String format ) { viewer.setFormat( format ); } /** * @param svg * the svg to set */ public void setSvg( String svg ) { viewer.setSvg( BirtTagUtil.convertBooleanValue( svg ) ); } /** * @param rtl * the rtl to set */ public void setRtl( String rtl ) { viewer.setRtl( BirtTagUtil.convertBooleanValue( rtl ) ); } /** * @param pageNum * the pageNum to set */ public void setPageNum( String pageNum ) { viewer.setPageNum( Long.parseLong( pageNum ) ); } /** * @param pageRange * the pageRange to set */ public void setPageRange( String pageRange ) { viewer.setPageRange( pageRange ); } /** * @param showParameterPage * the showParameterPage to set */ public void setShowParameterPage( String showParameterPage ) { viewer.setShowParameterPage( showParameterPage ); } /** * @param resourceFolder * the resourceFolder to set */ public void setResourceFolder( String resourceFolder ) { viewer.setResourceFolder( resourceFolder ); } }
false
true
protected void __handleIFrame( String src, String target ) throws Exception { JspWriter writer = pageContext.getOut( ); // prepare parameters String paramContainerId = "params_" + viewer.getId( ); //$NON-NLS-1$ writer .write( "<div id=\"" + paramContainerId + "\" style='display:none'>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ Iterator it = viewer.getParameters( ).values( ).iterator( ); while ( it.hasNext( ) ) { ParameterField param = (ParameterField) it.next( ); // get parameter name String encParamName = ParameterAccessor .htmlEncode( param.getName( ) ); Object[] values; Object valueObj = param.getValue( ); // support multi-value parameter if ( valueObj != null && valueObj instanceof Object[] ) { values = (Object[]) valueObj; } else { values = new Object[1]; values[0] = valueObj; } for ( int i = 0; i < values.length; i++ ) { // parse parameter object as standard format String paramValue = DataUtil.getDisplayValue( values[i] ); // set NULL parameter if ( paramValue == null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISNULL + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ continue; } // set Parameter value writer .write( "<input type = 'hidden' name=\"" + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + paramValue + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // if value is string/string[], check whether set isLocale flag if ( valueObj != null && param.isLocale( ) && ( valueObj instanceof String || valueObj instanceof String[] ) ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISLOCALE + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter pattern format if ( param.getPattern( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + encParamName + "_format\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getPattern( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter display text if ( param.getDisplayText( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PREFIX_DISPLAY_TEXT + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getDisplayText( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } } writer.write( "</div>\n" ); //$NON-NLS-1$ // create form String formId = "form_" + viewer.getId( ); //$NON-NLS-1$ writer.write( "<form id=\"" + formId + "\" method=\"post\"></form>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "<script type=\"text/javascript\">\n" ); //$NON-NLS-1$ writer.write( "function loadViewer" + viewer.getId( ) + "(){\n" ); //$NON-NLS-1$//$NON-NLS-2$ writer .write( "var formObj = document.getElementById( \"" + formId + "\" );\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "var paramContainer = document.getElementById(\"" //$NON-NLS-1$ + paramContainerId + "\");\n" ); //$NON-NLS-1$ writer .write( "var oParams = paramContainer.getElementsByTagName('input');\n" ); //$NON-NLS-1$ writer.write( "if( oParams )\n" ); //$NON-NLS-1$ writer.write( "{\n" ); //$NON-NLS-1$ writer.write( " for( var i=0;i<oParams.length;i++ ) \n" ); //$NON-NLS-1$ writer.write( " {\n" ); //$NON-NLS-1$ writer.write( " var param = document.createElement( \"INPUT\" );\n" ); //$NON-NLS-1$ writer.write( " formObj.appendChild( param );\n" ); //$NON-NLS-1$ writer.write( " param.TYPE = \"HIDDEN\";\n" ); //$NON-NLS-1$ writer.write( " param.name= oParams[i].name;\n" ); //$NON-NLS-1$ writer.write( " param.value= oParams[i].value;\n" ); //$NON-NLS-1$ writer.write( " }\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "formObj.action = \"" + src + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ if ( target != null ) writer.write( "formObj.target = \"" + target + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "formObj.submit( );\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "</script>\n" ); //$NON-NLS-1$ // write IFrame object writer.write( __handleIFrameDefinition( ) ); writer.write( "<script type=\"text/javascript\">" ); //$NON-NLS-1$ writer.write( "loadViewer" + viewer.getId( ) + "();" ); //$NON-NLS-1$//$NON-NLS-2$ writer.write( "</script>\n" ); //$NON-NLS-1$ }
protected void __handleIFrame( String src, String target ) throws Exception { JspWriter writer = pageContext.getOut( ); // prepare parameters String paramContainerId = "params_" + viewer.getId( ); //$NON-NLS-1$ writer .write( "<div id=\"" + paramContainerId + "\" style='display:none'>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ Iterator it = viewer.getParameters( ).values( ).iterator( ); while ( it.hasNext( ) ) { ParameterField param = (ParameterField) it.next( ); // get parameter name String encParamName = ParameterAccessor .htmlEncode( param.getName( ) ); Object[] values; Object valueObj = param.getValue( ); // support multi-value parameter if ( valueObj != null && valueObj instanceof Object[] ) { values = (Object[]) valueObj; } else { values = new Object[1]; values[0] = valueObj; } for ( int i = 0; i < values.length; i++ ) { // parse parameter object as standard format String paramValue = DataUtil.getDisplayValue( values[i] ); // set NULL parameter if ( paramValue == null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISNULL + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ continue; } // set Parameter value writer .write( "<input type = 'hidden' name=\"" + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + paramValue + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // if value is string/string[], check whether set isLocale flag if ( valueObj != null && param.isLocale( ) && ( valueObj instanceof String || valueObj instanceof String[] ) ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PARAM_ISLOCALE + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + encParamName + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter pattern format if ( param.getPattern( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + encParamName + "_format\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getPattern( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } // set parameter display text if ( param.getDisplayText( ) != null ) { writer .write( "<input type = 'hidden' name=\"" + ParameterAccessor.PREFIX_DISPLAY_TEXT + encParamName + "\" \n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( " value=\"" + param.getDisplayText( ) + "\">\n" ); //$NON-NLS-1$//$NON-NLS-2$ } } writer.write( "</div>\n" ); //$NON-NLS-1$ // create form String formId = "form_" + viewer.getId( ); //$NON-NLS-1$ writer.write( "<form id=\"" + formId + "\" method=\"post\"></form>\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "<script type=\"text/javascript\">\n" ); //$NON-NLS-1$ writer.write( "function loadViewer" + viewer.getId( ) + "(){\n" ); //$NON-NLS-1$//$NON-NLS-2$ writer .write( "var formObj = document.getElementById( \"" + formId + "\" );\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "var paramContainer = document.getElementById(\"" //$NON-NLS-1$ + paramContainerId + "\");\n" ); //$NON-NLS-1$ writer .write( "var oParams = paramContainer.getElementsByTagName('input');\n" ); //$NON-NLS-1$ writer.write( "if( oParams )\n" ); //$NON-NLS-1$ writer.write( "{\n" ); //$NON-NLS-1$ writer.write( " for( var i=0;i<oParams.length;i++ ) \n" ); //$NON-NLS-1$ writer.write( " {\n" ); //$NON-NLS-1$ writer.write( " var param = document.createElement( \"INPUT\" );\n" ); //$NON-NLS-1$ writer.write( " param.type = \"HIDDEN\";\n" ); //$NON-NLS-1$ writer.write( " param.name= oParams[i].name;\n" ); //$NON-NLS-1$ writer.write( " param.value= oParams[i].value;\n" ); //$NON-NLS-1$ writer.write( " formObj.appendChild( param );\n" ); //$NON-NLS-1$ writer.write( " }\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "formObj.action = \"" + src + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ if ( target != null ) writer.write( "formObj.target = \"" + target + "\";\n" ); //$NON-NLS-1$ //$NON-NLS-2$ writer.write( "formObj.submit( );\n" ); //$NON-NLS-1$ writer.write( "}\n" ); //$NON-NLS-1$ writer.write( "</script>\n" ); //$NON-NLS-1$ // write IFrame object writer.write( __handleIFrameDefinition( ) ); writer.write( "<script type=\"text/javascript\">" ); //$NON-NLS-1$ writer.write( "loadViewer" + viewer.getId( ) + "();" ); //$NON-NLS-1$//$NON-NLS-2$ writer.write( "</script>\n" ); //$NON-NLS-1$ }
diff --git a/war/src/launcher/java/JNLPMain.java b/war/src/launcher/java/JNLPMain.java index d25529bd2..44358a192 100644 --- a/war/src/launcher/java/JNLPMain.java +++ b/war/src/launcher/java/JNLPMain.java @@ -1,36 +1,39 @@ import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * Launches <tt>hudson.war</tt> from JNLP. * * @author Kohsuke Kawaguchi */ public class JNLPMain { public static void main(String[] args) throws Exception { // don't know if this is really necessary, but jnlp-agent benefited from this, // so I'm doing it here, too. System.setSecurityManager(null); - // launch GUI to display output - setUILookAndFeel(); - new MainDialog().setVisible(true); + boolean headlessMode = Boolean.getBoolean("hudson.master.headless"); + if (!headlessMode) { + // launch GUI to display output + setUILookAndFeel(); + new MainDialog().setVisible(true); + } Main.main(args); } /** * Sets to the platform native look and feel. * * see http://javaalmanac.com/egs/javax.swing/LookFeelNative.html */ public static void setUILookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (InstantiationException e) { } catch (ClassNotFoundException e) { } catch (UnsupportedLookAndFeelException e) { } catch (IllegalAccessException e) { } } }
true
true
public static void main(String[] args) throws Exception { // don't know if this is really necessary, but jnlp-agent benefited from this, // so I'm doing it here, too. System.setSecurityManager(null); // launch GUI to display output setUILookAndFeel(); new MainDialog().setVisible(true); Main.main(args); }
public static void main(String[] args) throws Exception { // don't know if this is really necessary, but jnlp-agent benefited from this, // so I'm doing it here, too. System.setSecurityManager(null); boolean headlessMode = Boolean.getBoolean("hudson.master.headless"); if (!headlessMode) { // launch GUI to display output setUILookAndFeel(); new MainDialog().setVisible(true); } Main.main(args); }
diff --git a/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java b/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java index 3741e0c..16b4acf 100644 --- a/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java +++ b/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java @@ -1,174 +1,174 @@ package net.loadingchunks.plugins.Leeroy.Types; import net.loadingchunks.plugins.Leeroy.Leeroy; import net.minecraft.server.MathHelper; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityCombustByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import com.topcat.npclib.NPCManager; import com.topcat.npclib.entity.HumanNPC; import com.topcat.npclib.entity.NPC; import com.topcat.npclib.nms.NpcEntityTargetEvent; import com.topcat.npclib.nms.NpcEntityTargetEvent.NpcTargetReason; /* When adding new NPC: * Add handling to LeeroyNPCHandler.java * Add handling of events in LeeroyNPCListener.java */ public class BasicNPC { public NPCManager manager; public String name; public HumanNPC npc; public Leeroy plugin; public String message1 = ""; public String message2 = ""; public String message3 = ""; public String message4 = ""; public Location original; public BasicNPC(Leeroy plugin, String name, Location l, String id, String msg1, String msg2, String msg3, String msg4, boolean isnew, String world, String hrtype, String type) { this.plugin = plugin; this.original = l; this.manager = new NPCManager(plugin); this.name = name; this.npc = (HumanNPC)manager.spawnHumanNPC(name, l); FixedMetadataValue meta = new FixedMetadataValue(this.plugin, type); FixedMetadataValue hash = new FixedMetadataValue(this.plugin, id); this.npc.getBukkitEntity().setMetadata("leeroy_type", meta); this.npc.getBukkitEntity().setMetadata("leeroy_id", hash); if(isnew) this.plugin.sql.AddNPC(id, name, hrtype, l, world); this.npc.lookAtPoint(this.getForward(l)); this.message1 = msg1; this.message2 = msg2; this.message3 = msg3; this.message4 = msg4; this.SetBroadcast(this.message4); } public void SetBroadcast(final String msg) { // Doesn't do anything in basic. } public void onTarget(Player player, NpcEntityTargetEvent event) { if(event.getNpcReason() == NpcTargetReason.NPC_RIGHTCLICKED) this.onRightClick(player, event); else if(event.getNpcReason() == NpcTargetReason.NPC_BOUNCED) this.onBounce(player, event); } public void onRightClick(Player player, NpcEntityTargetEvent event) { // Doesn't do anything in basic. } public void onBounce(Player player, EntityTargetEvent event) { // Doesn't do anything in basic. } public void onNear(Player player) { // Doesn't do anything in basic. } public void onHit(Entity assailant, EntityDamageByEntityEvent event) { if(event.getDamager() instanceof Player) this.onPlayer((Player)event.getDamager(), event); else if(event.getDamager() instanceof Monster) this.onMonster((Monster)event.getDamager(), event); } public void onPlayer(Player player, EntityDamageByEntityEvent event) { // Doesn't do anything in basic. } public void onMonster(Monster monster, EntityDamageByEntityEvent event) { // Doesn't do anything in basic. } public void broadcast(String msg) { if(msg == null || msg.isEmpty()) return; HumanNPC tmp = this.npc; for(Entity e : tmp.getBukkitEntity().getNearbyEntities(10,5,10)) { if(e instanceof Player) { String fmsg; Player p = (Player)e; fmsg = msg.replaceAll("<player>", p.getDisplayName()); fmsg = fmsg.replaceAll("<npc>", npc.getName()); p.sendMessage(fmsg); } } } public boolean IsNearby(Location e, Location l, Integer r, Integer h) { if( ((l.getX() + r) > e.getX() && (l.getX() - r) < e.getX()) && ((l.getY() + h) > e.getY() && (l.getY() - h) < e.getY()) && ((l.getZ() + r) > e.getY() && (l.getY() - r) < e.getY())) { return true; } else return false; } public Location getForward(Location l) { int direction = MathHelper.floor((double)((l.getYaw() * 4F) / 360F) + 0.5D) & 3; switch(direction) { case 0: // Direction 0 = +Z { - Location ret = new Location(l.getWorld(), l.getX(), l.getY(), (l.getZ()+1)); + Location ret = new Location(l.getWorld(), l.getX(), (l.getY()+1.62), (l.getZ()+1)); return ret; } case 1: // Direction 1 = -X { - Location ret = new Location(l.getWorld(), (l.getX()-1), l.getY(), l.getZ()); + Location ret = new Location(l.getWorld(), (l.getX()-1), (l.getY()+1.62), l.getZ()); return ret; } case 2: // Direction 2 = -Z { - Location ret = new Location(l.getWorld(), l.getX(), l.getY(), (l.getZ()-1)); + Location ret = new Location(l.getWorld(), l.getX(), (l.getY()+1.62), (l.getZ()-1)); return ret; } case 3: // Direction 3 = +Z { - Location ret = new Location(l.getWorld(), (l.getX()+1), l.getY(), l.getZ()); + Location ret = new Location(l.getWorld(), (l.getX()+1), (l.getY()+1.62), l.getZ()); return ret; } default: return l; } } }
false
true
public Location getForward(Location l) { int direction = MathHelper.floor((double)((l.getYaw() * 4F) / 360F) + 0.5D) & 3; switch(direction) { case 0: // Direction 0 = +Z { Location ret = new Location(l.getWorld(), l.getX(), l.getY(), (l.getZ()+1)); return ret; } case 1: // Direction 1 = -X { Location ret = new Location(l.getWorld(), (l.getX()-1), l.getY(), l.getZ()); return ret; } case 2: // Direction 2 = -Z { Location ret = new Location(l.getWorld(), l.getX(), l.getY(), (l.getZ()-1)); return ret; } case 3: // Direction 3 = +Z { Location ret = new Location(l.getWorld(), (l.getX()+1), l.getY(), l.getZ()); return ret; } default: return l; } }
public Location getForward(Location l) { int direction = MathHelper.floor((double)((l.getYaw() * 4F) / 360F) + 0.5D) & 3; switch(direction) { case 0: // Direction 0 = +Z { Location ret = new Location(l.getWorld(), l.getX(), (l.getY()+1.62), (l.getZ()+1)); return ret; } case 1: // Direction 1 = -X { Location ret = new Location(l.getWorld(), (l.getX()-1), (l.getY()+1.62), l.getZ()); return ret; } case 2: // Direction 2 = -Z { Location ret = new Location(l.getWorld(), l.getX(), (l.getY()+1.62), (l.getZ()-1)); return ret; } case 3: // Direction 3 = +Z { Location ret = new Location(l.getWorld(), (l.getX()+1), (l.getY()+1.62), l.getZ()); return ret; } default: return l; } }
diff --git a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java index 68ff5f91a..2fc50dd05 100644 --- a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java +++ b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java @@ -1,161 +1,164 @@ /* * Copyright 2012 JBoss, by Red Hat, 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.jboss.errai.bus.server.io; import org.jboss.errai.bus.client.api.messaging.Message; import org.jboss.errai.bus.client.api.QueueSession; import org.jboss.errai.bus.client.api.RoutingFlag; import org.jboss.errai.common.client.protocols.MessageParts; import org.jboss.errai.marshalling.client.api.json.EJArray; import org.jboss.errai.marshalling.client.api.json.EJValue; import org.jboss.errai.marshalling.client.marshallers.ErraiProtocolEnvelopeMarshaller; import org.jboss.errai.marshalling.server.DecodingSession; import org.jboss.errai.marshalling.server.JSONDecoder; import org.jboss.errai.marshalling.server.JSONStreamDecoder; import org.jboss.errai.marshalling.server.MappingContextSingleton; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static org.jboss.errai.bus.client.api.base.CommandMessage.createWithParts; import static org.jboss.errai.bus.client.api.base.CommandMessage.createWithPartsFromRawMap; /** * The <tt>MessageFactory</tt> facilitates the building of a command message using a JSON string */ public class MessageFactory { /** * Decodes a JSON string to a map (string name -> object) * * @param in - JSON string * @return map representing the string */ public static Map<String, Object> decodeToMap(String in) { //noinspection unchecked return (Map<String, Object>) JSONDecoder.decode(in); } /** * Creates the command message from the given JSON string and session. The message is constructed in * parts depending on the string * * @param session - the queue session in which the message exists * @param request - * @param json - the string representing the parts of the message * @return the message array constructed using the JSON string */ public static Message createCommandMessage(QueueSession session, HttpServletRequest request, String json) { if (json.length() == 0) return null; Map<String, Object> parts = decodeToMap(json); parts.remove(MessageParts.SessionID.name()); return from(parts, session, request); } @SuppressWarnings("unchecked") public static Message createCommandMessage(QueueSession session, String json) { if (json.length() == 0) return null; Message msg = createWithPartsFromRawMap(ErraiProtocolEnvelopeMarshaller.INSTANCE.demarshall(JSONDecoder.decode(json), new DecodingSession(MappingContextSingleton.get()))) .setResource("Session", session) .setResource("SessionID", session.getSessionId()); msg.setFlag(RoutingFlag.FromRemote); return msg; } public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } + else if (value.isNull()) { + return Collections.<Message>emptyList(); + } else { throw new RuntimeException("bad payload"); } } public static List<Message> createCommandMessage(QueueSession session, InputStream inputStream) throws IOException { EJValue value = JSONStreamDecoder.decode(inputStream); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, null)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, null)); } return messages; } else { throw new RuntimeException("bad payload"); } } public static List<Message> createCommandMessage(QueueSession session, EJValue value) { if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, null)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, null)); } return messages; } else { throw new RuntimeException("bad payload"); } } private static Map getParts(EJValue value) { return ErraiProtocolEnvelopeMarshaller.INSTANCE.demarshall(value, new DecodingSession(MappingContextSingleton.get())); } @SuppressWarnings("unchecked") private static Message from(Map parts, QueueSession session, HttpServletRequest request) { Message msg = createWithParts(parts) .setResource("Session", session) .setResource("SessionID", session.getSessionId()) .setResource(HttpServletRequest.class.getName(), request); msg.setFlag(RoutingFlag.FromRemote); return msg; } }
true
true
public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } else { throw new RuntimeException("bad payload"); } }
public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } else if (value.isNull()) { return Collections.<Message>emptyList(); } else { throw new RuntimeException("bad payload"); } }
diff --git a/search/src/java/cz/incad/Kramerius/exts/menu/main/guice/MainMenuConfiguration.java b/search/src/java/cz/incad/Kramerius/exts/menu/main/guice/MainMenuConfiguration.java index 73c0c648d..281ae6be3 100644 --- a/search/src/java/cz/incad/Kramerius/exts/menu/main/guice/MainMenuConfiguration.java +++ b/search/src/java/cz/incad/Kramerius/exts/menu/main/guice/MainMenuConfiguration.java @@ -1,102 +1,102 @@ /* * Copyright (C) 2012 Pavel Stastny * * 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 cz.incad.Kramerius.exts.menu.main.guice; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import cz.incad.Kramerius.exts.menu.main.MainMenu; import cz.incad.Kramerius.exts.menu.main.MainMenuPart; import cz.incad.Kramerius.exts.menu.main.impl.MainMenuImpl; import cz.incad.Kramerius.exts.menu.main.impl.adm.AdminMenuItem; import cz.incad.Kramerius.exts.menu.main.impl.adm.AdminMenuPartImpl; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.Convert; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.CriteriumsEditor; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.Enumerator; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.GlobalRightsAdministration; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.Import; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ImportMonographs; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ImportPeriodicals; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.IndexerAdministration; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.MetadataEditor; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ParametrizedConvert; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ParametrizedImport; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ParametrizedK4Replication; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ProcessesDialog; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.ReplicationRights; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.RolesEditor; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.UsersAdministration; import cz.incad.Kramerius.exts.menu.main.impl.adm.items.VirtualCollectionsAdministration; import cz.incad.Kramerius.exts.menu.main.impl.pub.PublicMainMenuItem; import cz.incad.Kramerius.exts.menu.main.impl.pub.PublicMenuPartImpl; import cz.incad.Kramerius.exts.menu.main.impl.pub.items.ChangePassword; import cz.incad.Kramerius.exts.menu.main.impl.pub.items.SaveProfile; import cz.incad.Kramerius.exts.menu.main.impl.pub.items.ShowProfile; /** * Menu configuration bean * @author pavels */ public class MainMenuConfiguration extends AbstractModule { @Override protected void configure() { // casti menu Multibinder<MainMenuPart> parts = Multibinder.newSetBinder(binder(), MainMenuPart.class); parts.addBinding().to(PublicMenuPartImpl.class); parts.addBinding().to(AdminMenuPartImpl.class); // polozky public menu Multibinder<PublicMainMenuItem> publicItems = Multibinder.newSetBinder(binder(), PublicMainMenuItem.class); publicItems.addBinding().to(ShowProfile.class); publicItems.addBinding().to(SaveProfile.class); publicItems.addBinding().to(ChangePassword.class); // polozky admin menu Multibinder<AdminMenuItem> adminItems = Multibinder.newSetBinder(binder(), AdminMenuItem.class); adminItems.addBinding().to(ProcessesDialog.class); adminItems.addBinding().to(ImportMonographs.class); adminItems.addBinding().to(ImportPeriodicals.class); adminItems.addBinding().to(IndexerAdministration.class); adminItems.addBinding().to(GlobalRightsAdministration.class); adminItems.addBinding().to(CriteriumsEditor.class); adminItems.addBinding().to(Enumerator.class); adminItems.addBinding().to(ReplicationRights.class); adminItems.addBinding().to(Convert.class); adminItems.addBinding().to(Import.class); adminItems.addBinding().to(MetadataEditor.class); adminItems.addBinding().to(RolesEditor.class); adminItems.addBinding().to(UsersAdministration.class); adminItems.addBinding().to(VirtualCollectionsAdministration.class); // pridani parametrizovanych procesu adminItems.addBinding().to(ParametrizedImport.class); - adminItems.addBinding().to(ParametrizedConvert.class); + //adminItems.addBinding().to(ParametrizedConvert.class); adminItems.addBinding().to(ParametrizedK4Replication.class); // menu bind(MainMenu.class).to(MainMenuImpl.class); } }
true
true
protected void configure() { // casti menu Multibinder<MainMenuPart> parts = Multibinder.newSetBinder(binder(), MainMenuPart.class); parts.addBinding().to(PublicMenuPartImpl.class); parts.addBinding().to(AdminMenuPartImpl.class); // polozky public menu Multibinder<PublicMainMenuItem> publicItems = Multibinder.newSetBinder(binder(), PublicMainMenuItem.class); publicItems.addBinding().to(ShowProfile.class); publicItems.addBinding().to(SaveProfile.class); publicItems.addBinding().to(ChangePassword.class); // polozky admin menu Multibinder<AdminMenuItem> adminItems = Multibinder.newSetBinder(binder(), AdminMenuItem.class); adminItems.addBinding().to(ProcessesDialog.class); adminItems.addBinding().to(ImportMonographs.class); adminItems.addBinding().to(ImportPeriodicals.class); adminItems.addBinding().to(IndexerAdministration.class); adminItems.addBinding().to(GlobalRightsAdministration.class); adminItems.addBinding().to(CriteriumsEditor.class); adminItems.addBinding().to(Enumerator.class); adminItems.addBinding().to(ReplicationRights.class); adminItems.addBinding().to(Convert.class); adminItems.addBinding().to(Import.class); adminItems.addBinding().to(MetadataEditor.class); adminItems.addBinding().to(RolesEditor.class); adminItems.addBinding().to(UsersAdministration.class); adminItems.addBinding().to(VirtualCollectionsAdministration.class); // pridani parametrizovanych procesu adminItems.addBinding().to(ParametrizedImport.class); adminItems.addBinding().to(ParametrizedConvert.class); adminItems.addBinding().to(ParametrizedK4Replication.class); // menu bind(MainMenu.class).to(MainMenuImpl.class); }
protected void configure() { // casti menu Multibinder<MainMenuPart> parts = Multibinder.newSetBinder(binder(), MainMenuPart.class); parts.addBinding().to(PublicMenuPartImpl.class); parts.addBinding().to(AdminMenuPartImpl.class); // polozky public menu Multibinder<PublicMainMenuItem> publicItems = Multibinder.newSetBinder(binder(), PublicMainMenuItem.class); publicItems.addBinding().to(ShowProfile.class); publicItems.addBinding().to(SaveProfile.class); publicItems.addBinding().to(ChangePassword.class); // polozky admin menu Multibinder<AdminMenuItem> adminItems = Multibinder.newSetBinder(binder(), AdminMenuItem.class); adminItems.addBinding().to(ProcessesDialog.class); adminItems.addBinding().to(ImportMonographs.class); adminItems.addBinding().to(ImportPeriodicals.class); adminItems.addBinding().to(IndexerAdministration.class); adminItems.addBinding().to(GlobalRightsAdministration.class); adminItems.addBinding().to(CriteriumsEditor.class); adminItems.addBinding().to(Enumerator.class); adminItems.addBinding().to(ReplicationRights.class); adminItems.addBinding().to(Convert.class); adminItems.addBinding().to(Import.class); adminItems.addBinding().to(MetadataEditor.class); adminItems.addBinding().to(RolesEditor.class); adminItems.addBinding().to(UsersAdministration.class); adminItems.addBinding().to(VirtualCollectionsAdministration.class); // pridani parametrizovanych procesu adminItems.addBinding().to(ParametrizedImport.class); //adminItems.addBinding().to(ParametrizedConvert.class); adminItems.addBinding().to(ParametrizedK4Replication.class); // menu bind(MainMenu.class).to(MainMenuImpl.class); }
diff --git a/src/org/geometerplus/fbreader/network/BookReference.java b/src/org/geometerplus/fbreader/network/BookReference.java index d403e086..84954c14 100644 --- a/src/org/geometerplus/fbreader/network/BookReference.java +++ b/src/org/geometerplus/fbreader/network/BookReference.java @@ -1,172 +1,172 @@ /* * Copyright (C) 2010-2011 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.network; import java.io.File; import java.net.URI; import org.geometerplus.fbreader.Paths; public class BookReference { public interface Type { int UNKNOWN = 0; // Unknown reference type int DOWNLOAD_FULL = 1; // reference for download full version of the book int DOWNLOAD_FULL_CONDITIONAL = 2; // reference for download full version of the book, useful only when book is bought int DOWNLOAD_DEMO = 3; // reference for downloading demo version of the book int DOWNLOAD_FULL_OR_DEMO = 4; // reference for downloading unknown version of the book int BUY = 5; // reference for buying the book (useful only when authentication is supported) int BUY_IN_BROWSER = 6; // reference to the site page, when it is possible to buy the book } // resolvedReferenceType -- reference type without any ambiguity (for example, DOWNLOAD_FULL_OR_DEMO is ambiguous) public interface Format { int NONE = 0; int MOBIPOCKET = 1; int FB2_ZIP = 2; int EPUB = 3; } public final String URL; public final int BookFormat; public final int ReferenceType; public BookReference(String url, int format, int type) { URL = url; BookFormat = format; ReferenceType = type; } // returns clean URL without any account/user-specific parts public String cleanURL() { return URL; } private static final String TOESCAPE = "<>:\"|?*\\"; public static String makeBookFileName(String url, int format, int resolvedReferenceType) { URI uri; try { uri = new URI(url); - } catch (java.net.URISyntaxException ex) { + } catch (Throwable ex) { return null; } String host = uri.getHost(); StringBuilder path = new StringBuilder(host); if (host.startsWith("www.")) { path.delete(0, 4); } path.insert(0, File.separator); if (resolvedReferenceType == Type.DOWNLOAD_DEMO) { path.insert(0, "Demos"); path.insert(0, File.separator); } path.insert(0, Paths.BooksDirectoryOption().getValue()); int index = path.length(); path.append(uri.getPath()); int nameIndex = index; while (index < path.length()) { char ch = path.charAt(index); if (TOESCAPE.indexOf(ch) != -1) { path.setCharAt(index, '_'); } if (ch == '/') { if (index + 1 == path.length()) { path.deleteCharAt(index); } else { path.setCharAt(index, File.separatorChar); nameIndex = index + 1; } } ++index; } String ext = null; switch (format) { case Format.EPUB: ext = ".epub"; break; case Format.MOBIPOCKET: ext = ".mobi"; break; case Format.FB2_ZIP: ext = ".fb2.zip"; break; } if (ext == null) { int j = path.indexOf(".", nameIndex); // using not lastIndexOf to preserve extensions like `.fb2.zip` if (j != -1) { ext = path.substring(j); path.delete(j, path.length()); } else { return null; } } else if (path.length() > ext.length() && path.substring(path.length() - ext.length()).equals(ext)) { path.delete(path.length() - ext.length(), path.length()); } String query = uri.getQuery(); if (query != null) { index = 0; while (index < query.length()) { int j = query.indexOf("&", index); if (j == -1) { j = query.length(); } String param = query.substring(index, j); if (!param.startsWith("username=") && !param.startsWith("password=") && !param.endsWith("=")) { int k = path.length(); path.append("_").append(param); while (k < path.length()) { char ch = path.charAt(k); if (TOESCAPE.indexOf(ch) != -1 || ch == '/') { path.setCharAt(k, '_'); } ++k; } } index = j + 1; } } return path.append(ext).toString(); } public final String makeBookFileName(int resolvedReferenceType) { return makeBookFileName(cleanURL(), BookFormat, resolvedReferenceType); } public final String localCopyFileName(int resolvedReferenceType) { String fileName = makeBookFileName(resolvedReferenceType); if (fileName != null && new File(fileName).exists()) { return fileName; } return null; } public String toString() { return "BookReference[type=" + ReferenceType + ";format=" + BookFormat + ";URL=" + URL + "]"; } }
true
true
public static String makeBookFileName(String url, int format, int resolvedReferenceType) { URI uri; try { uri = new URI(url); } catch (java.net.URISyntaxException ex) { return null; } String host = uri.getHost(); StringBuilder path = new StringBuilder(host); if (host.startsWith("www.")) { path.delete(0, 4); } path.insert(0, File.separator); if (resolvedReferenceType == Type.DOWNLOAD_DEMO) { path.insert(0, "Demos"); path.insert(0, File.separator); } path.insert(0, Paths.BooksDirectoryOption().getValue()); int index = path.length(); path.append(uri.getPath()); int nameIndex = index; while (index < path.length()) { char ch = path.charAt(index); if (TOESCAPE.indexOf(ch) != -1) { path.setCharAt(index, '_'); } if (ch == '/') { if (index + 1 == path.length()) { path.deleteCharAt(index); } else { path.setCharAt(index, File.separatorChar); nameIndex = index + 1; } } ++index; } String ext = null; switch (format) { case Format.EPUB: ext = ".epub"; break; case Format.MOBIPOCKET: ext = ".mobi"; break; case Format.FB2_ZIP: ext = ".fb2.zip"; break; } if (ext == null) { int j = path.indexOf(".", nameIndex); // using not lastIndexOf to preserve extensions like `.fb2.zip` if (j != -1) { ext = path.substring(j); path.delete(j, path.length()); } else { return null; } } else if (path.length() > ext.length() && path.substring(path.length() - ext.length()).equals(ext)) { path.delete(path.length() - ext.length(), path.length()); } String query = uri.getQuery(); if (query != null) { index = 0; while (index < query.length()) { int j = query.indexOf("&", index); if (j == -1) { j = query.length(); } String param = query.substring(index, j); if (!param.startsWith("username=") && !param.startsWith("password=") && !param.endsWith("=")) { int k = path.length(); path.append("_").append(param); while (k < path.length()) { char ch = path.charAt(k); if (TOESCAPE.indexOf(ch) != -1 || ch == '/') { path.setCharAt(k, '_'); } ++k; } } index = j + 1; } } return path.append(ext).toString(); }
public static String makeBookFileName(String url, int format, int resolvedReferenceType) { URI uri; try { uri = new URI(url); } catch (Throwable ex) { return null; } String host = uri.getHost(); StringBuilder path = new StringBuilder(host); if (host.startsWith("www.")) { path.delete(0, 4); } path.insert(0, File.separator); if (resolvedReferenceType == Type.DOWNLOAD_DEMO) { path.insert(0, "Demos"); path.insert(0, File.separator); } path.insert(0, Paths.BooksDirectoryOption().getValue()); int index = path.length(); path.append(uri.getPath()); int nameIndex = index; while (index < path.length()) { char ch = path.charAt(index); if (TOESCAPE.indexOf(ch) != -1) { path.setCharAt(index, '_'); } if (ch == '/') { if (index + 1 == path.length()) { path.deleteCharAt(index); } else { path.setCharAt(index, File.separatorChar); nameIndex = index + 1; } } ++index; } String ext = null; switch (format) { case Format.EPUB: ext = ".epub"; break; case Format.MOBIPOCKET: ext = ".mobi"; break; case Format.FB2_ZIP: ext = ".fb2.zip"; break; } if (ext == null) { int j = path.indexOf(".", nameIndex); // using not lastIndexOf to preserve extensions like `.fb2.zip` if (j != -1) { ext = path.substring(j); path.delete(j, path.length()); } else { return null; } } else if (path.length() > ext.length() && path.substring(path.length() - ext.length()).equals(ext)) { path.delete(path.length() - ext.length(), path.length()); } String query = uri.getQuery(); if (query != null) { index = 0; while (index < query.length()) { int j = query.indexOf("&", index); if (j == -1) { j = query.length(); } String param = query.substring(index, j); if (!param.startsWith("username=") && !param.startsWith("password=") && !param.endsWith("=")) { int k = path.length(); path.append("_").append(param); while (k < path.length()) { char ch = path.charAt(k); if (TOESCAPE.indexOf(ch) != -1 || ch == '/') { path.setCharAt(k, '_'); } ++k; } } index = j + 1; } } return path.append(ext).toString(); }
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java index d58c7a1b..8be3c5c8 100644 --- a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java +++ b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java @@ -1,1010 +1,1010 @@ /***************************************************************************** * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.vmware.bdd.cli.commands; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.conf.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.hadoop.impala.hive.HiveCommands; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import com.vmware.bdd.apitypes.ClusterCreate; import com.vmware.bdd.apitypes.ClusterRead; import com.vmware.bdd.apitypes.ClusterType; import com.vmware.bdd.apitypes.DistroRead; import com.vmware.bdd.apitypes.NetworkRead; import com.vmware.bdd.apitypes.NodeGroupCreate; import com.vmware.bdd.apitypes.NodeGroupRead; import com.vmware.bdd.apitypes.NodeRead; import com.vmware.bdd.apitypes.TopologyType; import com.vmware.bdd.cli.rest.CliRestException; import com.vmware.bdd.cli.rest.ClusterRestClient; import com.vmware.bdd.cli.rest.DistroRestClient; import com.vmware.bdd.cli.rest.NetworkRestClient; import com.vmware.bdd.spectypes.HadoopRole; import com.vmware.bdd.utils.AppConfigValidationUtils; import com.vmware.bdd.utils.AppConfigValidationUtils.ValidationType; import com.vmware.bdd.utils.ValidateResult; @Component public class ClusterCommands implements CommandMarker { @Autowired private DistroRestClient distroRestClient; @Autowired private NetworkRestClient networkRestClient; @Autowired private ClusterRestClient restClient; @Autowired private Configuration hadoopConfiguration; @Autowired private HiveCommands hiveCommands; private String hiveServerUrl; private String targetClusterName; @CliAvailabilityIndicator({ "cluster help" }) public boolean isCommandAvailable() { return true; } @CliCommand(value = "cluster create", help = "Create a hadoop cluster") public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } else if (name.indexOf(" ") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_BLANK_SPACE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } else if (specFilePath == null) { // create Hadoop (HDFS + MapReduce) cluster as default clusterCreate.setType(ClusterType.HDFS_MAPRED); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(TopologyType.NONE); } try { if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } else { String defaultDistroName = clusterCreate.getDefaultDistroName(distroRestClient.getAll()); if (CommandsUtils.isBlank(defaultDistroName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM__NO_DEFAULT_DISTRO); return; } else { clusterCreate.setDistro(defaultDistroName); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro()); clusterCreate.setVendor(distroRead.getVendor()); clusterCreate.setVersion(distroRead.getVersion()); if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> failedMsgList = new ArrayList<String>(); List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { List<String> distroRoles = findDistroRoles(clusterCreate); clusterCreate.validateClusterCreate(failedMsgList, warningMsgList, distroRoles); } // give a warning message if both type and specFilePath are specified if (type != null && specFilePath != null) { warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT); } if (!failedMsgList.isEmpty()) { showFailedMsg(clusterCreate.getName(), failedMsgList); return; } // rest invocation try { if (!CommandsUtils.showWarningMsg(clusterCreate.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, warningMsgList, alwaysAnswerYes)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(detail); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name, detail); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } - @CliCommand(value = "cluster export --spec", help = "Export cluster specification") + @CliCommand(value = "cluster export", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { ClusterRead cluster = restClient.get(name, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name + " does not exsit."); return; } //disallow scale out zookeeper node group. List<NodeGroupRead> ngs = cluster.getNodeGroups(); boolean found = false; for (NodeGroupRead ng : ngs) { if (ng.getName().equals(nodeGroup)) { found = true; if (ng.getRoles() != null && ng.getRoles().contains(HadoopRole.ZOOKEEPER_ROLE.toString())) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.ZOOKEEPER_NOT_RESIZE); return; } break; } } if (!found) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup + " does not exist."); return; } restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,"Invalid instance number:" + activeComputeNodeNum + " ."); return; } ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster unlimit", help = "Set number of instances powered off in a node group") public void unlimitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName) { try { int activeComputeNodeNum = -1; ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; boolean noCluster = false; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveServerUrl != null && hiveServerUrl.length() > 0) { System.out.println("Hive server info: " + hiveServerUrl); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(false); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } else { noCluster = true; } } else { cluster = restClient.get(name, false); } if (cluster == null) { if(noCluster) { System.out.println("There is no available cluster for targeting."); } else { System.out.println("Failed to target cluster: The cluster " + name + " not found"); } setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } else { targetClusterName = cluster.getName(); boolean hasHDFS = false; boolean hasHiveServer = false; for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); hasHDFS = true; } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServerAddress(hiveServerIP); hasHiveServer = true; } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); hasHDFS = true; } if(!hasHDFS){ setFsURL(""); } if(!hasHiveServer){ this.setHiveServerUrl(""); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServerAddress(String hiveServerAddress) { try { hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } private void setHiveServerUrl(String hiveServerUrl) { this.hiveServerUrl = hiveServerUrl; } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name, false); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!CommandsUtils.showWarningMsg(clusterConfig.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG, warningMsgList, alwaysAnswerYes)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("cluster name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("cluster name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GROUP_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_NAME, Arrays.asList("getName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); failedMsg.append("."); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } /* * Validate a configuration of the cluster at first. Validate configurations of all of node groups then. * And merge the failed info which have been producted by validation between cluster level and node group * level. */ private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); validateResult.setNoExistFileNames(vr.getNoExistFileNames()); } } List<String> failureNames = new LinkedList<String>(); Map<String,List<String>> noExistingFileNamesMap = new HashMap<String,List<String>>(); failureNames.addAll(validateResult.getFailureNames()); noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames()); // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); // merge failed names between cluster level and node group level. for (String failureName : vr.getFailureNames()) { if (!failureNames.contains(failureName)) { failureNames.add(failureName); } } // merge no existing file names between cluster level and node group level for (Entry<String, List<String>> noExistingFileNames : vr.getNoExistFileNames().entrySet()) { String configType = noExistingFileNames.getKey(); if (noExistingFileNamesMap.containsKey(configType)) { List<String> noExistingFilesTemp = noExistingFileNames.getValue(); List<String> noExistingFiles = noExistingFileNamesMap.get(configType); for (String fileName : noExistingFilesTemp) { if (!noExistingFiles.contains(fileName)) { noExistingFiles.add(fileName); } } noExistingFileNamesMap.put(configType, noExistingFiles); } else { noExistingFileNamesMap.put(configType, noExistingFileNames.getValue()); } } } } } validateResult.setFailureNames(failureNames); validateResult.setNoExistFileNames(noExistingFileNamesMap); return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if(whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); } }else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); String failureNameWarningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); warningMsgList.add(failureNameWarningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING + Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); if (warningList != null) { warningList.add(warningMsg); } } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private String getValidateWarningMsg(Map<String,List<String>> noExistingFilesMap) { StringBuilder warningMsgBuff = new StringBuilder(); if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) { warningMsgBuff.append("Warning: "); for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap.entrySet()) { List<String> noExistingFileNames = noExistingFilesEntry.getValue(); for (String noExistingFileName : noExistingFileNames) { warningMsgBuff.append(noExistingFileName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (noExistingFileNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append("not existing in "); warningMsgBuff.append(noExistingFilesEntry.getKey()+ " scope , "); } warningMsgBuff.replace(warningMsgBuff.length() - 2, warningMsgBuff.length(),". "); warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); } return warningMsgBuff.toString(); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
true
true
public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } else if (name.indexOf(" ") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_BLANK_SPACE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } else if (specFilePath == null) { // create Hadoop (HDFS + MapReduce) cluster as default clusterCreate.setType(ClusterType.HDFS_MAPRED); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(TopologyType.NONE); } try { if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } else { String defaultDistroName = clusterCreate.getDefaultDistroName(distroRestClient.getAll()); if (CommandsUtils.isBlank(defaultDistroName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM__NO_DEFAULT_DISTRO); return; } else { clusterCreate.setDistro(defaultDistroName); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro()); clusterCreate.setVendor(distroRead.getVendor()); clusterCreate.setVersion(distroRead.getVersion()); if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> failedMsgList = new ArrayList<String>(); List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { List<String> distroRoles = findDistroRoles(clusterCreate); clusterCreate.validateClusterCreate(failedMsgList, warningMsgList, distroRoles); } // give a warning message if both type and specFilePath are specified if (type != null && specFilePath != null) { warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT); } if (!failedMsgList.isEmpty()) { showFailedMsg(clusterCreate.getName(), failedMsgList); return; } // rest invocation try { if (!CommandsUtils.showWarningMsg(clusterCreate.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, warningMsgList, alwaysAnswerYes)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(detail); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name, detail); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster export --spec", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { ClusterRead cluster = restClient.get(name, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name + " does not exsit."); return; } //disallow scale out zookeeper node group. List<NodeGroupRead> ngs = cluster.getNodeGroups(); boolean found = false; for (NodeGroupRead ng : ngs) { if (ng.getName().equals(nodeGroup)) { found = true; if (ng.getRoles() != null && ng.getRoles().contains(HadoopRole.ZOOKEEPER_ROLE.toString())) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.ZOOKEEPER_NOT_RESIZE); return; } break; } } if (!found) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup + " does not exist."); return; } restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,"Invalid instance number:" + activeComputeNodeNum + " ."); return; } ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster unlimit", help = "Set number of instances powered off in a node group") public void unlimitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName) { try { int activeComputeNodeNum = -1; ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; boolean noCluster = false; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveServerUrl != null && hiveServerUrl.length() > 0) { System.out.println("Hive server info: " + hiveServerUrl); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(false); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } else { noCluster = true; } } else { cluster = restClient.get(name, false); } if (cluster == null) { if(noCluster) { System.out.println("There is no available cluster for targeting."); } else { System.out.println("Failed to target cluster: The cluster " + name + " not found"); } setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } else { targetClusterName = cluster.getName(); boolean hasHDFS = false; boolean hasHiveServer = false; for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); hasHDFS = true; } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServerAddress(hiveServerIP); hasHiveServer = true; } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); hasHDFS = true; } if(!hasHDFS){ setFsURL(""); } if(!hasHiveServer){ this.setHiveServerUrl(""); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServerAddress(String hiveServerAddress) { try { hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } private void setHiveServerUrl(String hiveServerUrl) { this.hiveServerUrl = hiveServerUrl; } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name, false); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!CommandsUtils.showWarningMsg(clusterConfig.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG, warningMsgList, alwaysAnswerYes)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("cluster name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("cluster name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GROUP_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_NAME, Arrays.asList("getName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); failedMsg.append("."); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } /* * Validate a configuration of the cluster at first. Validate configurations of all of node groups then. * And merge the failed info which have been producted by validation between cluster level and node group * level. */ private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); validateResult.setNoExistFileNames(vr.getNoExistFileNames()); } } List<String> failureNames = new LinkedList<String>(); Map<String,List<String>> noExistingFileNamesMap = new HashMap<String,List<String>>(); failureNames.addAll(validateResult.getFailureNames()); noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames()); // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); // merge failed names between cluster level and node group level. for (String failureName : vr.getFailureNames()) { if (!failureNames.contains(failureName)) { failureNames.add(failureName); } } // merge no existing file names between cluster level and node group level for (Entry<String, List<String>> noExistingFileNames : vr.getNoExistFileNames().entrySet()) { String configType = noExistingFileNames.getKey(); if (noExistingFileNamesMap.containsKey(configType)) { List<String> noExistingFilesTemp = noExistingFileNames.getValue(); List<String> noExistingFiles = noExistingFileNamesMap.get(configType); for (String fileName : noExistingFilesTemp) { if (!noExistingFiles.contains(fileName)) { noExistingFiles.add(fileName); } } noExistingFileNamesMap.put(configType, noExistingFiles); } else { noExistingFileNamesMap.put(configType, noExistingFileNames.getValue()); } } } } } validateResult.setFailureNames(failureNames); validateResult.setNoExistFileNames(noExistingFileNamesMap); return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if(whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); } }else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); String failureNameWarningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); warningMsgList.add(failureNameWarningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING + Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); if (warningList != null) { warningList.add(warningMsg); } } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private String getValidateWarningMsg(Map<String,List<String>> noExistingFilesMap) { StringBuilder warningMsgBuff = new StringBuilder(); if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) { warningMsgBuff.append("Warning: "); for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap.entrySet()) { List<String> noExistingFileNames = noExistingFilesEntry.getValue(); for (String noExistingFileName : noExistingFileNames) { warningMsgBuff.append(noExistingFileName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (noExistingFileNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append("not existing in "); warningMsgBuff.append(noExistingFilesEntry.getKey()+ " scope , "); } warningMsgBuff.replace(warningMsgBuff.length() - 2, warningMsgBuff.length(),". "); warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); } return warningMsgBuff.toString(); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
public void createCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type, @CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro, @CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath, @CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames, @CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames, @CliOption(key = { "networkName" }, mandatory = false, help = "Network Name") final String networkName, @CliOption(key = { "topology" }, mandatory = false, help = "Please specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology, @CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } else if (name.indexOf(" ") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_BLANK_SPACE); return; } //process resume if (resume) { resumeCreateCluster(name); return; } // build ClusterCreate object ClusterCreate clusterCreate = new ClusterCreate(); clusterCreate.setName(name); if (type != null) { ClusterType clusterType = ClusterType.getByDescription(type); if (clusterType == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type); return; } clusterCreate.setType(clusterType); } else if (specFilePath == null) { // create Hadoop (HDFS + MapReduce) cluster as default clusterCreate.setType(ClusterType.HDFS_MAPRED); } if (topology != null) { try { clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology)); } catch (IllegalArgumentException ex) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "topologyType=" + topology); return; } } else { clusterCreate.setTopologyPolicy(TopologyType.NONE); } try { if (distro != null) { List<String> distroNames = getDistroNames(); if (validName(distro, distroNames)) { clusterCreate.setDistro(distro); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + distroNames); return; } } else { String defaultDistroName = clusterCreate.getDefaultDistroName(distroRestClient.getAll()); if (CommandsUtils.isBlank(defaultDistroName)) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM__NO_DEFAULT_DISTRO); return; } else { clusterCreate.setDistro(defaultDistroName); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro()); clusterCreate.setVendor(distroRead.getVendor()); clusterCreate.setVersion(distroRead.getVersion()); if (rpNames != null) { List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames); if (rpNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setRpNames(rpNamesList); } } if (dsNames != null) { List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames); if (dsNamesList.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK); return; } else { clusterCreate.setDsNames(dsNamesList); } } List<String> failedMsgList = new ArrayList<String>(); List<String> warningMsgList = new ArrayList<String>(); List<String> networkNames = null; try { if (specFilePath != null) { ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS()); clusterCreate.setNodeGroups(clusterSpec.getNodeGroups()); clusterCreate.setConfiguration(clusterSpec.getConfiguration()); validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList); if (!validateHAInfo(clusterCreate.getNodeGroups())){ CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath); return; } } networkNames = getNetworkNames(); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } if (networkNames.isEmpty()) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_EXISTED); return; } else { if (networkName != null) { if (validName(networkName, networkNames)) { clusterCreate.setNetworkName(networkName); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + networkNames); return; } } else { if (networkNames.size() == 1) { clusterCreate.setNetworkName(networkNames.get(0)); } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED); return; } } } // Validate that the specified file is correct json format and proper value. if (specFilePath != null) { List<String> distroRoles = findDistroRoles(clusterCreate); clusterCreate.validateClusterCreate(failedMsgList, warningMsgList, distroRoles); } // give a warning message if both type and specFilePath are specified if (type != null && specFilePath != null) { warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT); } if (!failedMsgList.isEmpty()) { showFailedMsg(clusterCreate.getName(), failedMsgList); return; } // rest invocation try { if (!CommandsUtils.showWarningMsg(clusterCreate.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE, warningMsgList, alwaysAnswerYes)) { return; } restClient.create(clusterCreate); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CREAT); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> findDistroRoles(ClusterCreate clusterCreate) { DistroRead distroRead = null; distroRead = distroRestClient .get(clusterCreate.getDistro() != null ? clusterCreate .getDistro() : Constants.DEFAULT_DISTRO); if (distroRead != null) { return distroRead.getRoles(); } else { return null; } } @CliCommand(value = "cluster list", help = "Get cluster information") public void getCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { // rest invocation try { if (name == null) { ClusterRead[] clusters = restClient.getAll(detail); if (clusters != null) { prettyOutputClustersInfo(clusters, detail); } } else { ClusterRead cluster = restClient.get(name, detail); if (cluster != null) { prettyOutputClusterInfo(cluster, detail); } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster export", help = "Export cluster specification") public void exportClusterSpec( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "output" }, mandatory = false, help = "The output file name") final String fileName) { // rest invocation try { ClusterCreate cluster = restClient.getSpec(name); if (cluster != null) { CommandsUtils.prettyJsonOutput(cluster, fileName); } } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster delete", help = "Delete a cluster") public void deleteCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_DELETE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster start", help = "Start a cluster") public void startCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings .put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_START); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster stop", help = "Stop a cluster") public void stopCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP); //rest invocation try { restClient.actionOps(clusterName, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_RESULT_STOP); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName, Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "cluster resize", help = "Resize a cluster") public void resizeCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup, @CliOption(key = { "instanceNum" }, mandatory = true, help = "The resized number of instances. It should be larger that existing one") final int instanceNum) { if (instanceNum > 1) { try { ClusterRead cluster = restClient.get(name, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name + " does not exsit."); return; } //disallow scale out zookeeper node group. List<NodeGroupRead> ngs = cluster.getNodeGroups(); boolean found = false; for (NodeGroupRead ng : ngs) { if (ng.getName().equals(nodeGroup)) { found = true; if (ng.getRoles() != null && ng.getRoles().contains(HadoopRole.ZOOKEEPER_ROLE.toString())) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.ZOOKEEPER_NOT_RESIZE); return; } break; } } if (!found) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup + " does not exist."); return; } restClient.resize(name, nodeGroup, instanceNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESIZE); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } else { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESIZE, Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " instanceNum=" + instanceNum); } } @CliCommand(value = "cluster limit", help = "Set number of instances powered on in a node group") public void limitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName, @CliOption(key = { "activeComputeNodeNum" }, mandatory = true, help = "The number of instances powered on") final int activeComputeNodeNum) { try { // The active compute node number must be a integer and cannot be less than zero. if (activeComputeNodeNum < 0) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,"Invalid instance number:" + activeComputeNodeNum + " ."); return; } ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster unlimit", help = "Set number of instances powered off in a node group") public void unlimitCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName, @CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name") final String nodeGroupName) { try { int activeComputeNodeNum = -1; ClusterRead cluster = restClient.get(clusterName, false); if (cluster == null) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT, null, null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED, "cluster " + clusterName + " is not exsit !"); return; } if(!cluster.validateLimit(nodeGroupName)) { return; } restClient.limitCluster(clusterName, nodeGroupName, activeComputeNodeNum); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OP_ADJUSTMENT,null, Constants.OUTPUT_OP_ADJUSTMENT_SUCCEEDED); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OP_ADJUSTMENT,null,null, Constants.OUTPUT_OP_ADJUSTMENT_FAILED ,e.getMessage()); } } @CliCommand(value = "cluster target", help = "Set or query target cluster to run commands") public void targetCluster( @CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name, @CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) { ClusterRead cluster = null; boolean noCluster = false; try { if (info) { if (name != null) { System.out.println("Warning: can't specify option --name and --info at the same time"); return; } String fsUrl = hadoopConfiguration.get("fs.default.name"); String jtUrl = hadoopConfiguration.get("mapred.job.tracker"); if ((fsUrl == null || fsUrl.length() == 0) && (jtUrl == null || jtUrl.length() == 0)) { System.out.println("There is no targeted cluster. Please use \"cluster target --name\" to target first"); return; } if(targetClusterName != null && targetClusterName.length() > 0){ System.out.println("Cluster : " + targetClusterName); } if (fsUrl != null && fsUrl.length() > 0) { System.out.println("HDFS url : " + fsUrl); } if (jtUrl != null && jtUrl.length() > 0) { System.out.println("Job Tracker url : " + jtUrl); } if (hiveServerUrl != null && hiveServerUrl.length() > 0) { System.out.println("Hive server info: " + hiveServerUrl); } } else { if (name == null) { ClusterRead[] clusters = restClient.getAll(false); if (clusters != null && clusters.length > 0) { cluster = clusters[0]; } else { noCluster = true; } } else { cluster = restClient.get(name, false); } if (cluster == null) { if(noCluster) { System.out.println("There is no available cluster for targeting."); } else { System.out.println("Failed to target cluster: The cluster " + name + " not found"); } setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } else { targetClusterName = cluster.getName(); boolean hasHDFS = false; boolean hasHiveServer = false; for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) { for (String role : nodeGroup.getRoles()) { if (role.equals("hadoop_namenode")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String nameNodeIP = nodes.get(0).getIp(); setNameNode(nameNodeIP); hasHDFS = true; } else { throw new CliRestException("no name node available"); } } if (role.equals("hadoop_jobtracker")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String jobTrackerIP = nodes.get(0).getIp(); setJobTracker(jobTrackerIP); } else { throw new CliRestException("no job tracker available"); } } if (role.equals("hive_server")) { List<NodeRead> nodes = nodeGroup.getInstances(); if (nodes != null && nodes.size() > 0) { String hiveServerIP = nodes.get(0).getIp(); setHiveServerAddress(hiveServerIP); hasHiveServer = true; } else { throw new CliRestException("no hive server available"); } } } } if (cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { setFsURL(cluster.getExternalHDFS()); hasHDFS = true; } if(!hasHDFS){ setFsURL(""); } if(!hasHiveServer){ this.setHiveServerUrl(""); } } } } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); setFsURL(""); setJobTrackerURL(""); this.setHiveServerUrl(""); } } private void setNameNode(String nameNodeAddress) { String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020"; setFsURL(hdfsUrl); } private void setFsURL(String fsURL) { hadoopConfiguration.set("fs.default.name", fsURL); } private void setJobTracker(String jobTrackerAddress) { String jobTrackerUrl = jobTrackerAddress + ":8021"; setJobTrackerURL(jobTrackerUrl); } private void setJobTrackerURL(String jobTrackerUrl){ hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl); } private void setHiveServerAddress(String hiveServerAddress) { try { hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null); } catch (Exception e) { throw new CliRestException("faild to set hive server address"); } } private void setHiveServerUrl(String hiveServerUrl) { this.hiveServerUrl = hiveServerUrl; } @CliCommand(value = "cluster config", help = "Config an existing cluster") public void configCluster( @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name, @CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath, @CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation, @CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) { //validate the name if (name.indexOf("-") != -1) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE); return; } try { ClusterRead clusterRead = restClient.get(name, false); // build ClusterCreate object ClusterCreate clusterConfig = new ClusterCreate(); clusterConfig.setName(clusterRead.getName()); ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class, CommandsUtils.dataFromFile(specFilePath)); clusterConfig.setNodeGroups(clusterSpec.getNodeGroups()); clusterConfig.setConfiguration(clusterSpec.getConfiguration()); clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS()); List<String> warningMsgList = new ArrayList<String>(); validateConfiguration(clusterConfig, skipConfigValidation, warningMsgList); // add a confirm message for running job warningMsgList.add("Warning: " + Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING); if (!CommandsUtils.showWarningMsg(clusterConfig.getName(), Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG, warningMsgList, alwaysAnswerYes)) { return; } restClient.configCluster(clusterConfig); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_CONFIG); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); return; } } private void resumeCreateCluster(final String name) { Map<String, String> queryStrings = new HashMap<String, String>(); queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_RESUME); try { restClient.actionOps(name, queryStrings); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESULT_RESUME); } catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private List<String> getNetworkNames() { List<String> networkNames = new ArrayList<String>(0); NetworkRead[] networks = networkRestClient.getAll(false); if (networks != null) { for (NetworkRead network : networks) networkNames.add(network.getName()); } return networkNames; } private List<String> getDistroNames() { List<String> distroNames = new ArrayList<String>(0); DistroRead[] distros = distroRestClient.getAll(); if (distros != null) { for (DistroRead distro : distros) distroNames.add(distro.getName()); } return distroNames; } private boolean validName(String inputName, List<String> validNames) { for (String name : validNames) { if (name.equals(inputName)) { return true; } } return false; } private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) { TopologyType topology = cluster.getTopologyPolicy(); if (topology == null || topology == TopologyType.NONE) { System.out.printf("cluster name: %s, distro: %s, status: %s", cluster.getName(), cluster.getDistro(), cluster.getStatus()); } else { System.out.printf("cluster name: %s, distro: %s, topology: %s, status: %s", cluster.getName(), cluster.getDistro(), topology, cluster.getStatus()); } System.out.println(); if(cluster.getExternalHDFS() != null && !cluster.getExternalHDFS().isEmpty()) { System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS()); } LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); List<NodeGroupRead> nodegroups = cluster.getNodeGroups(); if (nodegroups != null) { ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_GROUP_NAME, Arrays.asList("getName")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_INSTANCE, Arrays.asList("getInstanceNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU, Arrays.asList("getCpuNum")); ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM, Arrays.asList("getMemCapacityMB")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_TYPE, Arrays.asList("getStorage", "getType")); ngColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_SIZE, Arrays.asList("getStorage", "getSizeGB")); try { if (detail) { LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NODE_NAME, Arrays.asList("getName")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_HOST, Arrays.asList("getHostName")); if (topology == TopologyType.RACK_AS_RACK || topology == TopologyType.HVE) { nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_RACK, Arrays.asList("getRack")); } nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_STATUS, Arrays.asList("getStatus")); for (NodeGroupRead nodegroup : nodegroups) { CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, new NodeGroupRead[] { nodegroup }, Constants.OUTPUT_INDENT); List<NodeRead> nodes = nodegroup.getInstances(); if (nodes != null) { System.out.println(); CommandsUtils.printInTableFormat( nColumnNamesWithGetMethodNames, nodes.toArray(), new StringBuilder().append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT).toString()); } System.out.println(); } } else CommandsUtils.printInTableFormat( ngColumnNamesWithGetMethodNames, nodegroups.toArray(), Constants.OUTPUT_INDENT); } catch (Exception e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, cluster.getName(), Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } } private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) { for (ClusterRead cluster : clusters) { prettyOutputClusterInfo(cluster, detail); System.out.println(); } } private void showFailedMsg(String name, List<String> failedMsgList) { //cluster creation failed message. StringBuilder failedMsg = new StringBuilder(); failedMsg.append(Constants.INVALID_VALUE); if (failedMsgList.size() > 1) { failedMsg.append("s"); } failedMsg.append(" "); StringBuilder tmpMsg = new StringBuilder(); for (String msg : failedMsgList) { tmpMsg.append(",").append(msg); } tmpMsg.replace(0, 1, ""); failedMsg.append(tmpMsg); failedMsg.append("."); CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name, Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL, failedMsg.toString()); } private void validateConfiguration(ClusterCreate cluster, boolean skipConfigValidation, List<String> warningMsgList) { // validate blacklist ValidateResult blackListResult = validateBlackList(cluster); if (blackListResult != null) { addBlackListWarning(blackListResult, warningMsgList); } if (!skipConfigValidation) { // validate whitelist ValidateResult whiteListResult = validateWhiteList(cluster); addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList); } else { cluster.setValidateConfig(false); } } private ValidateResult validateBlackList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.BLACK_LIST); } private ValidateResult validateWhiteList(ClusterCreate cluster) { return validateConfiguration(cluster, ValidationType.WHITE_LIST); } /* * Validate a configuration of the cluster at first. Validate configurations of all of node groups then. * And merge the failed info which have been producted by validation between cluster level and node group * level. */ private ValidateResult validateConfiguration(ClusterCreate cluster, ValidationType validationType) { ValidateResult validateResult = new ValidateResult(); // validate cluster level Configuration ValidateResult vr = null; if (cluster.getConfiguration() != null && !cluster.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, cluster.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); validateResult.setFailureNames(vr.getFailureNames()); validateResult.setNoExistFileNames(vr.getNoExistFileNames()); } } List<String> failureNames = new LinkedList<String>(); Map<String,List<String>> noExistingFileNamesMap = new HashMap<String,List<String>>(); failureNames.addAll(validateResult.getFailureNames()); noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames()); // validate nodegroup level Configuration for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) { if (nodeGroup.getConfiguration() != null && !nodeGroup.getConfiguration().isEmpty()) { vr = AppConfigValidationUtils.validateConfig(validationType, nodeGroup.getConfiguration()); if (vr.getType() != ValidateResult.Type.VALID) { validateResult.setType(vr.getType()); // merge failed names between cluster level and node group level. for (String failureName : vr.getFailureNames()) { if (!failureNames.contains(failureName)) { failureNames.add(failureName); } } // merge no existing file names between cluster level and node group level for (Entry<String, List<String>> noExistingFileNames : vr.getNoExistFileNames().entrySet()) { String configType = noExistingFileNames.getKey(); if (noExistingFileNamesMap.containsKey(configType)) { List<String> noExistingFilesTemp = noExistingFileNames.getValue(); List<String> noExistingFiles = noExistingFileNamesMap.get(configType); for (String fileName : noExistingFilesTemp) { if (!noExistingFiles.contains(fileName)) { noExistingFiles.add(fileName); } } noExistingFileNamesMap.put(configType, noExistingFiles); } else { noExistingFileNamesMap.put(configType, noExistingFileNames.getValue()); } } } } } validateResult.setFailureNames(failureNames); validateResult.setNoExistFileNames(noExistingFileNamesMap); return validateResult; } private void addWhiteListWarning(final String clusterName, ValidateResult whiteListResult, List<String> warningMsgList) { if(whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); } }else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) { String noExistingWarningMsg = getValidateWarningMsg(whiteListResult.getNoExistFileNames()); String failureNameWarningMsg = getValidateWarningMsg(whiteListResult.getFailureNames(), Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING); if (warningMsgList != null) { warningMsgList.add(noExistingWarningMsg); warningMsgList.add(failureNameWarningMsg); } } } private void addBlackListWarning(ValidateResult blackListResult, List<String> warningList) { if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) { String warningMsg = getValidateWarningMsg(blackListResult.getFailureNames(), Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING + Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); if (warningList != null) { warningList.add(warningMsg); } } } private String getValidateWarningMsg(List<String> failureNames, String warningMsg) { StringBuilder warningMsgBuff = new StringBuilder(); if (failureNames != null && !failureNames.isEmpty()) { warningMsgBuff.append("Warning: "); for (String failureName : failureNames) { warningMsgBuff.append(failureName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (failureNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append(warningMsg); } return warningMsgBuff.toString(); } private String getValidateWarningMsg(Map<String,List<String>> noExistingFilesMap) { StringBuilder warningMsgBuff = new StringBuilder(); if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) { warningMsgBuff.append("Warning: "); for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap.entrySet()) { List<String> noExistingFileNames = noExistingFilesEntry.getValue(); for (String noExistingFileName : noExistingFileNames) { warningMsgBuff.append(noExistingFileName).append(", "); } warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length()); if (noExistingFileNames.size() > 1) { warningMsgBuff.append(" are "); } else { warningMsgBuff.append(" is "); } warningMsgBuff.append("not existing in "); warningMsgBuff.append(noExistingFilesEntry.getKey()+ " scope , "); } warningMsgBuff.replace(warningMsgBuff.length() - 2, warningMsgBuff.length(),". "); warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT); } return warningMsgBuff.toString(); } private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) { List<String> haFlagList = Arrays.asList("off","on","ft"); if (nodeGroups != null){ for(NodeGroupCreate group : nodeGroups){ if (!haFlagList.contains(group.getHaFlag().toLowerCase())){ return false; } } } return true; } }
diff --git a/seck-web/src/main/java/com/pcwerk/seck/servlet/HelloWorld.java b/seck-web/src/main/java/com/pcwerk/seck/servlet/HelloWorld.java index b1d15a0..da231f6 100644 --- a/seck-web/src/main/java/com/pcwerk/seck/servlet/HelloWorld.java +++ b/seck-web/src/main/java/com/pcwerk/seck/servlet/HelloWorld.java @@ -1,52 +1,52 @@ package com.pcwerk.seck.servlet; import java.io.*; import java.util.List; import javax.servlet.*; import javax.servlet.http.*; import com.pcwerk.seck.indexer.Indexer; import com.pcwerk.seck.store.WebDocument; public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String query = request.getParameter("query"); System.out.println("Getting indexer"); Indexer indexSearch = new Indexer("indexing"); System.out.println("Got indexer"); System.out.println("Query is: " + query); List<WebDocument> resultList = indexSearch.indexQuerySearch( query ); out.println("<table><tr><th>URL</th><th>score</th></tr>"); for( WebDocument result : resultList) { out.println("<tr><td>"); out.println("<a href='" + result.getUrl() + "'>'" + result.getTitle() + "' </a>"); out.println("</td><td>"); out.println(result.getScore()); out.println("</td></tr>"); } out.println("</table>"); - out.println("<a href=seck-web-0.0.6-dev/index.jsp>back to search</a>"); + out.println("<a href=index.jsp>back to search</a>"); } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String query = request.getParameter("query"); System.out.println("Getting indexer"); Indexer indexSearch = new Indexer("indexing"); System.out.println("Got indexer"); System.out.println("Query is: " + query); List<WebDocument> resultList = indexSearch.indexQuerySearch( query ); out.println("<table><tr><th>URL</th><th>score</th></tr>"); for( WebDocument result : resultList) { out.println("<tr><td>"); out.println("<a href='" + result.getUrl() + "'>'" + result.getTitle() + "' </a>"); out.println("</td><td>"); out.println(result.getScore()); out.println("</td></tr>"); } out.println("</table>"); out.println("<a href=seck-web-0.0.6-dev/index.jsp>back to search</a>"); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String query = request.getParameter("query"); System.out.println("Getting indexer"); Indexer indexSearch = new Indexer("indexing"); System.out.println("Got indexer"); System.out.println("Query is: " + query); List<WebDocument> resultList = indexSearch.indexQuerySearch( query ); out.println("<table><tr><th>URL</th><th>score</th></tr>"); for( WebDocument result : resultList) { out.println("<tr><td>"); out.println("<a href='" + result.getUrl() + "'>'" + result.getTitle() + "' </a>"); out.println("</td><td>"); out.println(result.getScore()); out.println("</td></tr>"); } out.println("</table>"); out.println("<a href=index.jsp>back to search</a>"); }
diff --git a/src/org/mediawiki/importer/ListFilter.java b/src/org/mediawiki/importer/ListFilter.java index 6478cfd..ff4d53c 100644 --- a/src/org/mediawiki/importer/ListFilter.java +++ b/src/org/mediawiki/importer/ListFilter.java @@ -1,61 +1,62 @@ /* * MediaWiki import/export processing tools * Copyright 2005 by Brion Vibber * * 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. * * $Id$ */ package org.mediawiki.importer; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class ListFilter extends PageFilter { protected HashMap list; public ListFilter(DumpWriter sink, String sourceFileName) throws IOException { super(sink); list = new HashMap(); BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream(sourceFileName), "utf-8")); String line = input.readLine(); while (line != null) { if (!line.startsWith("#")) { String title = line.trim(); + title = title.replace("_", " "); if (title.startsWith(":")) title = line.substring(1); if (title.length() > 0) list.put(title, title); } line = input.readLine(); } input.close(); } protected boolean pass(Page page) { return list.containsKey(page.Title.subjectPage().toString()) || list.containsKey(page.Title.talkPage().toString()); } }
true
true
public ListFilter(DumpWriter sink, String sourceFileName) throws IOException { super(sink); list = new HashMap(); BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream(sourceFileName), "utf-8")); String line = input.readLine(); while (line != null) { if (!line.startsWith("#")) { String title = line.trim(); if (title.startsWith(":")) title = line.substring(1); if (title.length() > 0) list.put(title, title); } line = input.readLine(); } input.close(); }
public ListFilter(DumpWriter sink, String sourceFileName) throws IOException { super(sink); list = new HashMap(); BufferedReader input = new BufferedReader(new InputStreamReader( new FileInputStream(sourceFileName), "utf-8")); String line = input.readLine(); while (line != null) { if (!line.startsWith("#")) { String title = line.trim(); title = title.replace("_", " "); if (title.startsWith(":")) title = line.substring(1); if (title.length() > 0) list.put(title, title); } line = input.readLine(); } input.close(); }
diff --git a/src/org/openstreetmap/fma/jtiledownloader/views/main/slippymap/SlippyMapChooserWindow.java b/src/org/openstreetmap/fma/jtiledownloader/views/main/slippymap/SlippyMapChooserWindow.java index e19ccc5..514d3d2 100644 --- a/src/org/openstreetmap/fma/jtiledownloader/views/main/slippymap/SlippyMapChooserWindow.java +++ b/src/org/openstreetmap/fma/jtiledownloader/views/main/slippymap/SlippyMapChooserWindow.java @@ -1,44 +1,44 @@ package org.openstreetmap.fma.jtiledownloader.views.main.slippymap; //License: GPL. Copyright 2008 by Jan Peter Stotz // Adapted for JTileDownloader by Sven Strickroth <[email protected]>, 2009 - 2010 import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.WindowConstants; import org.openstreetmap.fma.jtiledownloader.datatypes.TileProviderIf; import org.openstreetmap.fma.jtiledownloader.views.main.inputpanel.BBoxLatLonPanel; import org.openstreetmap.gui.jmapviewer.JMapViewer; /** * * Demonstrates the usage of {@link JMapViewer} * * @author Jan Peter Stotz * */ public class SlippyMapChooserWindow extends JFrame { private SlippyMapChooser map = null; private static final long serialVersionUID = 1L; public SlippyMapChooserWindow(BBoxLatLonPanel bboxlatlonpanel, TileProviderIf tileProvider, String tileDirectory) { super("Slippy Map Chooser"); setSize(400, 400); - map = new SlippyMapChooser(bboxlatlonpanel, tileProvider, tileDirectory); + map = new SlippyMapChooser(bboxlatlonpanel, tileDirectory, tileProvider); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); add(map, BorderLayout.CENTER); } public SlippyMapChooser getSlippyMapChooser() { return map; } }
true
true
public SlippyMapChooserWindow(BBoxLatLonPanel bboxlatlonpanel, TileProviderIf tileProvider, String tileDirectory) { super("Slippy Map Chooser"); setSize(400, 400); map = new SlippyMapChooser(bboxlatlonpanel, tileProvider, tileDirectory); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); add(map, BorderLayout.CENTER); }
public SlippyMapChooserWindow(BBoxLatLonPanel bboxlatlonpanel, TileProviderIf tileProvider, String tileDirectory) { super("Slippy Map Chooser"); setSize(400, 400); map = new SlippyMapChooser(bboxlatlonpanel, tileDirectory, tileProvider); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); add(map, BorderLayout.CENTER); }
diff --git a/src/org/apache/xerces/validators/schema/TraverseSchema.java b/src/org/apache/xerces/validators/schema/TraverseSchema.java index 0734179cb..14fb8d048 100644 --- a/src/org/apache/xerces/validators/schema/TraverseSchema.java +++ b/src/org/apache/xerces/validators/schema/TraverseSchema.java @@ -1,8620 +1,8620 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000,2001 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.validators.schema; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.validators.common.Grammar; import org.apache.xerces.validators.common.GrammarResolver; import org.apache.xerces.validators.common.GrammarResolverImpl; import org.apache.xerces.validators.common.XMLElementDecl; import org.apache.xerces.validators.common.XMLAttributeDecl; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.XUtil; import org.apache.xerces.validators.schema.identity.Field; import org.apache.xerces.validators.schema.identity.IdentityConstraint; import org.apache.xerces.validators.schema.identity.Key; import org.apache.xerces.validators.schema.identity.KeyRef; import org.apache.xerces.validators.schema.identity.Selector; import org.apache.xerces.validators.schema.identity.Unique; import org.apache.xerces.validators.schema.identity.XPath; import org.apache.xerces.validators.schema.identity.XPathException; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl; import org.apache.xerces.validators.datatype.IDDatatypeValidator; import org.apache.xerces.validators.datatype.NOTATIONDatatypeValidator; import org.apache.xerces.validators.datatype.StringDatatypeValidator; import org.apache.xerces.validators.datatype.ListDatatypeValidator; import org.apache.xerces.validators.datatype.UnionDatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.utils.StringPool; import org.w3c.dom.Element; import java.io.IOException; import java.util.*; import java.net.URL; import java.net.MalformedURLException; //REVISIT: for now, import everything in the DOM package import org.w3c.dom.*; //Unit Test import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.validators.common.XMLValidator; import org.apache.xerces.validators.datatype.DatatypeValidator.*; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.framework.XMLParser; import org.apache.xerces.framework.XMLDocumentScanner; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.w3c.dom.Document; /** Don't check the following code in because it creates a dependency on the serializer, preventing to package the parser without the serializer. import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; **/ import org.apache.xerces.validators.schema.SchemaSymbols; /** * Instances of this class get delegated to Traverse the Schema and * to populate the Grammar internal representation by * instances of Grammar objects. * Traverse a Schema Grammar: * * @author Eric Ye, IBM * @author Jeffrey Rodriguez, IBM * @author Andy Clark, IBM * * @see org.apache.xerces.validators.common.Grammar * * @version $Id$ */ public class TraverseSchema implements NamespacesScope.NamespacesHandler{ //CONSTANTS private static final int TOP_LEVEL_SCOPE = -1; /** Identity constraint keywords. */ private static final String[][] IDENTITY_CONSTRAINTS = { { SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_UNIQUE }, { SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEY }, { SchemaSymbols.URI_SCHEMAFORSCHEMA, SchemaSymbols.ELT_KEYREF }, }; private static final String redefIdentifier = "_redefined"; // Flags for handleOccurrences to indicate any special // restrictions on minOccurs and maxOccurs relating to "all". // NOT_ALL_CONTEXT - not processing an <all> // PROCESSING_ALL - processing an <element> in an <all> // GROUP_REF_WITH_ALL - processing <group> reference that contained <all> // CHILD_OF_GROUP - processing a child of a model group definition private static final int NOT_ALL_CONTEXT = 0; private static final int PROCESSING_ALL = 1; private static final int GROUP_REF_WITH_ALL = 2; private static final int CHILD_OF_GROUP = 4; //debugging private static final boolean DEBUGGING = false; /** Compile to true to debug identity constraints. */ private static final boolean DEBUG_IDENTITY_CONSTRAINTS = false; /** * Compile to true to debug datatype validator lookup for * identity constraint support. */ private static final boolean DEBUG_IC_DATATYPES = false; //private data members private boolean fFullConstraintChecking = false; private XMLErrorReporter fErrorReporter = null; private StringPool fStringPool = null; private GrammarResolver fGrammarResolver = null; private SchemaGrammar fSchemaGrammar = null; private Element fSchemaRootElement; // this is always set to refer to the root of the linked list containing the root info of schemas under redefinition. private SchemaInfo fSchemaInfoListRoot = null; private SchemaInfo fCurrentSchemaInfo = null; private boolean fRedefineSucceeded; private DatatypeValidatorFactoryImpl fDatatypeRegistry = null; private Hashtable fComplexTypeRegistry = new Hashtable(); private Hashtable fAttributeDeclRegistry = new Hashtable(); // stores the names of groups that we've traversed so we can avoid multiple traversals // qualified group names are keys and their contentSpecIndexes are values. private Hashtable fGroupNameRegistry = new Hashtable(); // this Hashtable keeps track of whether a given redefined group does so by restriction. private Hashtable fRestrictedRedefinedGroupRegistry = new Hashtable(); // stores "final" values of simpleTypes--no clean way to integrate this into the existing datatype validation structure... private Hashtable fSimpleTypeFinalRegistry = new Hashtable(); // stores <notation> decl private Hashtable fNotationRegistry = new Hashtable(); private Vector fIncludeLocations = new Vector(); private Vector fImportLocations = new Vector(); private Hashtable fRedefineLocations = new Hashtable(); private Vector fTraversedRedefineElements = new Vector(); // Hashtable associating attributeGroups within a <redefine> which // restrict attributeGroups in the original schema with the // new name for those groups in the modified redefined schema. private Hashtable fRedefineAttributeGroupMap = null; // simpleType data private Hashtable fFacetData = new Hashtable(10); private Stack fSimpleTypeNameStack = new Stack(); private String fListName = ""; private int fAnonTypeCount =0; private int fScopeCount=0; private int fCurrentScope=TOP_LEVEL_SCOPE; private int fSimpleTypeAnonCount = 0; private Stack fCurrentTypeNameStack = new Stack(); private Stack fCurrentGroupNameStack = new Stack(); private Vector fElementRecurseComplex = new Vector(); private Vector fSubstitutionGroupRecursionRegistry = new Vector(); private boolean fElementDefaultQualified = false; private boolean fAttributeDefaultQualified = false; private int fBlockDefault = 0; private int fFinalDefault = 0; private int fTargetNSURI; private String fTargetNSURIString = ""; private NamespacesScope fNamespacesScope = null; private String fCurrentSchemaURL = ""; private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl(); private XMLAttributeDecl fTemp2AttributeDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); private XMLElementDecl fTempElementDecl2 = new XMLElementDecl(); private XMLContentSpec tempContentSpec1 = new XMLContentSpec(); private XMLContentSpec tempContentSpec2 = new XMLContentSpec(); private EntityResolver fEntityResolver = null; private SubstitutionGroupComparator fSComp = null; private Hashtable fIdentityConstraints = new Hashtable(); // Yet one more data structure; this one associates // <unique> and <key> QNames with their corresponding objects, // so that <keyRef>s can find them. private Hashtable fIdentityConstraintNames = new Hashtable(); // General Attribute Checking private GeneralAttrCheck fGeneralAttrCheck = null; private int fXsiURI; // REVISIT: maybe need to be moved into SchemaGrammar class public class ComplexTypeInfo { public String typeName; public DatatypeValidator baseDataTypeValidator; public ComplexTypeInfo baseComplexTypeInfo; public int derivedBy = 0; public int blockSet = 0; public int finalSet = 0; public int miscFlags=0; public int scopeDefined = -1; public int contentType; public int contentSpecHandle = -1; public int templateElementIndex = -1; public int attlistHead = -1; public DatatypeValidator datatypeValidator; public boolean isAbstractType() { return ((miscFlags & CT_IS_ABSTRACT)!=0); } public boolean containsAttrTypeID () { return ((miscFlags & CT_CONTAINS_ATTR_TYPE_ID)!=0); } public boolean declSeen () { return ((miscFlags & CT_DECL_SEEN)!=0); } public void setIsAbstractType() { miscFlags |= CT_IS_ABSTRACT; } public void setContainsAttrTypeID() { miscFlags |= CT_CONTAINS_ATTR_TYPE_ID; } public void setDeclSeen() { miscFlags |= CT_DECL_SEEN; } } private static final int CT_IS_ABSTRACT=1; private static final int CT_CONTAINS_ATTR_TYPE_ID=2; private static final int CT_DECL_SEEN=4; // indicates that the declaration was // traversed as opposed to processed due // to a forward reference private class ComplexTypeRecoverableError extends Exception { ComplexTypeRecoverableError() {super();} ComplexTypeRecoverableError(String s) {super(s);} } private class ParticleRecoverableError extends Exception { ParticleRecoverableError(String s) {super(s);} } private class ElementInfo { int elementIndex; String typeName; private ElementInfo(int i, String name) { elementIndex = i; typeName = name; } } //REVISIT: verify the URI. public final static String SchemaForSchemaURI = "http://www.w3.org/TR-1/Schema"; private TraverseSchema( ) { // new TraverseSchema() is forbidden; } public void setFullConstraintCheckingEnabled() { fFullConstraintChecking = true; } public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } public void startNamespaceDeclScope(int prefix, int uri){ //TO DO } public void endNamespaceDeclScope(int prefix){ //TO DO, do we need to do anything here? } public boolean particleEmptiable(int contentSpecIndex) { if (!fFullConstraintChecking) { return true; } if (minEffectiveTotalRange(contentSpecIndex)==0) return true; else return false; } public int minEffectiveTotalRange(int contentSpecIndex) { fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1); int type = tempContentSpec1.type; if (type == XMLContentSpec.CONTENTSPECNODE_SEQ || type == XMLContentSpec.CONTENTSPECNODE_ALL) { return minEffectiveTotalRangeSeq(contentSpecIndex); } else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) { return minEffectiveTotalRangeChoice(contentSpecIndex); } else { return(fSchemaGrammar.getContentSpecMinOccurs(contentSpecIndex)); } } private int minEffectiveTotalRangeSeq(int csIndex) { fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); int type = tempContentSpec1.type; int left = tempContentSpec1.value; int right = tempContentSpec1.otherValue; int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex); int result; if (right == -2) result = min * minEffectiveTotalRange(left); else result = min * (minEffectiveTotalRange(left) + minEffectiveTotalRange(right)); return result; } private int minEffectiveTotalRangeChoice(int csIndex) { fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); int type = tempContentSpec1.type; int left = tempContentSpec1.value; int right = tempContentSpec1.otherValue; int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex); int result; if (right == -2) result = min * minEffectiveTotalRange(left); else { int minLeft = minEffectiveTotalRange(left); int minRight = minEffectiveTotalRange(right); result = min * ((minLeft < minRight)?minLeft:minRight); } return result; } public int maxEffectiveTotalRange(int contentSpecIndex) { fSchemaGrammar.getContentSpec(contentSpecIndex, tempContentSpec1); int type = tempContentSpec1.type; if (type == XMLContentSpec.CONTENTSPECNODE_SEQ || type == XMLContentSpec.CONTENTSPECNODE_ALL) { return maxEffectiveTotalRangeSeq(contentSpecIndex); } else if (type == XMLContentSpec.CONTENTSPECNODE_CHOICE) { return maxEffectiveTotalRangeChoice(contentSpecIndex); } else { return(fSchemaGrammar.getContentSpecMaxOccurs(contentSpecIndex)); } } private int maxEffectiveTotalRangeSeq(int csIndex) { fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); int type = tempContentSpec1.type; int left = tempContentSpec1.value; int right = tempContentSpec1.otherValue; int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex); if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; int maxLeft = maxEffectiveTotalRange(left); if (right == -2) { if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; else return max * maxLeft; } else { int maxRight = maxEffectiveTotalRange(right); if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED || maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; else return max * (maxLeft + maxRight); } } private int maxEffectiveTotalRangeChoice(int csIndex) { fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); int type = tempContentSpec1.type; int left = tempContentSpec1.value; int right = tempContentSpec1.otherValue; int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex); if (max == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; int maxLeft = maxEffectiveTotalRange(left); if (right == -2) { if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; else return max * maxLeft; } else { int maxRight = maxEffectiveTotalRange(right); if (maxLeft == SchemaSymbols.OCCURRENCE_UNBOUNDED || maxRight == SchemaSymbols.OCCURRENCE_UNBOUNDED) return SchemaSymbols.OCCURRENCE_UNBOUNDED; else return max * ((maxLeft > maxRight)?maxLeft:maxRight); } } private String resolvePrefixToURI (String prefix) throws Exception { String uriStr = fStringPool.toString(fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix))); if (uriStr.length() == 0 && prefix.length() > 0) { // REVISIT: Localize reportGenericSchemaError("prefix : [" + prefix +"] cannot be resolved to a URI"); return ""; } //REVISIT, !!!! a hack: needs to be updated later, cause now we only use localpart to key build-in datatype. if ( prefix.length()==0 && uriStr.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && fTargetNSURIString.length() == 0) { uriStr = ""; } return uriStr; } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver, XMLErrorReporter errorReporter, String schemaURL, EntityResolver entityResolver, boolean fullChecking, GeneralAttrCheck generalAttrCheck ) throws Exception { fErrorReporter = errorReporter; fCurrentSchemaURL = schemaURL; fFullConstraintChecking = fullChecking; fEntityResolver = entityResolver; fGeneralAttrCheck = generalAttrCheck; doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver, XMLErrorReporter errorReporter, String schemaURL, boolean fullChecking, GeneralAttrCheck generalAttrCheck ) throws Exception { fErrorReporter = errorReporter; fCurrentSchemaURL = schemaURL; fFullConstraintChecking = fullChecking; fGeneralAttrCheck = generalAttrCheck; doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public TraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver, boolean fullChecking, GeneralAttrCheck generalAttrCheck ) throws Exception { fFullConstraintChecking = fullChecking; fGeneralAttrCheck = generalAttrCheck; doTraverseSchema(root, stringPool, schemaGrammar, grammarResolver); } public void doTraverseSchema(Element root, StringPool stringPool, SchemaGrammar schemaGrammar, GrammarResolver grammarResolver) throws Exception { fNamespacesScope = new NamespacesScope(this); fSchemaRootElement = root; fStringPool = stringPool; fSchemaGrammar = schemaGrammar; if (fFullConstraintChecking) { fSchemaGrammar.setDeferContentSpecExpansion(); fSchemaGrammar.setCheckUniqueParticleAttribution(); } fGrammarResolver = grammarResolver; fDatatypeRegistry = (DatatypeValidatorFactoryImpl) fGrammarResolver.getDatatypeRegistry(); //Expand to registry type to contain all primitive datatype fDatatypeRegistry.expandRegistryToFullSchemaSet(); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); if (root == null) { // REVISIT: Anything to do? return; } // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope); //Make sure namespace binding is defaulted String rootPrefix = root.getPrefix(); if( rootPrefix == null || rootPrefix.length() == 0 ){ String xmlns = root.getAttribute("xmlns"); if( xmlns.length() == 0 ) root.setAttribute("xmlns", SchemaSymbols.URI_SCHEMAFORSCHEMA ); } //Retrieve the targetNamespace URI information fTargetNSURIString = getTargetNamespaceString(root); fTargetNSURI = fStringPool.addSymbol(fTargetNSURIString); if (fGrammarResolver == null) { // REVISIT: Localize reportGenericSchemaError("Internal error: don't have a GrammarResolver for TraverseSchema"); } else{ // for complex type registry, attribute decl registry and // namespace mapping, needs to check whether the passed in // Grammar was a newly instantiated one. if (fSchemaGrammar.getComplexTypeRegistry() == null ) { fSchemaGrammar.setComplexTypeRegistry(fComplexTypeRegistry); } else { fComplexTypeRegistry = fSchemaGrammar.getComplexTypeRegistry(); } if (fSchemaGrammar.getAttributeDeclRegistry() == null ) { fSchemaGrammar.setAttributeDeclRegistry(fAttributeDeclRegistry); } else { fAttributeDeclRegistry = fSchemaGrammar.getAttributeDeclRegistry(); } if (fSchemaGrammar.getNamespacesScope() == null ) { fSchemaGrammar.setNamespacesScope(fNamespacesScope); } else { fNamespacesScope = fSchemaGrammar.getNamespacesScope(); } fSchemaGrammar.setDatatypeRegistry(fDatatypeRegistry); fSchemaGrammar.setTargetNamespaceURI(fTargetNSURIString); fGrammarResolver.putGrammar(fTargetNSURIString, fSchemaGrammar); } // Retrived the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT); if (blockAttr == null) fBlockDefault = 0; else fBlockDefault = parseBlockSet(blockAttr.getValue()); Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT); if (finalAttr == null) fFinalDefault = 0; else fFinalDefault = parseFinalSet(finalAttr.getValue()); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { //fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); // process <redefine>, <include> and <import> info items. Element child = XUtil.getFirstChildElement(root); for (; child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { fNamespacesScope.increaseDepth(); traverseInclude(child); fNamespacesScope.decreaseDepth(); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } else if (name.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefineSucceeded = true; // presume worked until proven failed. traverseRedefine(child); } else break; } // child refers to the first info item which is not <annotation> or // one of the schema inclusion/importation declarations. for (; child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { traverseAttributeGroupDecl(child, null, null); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { traverseAttributeDecl( child, null, false ); } else if (name.equals(SchemaSymbols.ELT_GROUP)) { traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { traverseNotationDecl(child); //TO DO } else { // REVISIT: Localize reportGenericSchemaError("error in content of <schema> element information item"); } } // for each child node // handle identity constraints // we must traverse <key>s and <unique>s before we tackel<keyref>s, // since all have global scope and may be declared anywhere in the schema. Enumeration elementIndexes = fIdentityConstraints.keys(); while (elementIndexes.hasMoreElements()) { Integer elementIndexObj = (Integer)elementIndexes.nextElement(); if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj); } Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj); if (identityConstraints != null) { int elementIndex = elementIndexObj.intValue(); traverseIdentityNameConstraintsFor(elementIndex, identityConstraints); } } elementIndexes = fIdentityConstraints.keys(); while (elementIndexes.hasMoreElements()) { Integer elementIndexObj = (Integer)elementIndexes.nextElement(); if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: traversing identity constraints for element: "+elementIndexObj); } Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj); if (identityConstraints != null) { int elementIndex = elementIndexObj.intValue(); traverseIdentityRefConstraintsFor(elementIndex, identityConstraints); } } } // traverseSchema(Element) private void extractTopLevel3Components(Element root) throws Exception { for (Element child = XUtil.getFirstChildElement(root); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); String compName = child.getAttribute(SchemaSymbols.ATT_NAME); if (name.equals(SchemaSymbols.ELT_ELEMENT)) { // Check if the element has already been declared if (fSchemaGrammar.topLevelElemDecls.get(compName) != null) { reportGenericSchemaError("sch-props-correct: Duplicate declaration for an element " + compName); } else { fSchemaGrammar.topLevelElemDecls.put(compName, child); } } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE) || name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { // Check for dublicate declaration if (fSchemaGrammar.topLevelTypeDecls.get(compName) != null) { reportGenericSchemaError("sch-props-correct: Duplicate declaration for a type " + compName); } else { fSchemaGrammar.topLevelTypeDecls.put(compName, child); } } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { // Check for dublicate declaration if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) { reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute group " + compName); } else { fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child); } } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { // Check for dublicate declaration if (fSchemaGrammar.topLevelAttrGrpDecls.get(compName) != null) { reportGenericSchemaError("sch-props-correct: Duplicate declaration for an attribute " + compName); } else { fSchemaGrammar.topLevelAttrGrpDecls.put(compName, child); } } else if ( name.equals(SchemaSymbols.ELT_GROUP) ) { // Check if the group has already been declared if (fSchemaGrammar.topLevelGroupDecls.get(compName) != null){ reportGenericSchemaError("sch-props-correct: Duplicate declaration for a group " + compName); } else { fSchemaGrammar.topLevelGroupDecls.put(compName, child); } } else if ( name.equals(SchemaSymbols.ELT_NOTATION) ) { // Check for dublicate declaration if (fSchemaGrammar.topLevelNotationDecls.get(compName) != null) { reportGenericSchemaError("sch-props-correct: Duplicate declaration for a notation " + compName); } else { fSchemaGrammar.topLevelNotationDecls.put(compName, child); } } } // for each child node } /** * Expands a system id and returns the system id as a URL, if * it can be expanded. A return value of null means that the * identifier is already expanded. An exception thrown * indicates a failure to expand the id. * * @param systemId The systemId to be expanded. * * @return Returns the URL object representing the expanded system * identifier. A null value indicates that the given * system identifier is already expanded. * */ private String expandSystemId(String systemId, String currentSystemId) throws Exception{ String id = systemId; // check for bad parameters id if (id == null || id.length() == 0) { return systemId; } // if id already expanded, return try { URL url = new URL(id); if (url != null) { return systemId; } } catch (MalformedURLException e) { // continue on... } // normalize id id = fixURI(id); // normalize base URL base = null; URL url = null; try { if (currentSystemId == null) { String dir; try { dir = fixURI(System.getProperty("user.dir")); } catch (SecurityException se) { dir = ""; } if (!dir.endsWith("/")) { dir = dir + "/"; } base = new URL("file", "", dir); } else { base = new URL(currentSystemId); } // expand id url = new URL(base, id); } catch (Exception e) { // let it go through } if (url == null) { return systemId; } return url.toString(); } /** * Fixes a platform dependent filename to standard URI form. * * @param str The string to fix. * * @return Returns the fixed URI string. */ private static String fixURI(String str) { // handle platform dependent strings str = str.replace(java.io.File.separatorChar, '/'); // Windows fix if (str.length() >= 2) { char ch1 = str.charAt(1); if (ch1 == ':') { char ch0 = Character.toUpperCase(str.charAt(0)); if (ch0 >= 'A' && ch0 <= 'Z') { str = "/" + str; } } } // done return str; } private void traverseInclude(Element includeDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(includeDecl, scope); checkContent(includeDecl, XUtil.getFirstChildElement(includeDecl), true); Attr locationAttr = includeDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION); if (locationAttr == null) { // REVISIT: Localize reportGenericSchemaError("a schemaLocation attribute must be specified on an <include> element"); return; } String location = locationAttr.getValue(); // expand it before passing it to the parser InputSource source = null; if (fEntityResolver != null) { source = fEntityResolver.resolveEntity("", location); } if (source == null) { location = expandSystemId(location, fCurrentSchemaURL); source = new InputSource(location); } else { // create a string for uniqueness of this included schema in fIncludeLocations if (source.getPublicId () != null) location = source.getPublicId (); location += (',' + source.getSystemId ()); } if (fIncludeLocations.contains((Object)location)) { return; } fIncludeLocations.addElement((Object)location); DOMParser parser = new IgnoreWhitespaceParser(); parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() { public void fatalError(SAXParseException ex) throws SAXException { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber()); String message = ex.getMessage(); if(message.toLowerCase().trim().endsWith("not found.")) { System.err.println("[Warning] "+ str.toString()+": "+ message); } else { // do standard thing System.err.println("[Fatal Error] "+ str.toString()+":"+message); throw ex; } } }); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( source ); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { //e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = getTargetNamespaceString(root); if (targetNSURI.length() > 0 && !targetNSURI.equals(fTargetNSURIString) ) { // REVISIT: Localize reportGenericSchemaError("included schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"'"); } else { // We not creating another TraverseSchema object to compile // the included schema file, because the scope count, anon-type count // should not be reset for a included schema, this can be fixed by saving // the counters in the Schema Grammar, if (fSchemaInfoListRoot == null) { fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified, fBlockDefault, fFinalDefault, fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, fNamespacesScope, null, null); fCurrentSchemaInfo = fSchemaInfoListRoot; } fSchemaRootElement = root; fCurrentSchemaURL = location; traverseIncludedSchemaHeader(root); // and now we'd better save this stuff! fCurrentSchemaInfo = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified, fBlockDefault, fFinalDefault, fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, fNamespacesScope, fCurrentSchemaInfo.getNext(), fCurrentSchemaInfo); (fCurrentSchemaInfo.getPrev()).setNext(fCurrentSchemaInfo); traverseIncludedSchema(root); // there must always be a previous element! fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev(); fCurrentSchemaInfo.restore(); } } } private void traverseIncludedSchemaHeader(Element root) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope); // Retrieved the Namespace mapping from the schema element. NamedNodeMap schemaEltAttrs = root.getAttributes(); int i = 0; Attr sattr = null; boolean seenXMLNS = false; while ((sattr = (Attr)schemaEltAttrs.item(i++)) != null) { String attName = sattr.getName(); if (attName.startsWith("xmlns:")) { String attValue = sattr.getValue(); String prefix = attName.substring(attName.indexOf(":")+1); fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(prefix), fStringPool.addSymbol(attValue) ); } if (attName.equals("xmlns")) { String attValue = sattr.getValue(); fNamespacesScope.setNamespaceForPrefix( StringPool.EMPTY_STRING, fStringPool.addSymbol(attValue) ); seenXMLNS = true; } } if (!seenXMLNS && fTargetNSURIString.length() == 0 ) { fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""), fStringPool.addSymbol("") ); } fElementDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ELEMENTFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); fAttributeDefaultQualified = root.getAttribute(SchemaSymbols.ATT_ATTRIBUTEFORMDEFAULT).equals(SchemaSymbols.ATTVAL_QUALIFIED); Attr blockAttr = root.getAttributeNode(SchemaSymbols.ATT_BLOCKDEFAULT); if (blockAttr == null) fBlockDefault = 0; else fBlockDefault = parseBlockSet(blockAttr.getValue()); Attr finalAttr = root.getAttributeNode(SchemaSymbols.ATT_FINALDEFAULT); if (finalAttr == null) fFinalDefault = 0; else fFinalDefault = parseFinalSet(finalAttr.getValue()); //REVISIT, really sticky when noTargetNamesapce, for now, we assume everyting is in the same name space); if (fTargetNSURI == StringPool.EMPTY_STRING) { fElementDefaultQualified = true; //fAttributeDefaultQualified = true; } //fScopeCount++; fCurrentScope = -1; } // traverseIncludedSchemaHeader private void traverseIncludedSchema(Element root) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(root, scope); //extract all top-level attribute, attributeGroup, and group Decls and put them in the 3 hasn table in the SchemaGrammar. extractTopLevel3Components(root); // handle <redefine>, <include> and <import> elements. Element child = XUtil.getFirstChildElement(root); for (; child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_INCLUDE)) { fNamespacesScope.increaseDepth(); traverseInclude(child); fNamespacesScope.decreaseDepth(); } else if (name.equals(SchemaSymbols.ELT_IMPORT)) { traverseImport(child); } else if (name.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefineSucceeded = true; // presume worked until proven failed. traverseRedefine(child); } else break; } // handle the rest of the schema elements. // BEWARE! this method gets called both from traverseRedefine and // traverseInclude; the preconditions (especially with respect to // groups and attributeGroups) are different! for (; child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_ELEMENT )) { traverseElementDecl(child); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { if(fRedefineAttributeGroupMap != null) { String dName = child.getAttribute(SchemaSymbols.ATT_NAME); String bName = (String)fRedefineAttributeGroupMap.get(dName); if(bName != null) { child.setAttribute(SchemaSymbols.ATT_NAME, bName); // and make sure we wipe this out of the grammar! fSchemaGrammar.topLevelAttrGrpDecls.remove(dName); // Now we reuse this location in the array to store info we'll need for validation... ComplexTypeInfo typeInfo = new ComplexTypeInfo(); int templateElementNameIndex = fStringPool.addSymbol("$"+bName); int typeNameIndex = fStringPool.addSymbol("%"+bName); typeInfo.scopeDefined = -2; typeInfo.contentSpecHandle = -1; typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE; typeInfo.datatypeValidator = null; typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl( new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, typeInfo.scopeDefined, typeInfo.contentType, typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator); Vector anyAttDecls = new Vector(); // need to determine how to initialize these babies; then // on the <redefine> traversing end, try // and cast the hash value into the right form; // failure indicates nothing to redefine; success // means we can feed checkAttribute... what it needs... traverseAttributeGroupDecl(child, typeInfo, anyAttDecls); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex( typeInfo.templateElementIndex); fRedefineAttributeGroupMap.put(dName, new Object []{typeInfo, fSchemaGrammar, anyAttDecls}); continue; } } traverseAttributeGroupDecl(child, null, null); // fSchemaGrammar.topLevelAttrGrpDecls.remove(child.getAttribute("name")); } else if (name.equals( SchemaSymbols.ELT_ATTRIBUTE ) ) { traverseAttributeDecl( child, null , false); } else if (name.equals(SchemaSymbols.ELT_GROUP)) { String dName = child.getAttribute(SchemaSymbols.ATT_NAME); if(fGroupNameRegistry.get(fTargetNSURIString + ","+dName) == null) { // we've been renamed already traverseGroupDecl(child); continue; } // if we're here: must have been a restriction. // we have yet to be renamed. try { Integer i = (Integer)fGroupNameRegistry.get(fTargetNSURIString + ","+dName); // if that succeeded then we're done; were ref'd here in // an include most likely. continue; } catch (ClassCastException c) { String s = (String)fGroupNameRegistry.get(fTargetNSURIString + ","+dName); if (s == null) continue; // must have seen this already--somehow... }; String bName = (String)fGroupNameRegistry.get(fTargetNSURIString +"," + dName); if(bName != null) { child.setAttribute(SchemaSymbols.ATT_NAME, bName); // Now we reuse this location in the array to store info we'll need for validation... // note that traverseGroupDecl will happily do that for us! } traverseGroupDecl(child); } else if (name.equals(SchemaSymbols.ELT_NOTATION)) { traverseNotationDecl(child); } else { // REVISIT: Localize reportGenericSchemaError("error in content of included <schema> element information item"); } } // for each child node } // This method's job is to open a redefined schema and store away its root element, defaultElementQualified and other // such info, in order that it can be available when redefinition actually takes place. // It assumes that it will be called from the schema doing the redefining, and it assumes // that the other schema's info has already been saved, putting the info it finds into the // SchemaInfoList element that is passed in. private void openRedefinedSchema(Element redefineDecl, SchemaInfo store) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(redefineDecl, scope); Attr locationAttr = redefineDecl.getAttributeNode(SchemaSymbols.ATT_SCHEMALOCATION); if (locationAttr == null) { // REVISIT: Localize fRedefineSucceeded = false; reportGenericSchemaError("a schemaLocation attribute must be specified on a <redefine> element"); return; } String location = locationAttr.getValue(); // expand it before passing it to the parser InputSource source = null; if (fEntityResolver != null) { source = fEntityResolver.resolveEntity("", location); } if (source == null) { location = expandSystemId(location, fCurrentSchemaURL); source = new InputSource(location); } else { // Make sure we don't redefine the same schema twice; it's allowed // but the specs encourage us to avoid it. if (source.getPublicId () != null) location = source.getPublicId (); // make sure we're not redefining ourselves! if(source.getSystemId().equals(fCurrentSchemaURL)) { // REVISIT: localize reportGenericSchemaError("src-redefine.2: a schema cannot redefine itself"); fRedefineSucceeded = false; return; } location += (',' + source.getSystemId ()); } if (fRedefineLocations.get((Object)location) != null) { // then we'd better make sure we're directed at that schema... fCurrentSchemaInfo = (SchemaInfo)(fRedefineLocations.get((Object)location)); fCurrentSchemaInfo.restore(); return; } DOMParser parser = new IgnoreWhitespaceParser(); parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( source ); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { //e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar to be redefined Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root == null) { // nothing to be redefined, so just continue; specs disallow an error here. fRedefineSucceeded = false; return; } // now if root isn't null, it'll contain the root of the schema we need to redefine. // We do this in two phases: first, we look through the children of // redefineDecl. Each one will correspond to an element of the // redefined schema that we need to redefine. To do this, we rename the // element of the redefined schema, and rework the base or ref tag of // the kid we're working on to refer to the renamed group or derive the // renamed type. Once we've done this, we actually go through the // schema being redefined and convert it to a grammar. Only then do we // run through redefineDecl's kids and put them in the grammar. // // This approach is kosher with the specs. It does raise interesting // questions about error reporting, and perhaps also about grammar // access, but it is comparatively efficient (we need make at most // only 2 traversals of any given information item) and moreover // we can use existing code to build the grammar structures once the // first pass is out of the way, so this should be quite robust. // check to see if the targetNameSpace is right String redefinedTargetNSURIString = getTargetNamespaceString(root); if (redefinedTargetNSURIString.length() > 0 && !redefinedTargetNSURIString.equals(fTargetNSURIString) ) { // REVISIT: Localize fRedefineSucceeded = false; reportGenericSchemaError("redefined schema '"+location+"' has a different targetNameSpace '" +redefinedTargetNSURIString+"' from the original schema"); } else { // targetNamespace is right, so let's do the renaming... // and let's keep in mind that the targetNamespace of the redefined // elements is that of the redefined schema! fSchemaRootElement = root; fCurrentSchemaURL = location; fNamespacesScope = new NamespacesScope(this); if((redefinedTargetNSURIString.length() == 0) && (root.getAttributeNode("xmlns") == null)) { fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, fTargetNSURI); } else { } // get default form xmlns bindings et al. traverseIncludedSchemaHeader(root); // and then save them... store.setNext(new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified, fBlockDefault, fFinalDefault, fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, fNamespacesScope, null, store)); (store.getNext()).setPrev(store); fCurrentSchemaInfo = store.getNext(); fRedefineLocations.put((Object)location, store.getNext()); } // end if } // end openRedefinedSchema /**** * <redefine * schemaLocation = uriReference * {any attributes with non-schema namespace . . .}> * Content: (annotation | ( * attributeGroup | complexType | group | simpleType))* * </redefine> */ private void traverseRedefine(Element redefineDecl) throws Exception { // initialize storage areas... fRedefineAttributeGroupMap = new Hashtable(); NamespacesScope saveNSScope = (NamespacesScope)fNamespacesScope.clone(); // only case in which need to save contents is when fSchemaInfoListRoot is null; otherwise we'll have // done this already one way or another. if (fSchemaInfoListRoot == null) { fSchemaInfoListRoot = new SchemaInfo(fElementDefaultQualified, fAttributeDefaultQualified, fBlockDefault, fFinalDefault, fCurrentScope, fCurrentSchemaURL, fSchemaRootElement, fNamespacesScope, null, null); openRedefinedSchema(redefineDecl, fSchemaInfoListRoot); if(!fRedefineSucceeded) return; fCurrentSchemaInfo = fSchemaInfoListRoot.getNext(); fNamespacesScope = (NamespacesScope)saveNSScope.clone(); renameRedefinedComponents(redefineDecl,fSchemaInfoListRoot.getNext().getRoot(), fSchemaInfoListRoot.getNext()); } else { // may have a chain here; need to be wary! SchemaInfo curr = fSchemaInfoListRoot; for(; curr.getNext() != null; curr = curr.getNext()); fCurrentSchemaInfo = curr; fCurrentSchemaInfo.restore(); openRedefinedSchema(redefineDecl, fCurrentSchemaInfo); if(!fRedefineSucceeded) return; fNamespacesScope = (NamespacesScope)saveNSScope.clone(); renameRedefinedComponents(redefineDecl,fCurrentSchemaInfo.getRoot(), fCurrentSchemaInfo); } // Now we have to march through our nicely-renamed schemas from the // bottom up. When we do these traversals other <redefine>'s may // perhaps be encountered; we leave recursion to sort this out. fCurrentSchemaInfo.restore(); traverseIncludedSchema(fSchemaRootElement); fNamespacesScope = (NamespacesScope)saveNSScope.clone(); // and last but not least: traverse our own <redefine>--the one all // this labour has been expended upon. for (Element child = XUtil.getFirstChildElement(redefineDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); // annotations can occur anywhere in <redefine>s! if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) { traverseAnnotationDecl(child); } else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE )) { traverseSimpleTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE )) { traverseComplexTypeDecl(child); } else if (name.equals(SchemaSymbols.ELT_GROUP)) { String dName = child.getAttribute(SchemaSymbols.ATT_NAME); if(fGroupNameRegistry.get(fTargetNSURIString +","+ dName) == null || ((fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName) != null) && !((Boolean)fRestrictedRedefinedGroupRegistry.get(fTargetNSURIString+","+dName)).booleanValue())) { // extension! traverseGroupDecl(child); continue; } traverseGroupDecl(child); Integer bCSIndexObj = null; try { bCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString +","+ dName+redefIdentifier); } catch(ClassCastException c) { // if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema. // REVISIT: localize reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>"); continue; } if(bCSIndexObj != null) { // we have something! int bCSIndex = bCSIndexObj.intValue(); Integer dCSIndexObj; try { dCSIndexObj = (Integer)fGroupNameRegistry.get(fTargetNSURIString+","+dName); } catch (ClassCastException c) { continue; } if(dCSIndexObj == null) // something went wrong... continue; int dCSIndex = dCSIndexObj.intValue(); try { checkParticleDerivationOK(dCSIndex, -1, bCSIndex, -1, null); } catch (ParticleRecoverableError e) { reportGenericSchemaError(e.getMessage()); } } else // REVISIT: localize reportGenericSchemaError("src-redefine.6.2: a <group> within a <redefine> must either have a ref to a <group> with the same name or must restrict such an <group>"); } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { if(fRedefineAttributeGroupMap != null) { String dName = child.getAttribute(SchemaSymbols.ATT_NAME); Object [] bAttGrpStore = null; try { bAttGrpStore = (Object [])fRedefineAttributeGroupMap.get(dName); } catch(ClassCastException c) { // if it's still a String, then we mustn't have found a corresponding attributeGroup in the redefined schema. // REVISIT: localize reportGenericSchemaError("src-redefine.7.2: an <attributeGroup> within a <redefine> must either have a ref to an <attributeGroup> with the same name or must restrict such an <attributeGroup>"); continue; } if(bAttGrpStore != null) { // we have something! ComplexTypeInfo bTypeInfo = (ComplexTypeInfo)bAttGrpStore[0]; SchemaGrammar bSchemaGrammar = (SchemaGrammar)bAttGrpStore[1]; Vector bAnyAttDecls = (Vector)bAttGrpStore[2]; XMLAttributeDecl bAnyAttDecl = (bAnyAttDecls.size()>0 )? (XMLAttributeDecl)bAnyAttDecls.elementAt(0):null; ComplexTypeInfo dTypeInfo = new ComplexTypeInfo(); int templateElementNameIndex = fStringPool.addSymbol("$"+dName); int dTypeNameIndex = fStringPool.addSymbol("%"+dName); dTypeInfo.scopeDefined = -2; dTypeInfo.contentSpecHandle = -1; dTypeInfo.contentType = XMLElementDecl.TYPE_SIMPLE; dTypeInfo.datatypeValidator = null; dTypeInfo.templateElementIndex = fSchemaGrammar.addElementDecl( new QName(-1, templateElementNameIndex,dTypeNameIndex,fTargetNSURI), (fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : -2, dTypeInfo.scopeDefined, dTypeInfo.contentType, dTypeInfo.contentSpecHandle, -1, dTypeInfo.datatypeValidator); Vector dAnyAttDecls = new Vector(); XMLAttributeDecl dAnyAttDecl = (dAnyAttDecls.size()>0 )? (XMLAttributeDecl)dAnyAttDecls.elementAt(0):null; traverseAttributeGroupDecl(child, dTypeInfo, dAnyAttDecls); dTypeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex( dTypeInfo.templateElementIndex); try { checkAttributesDerivationOKRestriction(dTypeInfo.attlistHead,fSchemaGrammar, dAnyAttDecl,bTypeInfo.attlistHead,bSchemaGrammar,bAnyAttDecl); } catch (ComplexTypeRecoverableError e) { String message = e.getMessage(); reportGenericSchemaError("src-redefine.7.2: redefinition failed because of " + message); } continue; } } traverseAttributeGroupDecl(child, null, null); } // no else; error reported in the previous traversal } //for // and restore the original globals fCurrentSchemaInfo = fCurrentSchemaInfo.getPrev(); fCurrentSchemaInfo.restore(); } // traverseRedefine // the purpose of this method is twofold: 1. To find and appropriately modify all information items // in redefinedSchema with names that are redefined by children of // redefineDecl. 2. To make sure the redefine element represented by // redefineDecl is valid as far as content goes and with regard to // properly referencing components to be redefined. No traversing is done here! // This method also takes actions to find and, if necessary, modify the names // of elements in <redefine>'s in the schema that's being redefined. private void renameRedefinedComponents(Element redefineDecl, Element schemaToRedefine, SchemaInfo currSchemaInfo) throws Exception { for (Element child = XUtil.getFirstChildElement(redefineDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (name.equals(SchemaSymbols.ELT_ANNOTATION) ) continue; else if (name.equals(SchemaSymbols.ELT_SIMPLETYPE)) { String typeName = child.getAttribute( SchemaSymbols.ATT_NAME ); if(fTraversedRedefineElements.contains(typeName)) continue; if(validateRedefineNameChange(SchemaSymbols.ELT_SIMPLETYPE, typeName, typeName+redefIdentifier, child)) { fixRedefinedSchema(SchemaSymbols.ELT_SIMPLETYPE, typeName, typeName+redefIdentifier, schemaToRedefine, currSchemaInfo); } } else if (name.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { String typeName = child.getAttribute( SchemaSymbols.ATT_NAME ); if(fTraversedRedefineElements.contains(typeName)) continue; if(validateRedefineNameChange(SchemaSymbols.ELT_COMPLEXTYPE, typeName, typeName+redefIdentifier, child)) { fixRedefinedSchema(SchemaSymbols.ELT_COMPLEXTYPE, typeName, typeName+redefIdentifier, schemaToRedefine, currSchemaInfo); } } else if (name.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { String baseName = child.getAttribute( SchemaSymbols.ATT_NAME ); if(fTraversedRedefineElements.contains(baseName)) continue; if(validateRedefineNameChange(SchemaSymbols.ELT_ATTRIBUTEGROUP, baseName, baseName+redefIdentifier, child)) { fixRedefinedSchema(SchemaSymbols.ELT_ATTRIBUTEGROUP, baseName, baseName+redefIdentifier, schemaToRedefine, currSchemaInfo); } } else if (name.equals(SchemaSymbols.ELT_GROUP)) { String baseName = child.getAttribute( SchemaSymbols.ATT_NAME ); if(fTraversedRedefineElements.contains(baseName)) continue; if(validateRedefineNameChange(SchemaSymbols.ELT_GROUP, baseName, baseName+redefIdentifier, child)) { fixRedefinedSchema(SchemaSymbols.ELT_GROUP, baseName, baseName+redefIdentifier, schemaToRedefine, currSchemaInfo); } } else { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("invalid top-level content for <redefine>"); return; } } // for } // renameRedefinedComponents // This function looks among the children of curr for an element of type elementSought. // If it finds one, it evaluates whether its ref attribute contains a reference // to originalName. If it does, it returns 1 + the value returned by // calls to itself on all other children. In all other cases it returns 0 plus // the sum of the values returned by calls to itself on curr's children. // It also resets the value of ref so that it will refer to the renamed type from the schema // being redefined. private int changeRedefineGroup(QName originalName, String elementSought, String newName, Element curr) throws Exception { int result = 0; for (Element child = XUtil.getFirstChildElement(curr); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (!name.equals(elementSought)) result += changeRedefineGroup(originalName, elementSought, newName, child); else { String ref = child.getAttribute( SchemaSymbols.ATT_REF ); if (!ref.equals("")) { String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if(originalName.equals(new QName(-1, fStringPool.addSymbol(localpart), fStringPool.addSymbol(localpart), fStringPool.addSymbol(uriStr)))) { if(prefix.equals("")) child.setAttribute(SchemaSymbols.ATT_REF, newName); else child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName); result++; if(elementSought.equals(SchemaSymbols.ELT_GROUP)) { String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS ); String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS ); if(!((maxOccurs.length() == 0 || maxOccurs.equals("1")) && (minOccurs.length() == 0 || minOccurs.equals("1")))) { //REVISIT: localize reportGenericSchemaError("src-redefine.6.1.2: the group " + ref + " which contains a reference to a group being redefined must have minOccurs = maxOccurs = 1"); } } } } // if ref was null some other stage of processing will flag the error } } return result; } // changeRedefineGroup // This simple function looks for the first occurrence of an eltLocalname // schema information item and appropriately changes the value of // its name or type attribute from oldName to newName. // Root contains the root of the schema being operated upon. // If it turns out that what we're looking for is in a <redefine> though, then we // just rename it--and it's reference--to be the same and wait until // renameRedefineDecls can get its hands on it and do it properly. private void fixRedefinedSchema(String eltLocalname, String oldName, String newName, Element schemaToRedefine, SchemaInfo currSchema) throws Exception { boolean foundIt = false; for (Element child = XUtil.getFirstChildElement(schemaToRedefine); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if(name.equals(SchemaSymbols.ELT_REDEFINE)) { // need to search the redefine decl... for (Element redefChild = XUtil.getFirstChildElement(child); redefChild != null; redefChild = XUtil.getNextSiblingElement(redefChild)) { String redefName = redefChild.getLocalName(); if (redefName.equals(eltLocalname) ) { String infoItemName = redefChild.getAttribute( SchemaSymbols.ATT_NAME ); if(!infoItemName.equals(oldName)) continue; else { // found it! foundIt = true; openRedefinedSchema(child, currSchema); if(!fRedefineSucceeded) return; NamespacesScope saveNSS = (NamespacesScope)fNamespacesScope.clone(); currSchema.restore(); if (validateRedefineNameChange(eltLocalname, oldName, newName+redefIdentifier, redefChild) && (currSchema.getNext() != null)) { currSchema.getNext().restore(); fixRedefinedSchema(eltLocalname, oldName, newName+redefIdentifier, fSchemaRootElement, currSchema.getNext()); } fNamespacesScope = saveNSS; redefChild.setAttribute( SchemaSymbols.ATT_NAME, newName ); // and we now know we will traverse this, so set fTraversedRedefineElements appropriately... fTraversedRedefineElements.addElement(newName); currSchema.restore(); fCurrentSchemaInfo = currSchema; break; } } } //for if (foundIt) break; } else if (name.equals(eltLocalname) ) { String infoItemName = child.getAttribute( SchemaSymbols.ATT_NAME ); if(!infoItemName.equals(oldName)) continue; else { // found it! foundIt = true; child.setAttribute( SchemaSymbols.ATT_NAME, newName ); break; } } } //for if(!foundIt) { fRedefineSucceeded = false; // REVISIT: localize reportGenericSchemaError("could not find a declaration in the schema to be redefined corresponding to " + oldName); } } // end fixRedefinedSchema // this method returns true if the redefine component is valid, and if // it was possible to revise it correctly. The definition of // correctly will depend on whether renameRedefineDecls // or fixRedefineSchema is the caller. // this method also prepends a prefix onto newName if necessary; newName will never contain one. private boolean validateRedefineNameChange(String eltLocalname, String oldName, String newName, Element child) throws Exception { if (eltLocalname.equals(SchemaSymbols.ELT_SIMPLETYPE)) { QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI); Element grandKid = XUtil.getFirstChildElement(child); if (grandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child"); } else { String grandKidName = grandKid.getLocalName(); if(grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = XUtil.getNextSiblingElement(grandKid); grandKidName = grandKid.getLocalName(); } if (grandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child"); } else if(!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a simpleType child of a <redefine> must have a restriction element as a child"); } else { String derivedBase = grandKid.getAttribute( SchemaSymbols.ATT_BASE ); QName processedDerivedBase = parseBase(derivedBase); if(!processedTypeName.equals(processedDerivedBase)) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("the base attribute of the restriction child of a simpleType child of a redefine must have the same value as the simpleType's type attribute"); } else { // now we have to do the renaming... String prefix = ""; int colonptr = derivedBase.indexOf(":"); if ( colonptr > 0) prefix = derivedBase.substring(0,colonptr) + ":"; grandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName ); return true; } } } } else if (eltLocalname.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { QName processedTypeName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI); Element grandKid = XUtil.getFirstChildElement(child); if (grandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild"); } else { if(grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = XUtil.getNextSiblingElement(grandKid); } if (grandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild"); } else { // have to go one more level down; let another pass worry whether complexType is valid. Element greatGrandKid = XUtil.getFirstChildElement(grandKid); if (greatGrandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild"); } else { String greatGrandKidName = greatGrandKid.getLocalName(); if(greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { greatGrandKid = XUtil.getNextSiblingElement(greatGrandKid); greatGrandKidName = greatGrandKid.getLocalName(); } if (greatGrandKid == null) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild"); } else if(!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) && !greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("a complexType child of a <redefine> must have a restriction or extension element as a grandchild"); } else { String derivedBase = greatGrandKid.getAttribute( SchemaSymbols.ATT_BASE ); QName processedDerivedBase = parseBase(derivedBase); if(!processedTypeName.equals(processedDerivedBase)) { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("the base attribute of the restriction or extension grandchild of a complexType child of a redefine must have the same value as the complexType's type attribute"); } else { // now we have to do the renaming... String prefix = ""; int colonptr = derivedBase.indexOf(":"); if ( colonptr > 0) prefix = derivedBase.substring(0,colonptr) + ":"; greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, prefix + newName ); return true; } } } } } } else if (eltLocalname.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI); int attGroupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child); if(attGroupRefsCount > 1) { fRedefineSucceeded = false; // REVISIT: localize reportGenericSchemaError("if an attributeGroup child of a <redefine> element contains an attributeGroup ref'ing itself, it must have exactly 1; this one has " + attGroupRefsCount); } else if (attGroupRefsCount == 1) { return true; } else fRedefineAttributeGroupMap.put(oldName, newName); } else if (eltLocalname.equals(SchemaSymbols.ELT_GROUP)) { QName processedBaseName = new QName(-1, fStringPool.addSymbol(oldName), fStringPool.addSymbol(oldName), fTargetNSURI); int groupRefsCount = changeRedefineGroup(processedBaseName, eltLocalname, newName, child); String restrictedName = newName.substring(0, newName.length()-redefIdentifier.length()); if(!fRedefineSucceeded) { fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false)); } if(groupRefsCount > 1) { fRedefineSucceeded = false; fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false)); // REVISIT: localize reportGenericSchemaError("if a group child of a <redefine> element contains a group ref'ing itself, it must have exactly 1; this one has " + groupRefsCount); } else if (groupRefsCount == 1) { fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(false)); return true; } else { fGroupNameRegistry.put(fTargetNSURIString + "," + oldName, newName); fRestrictedRedefinedGroupRegistry.put(fTargetNSURIString+","+restrictedName, new Boolean(true)); } } else { fRedefineSucceeded = false; // REVISIT: Localize reportGenericSchemaError("internal Xerces error; please submit a bug with schema as testcase"); } // if we get here then we must have reported an error and failed somewhere... return false; } // validateRedefineNameChange private void traverseImport(Element importDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_GLOBAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(importDecl, scope); checkContent(importDecl, XUtil.getFirstChildElement(importDecl), true); String location = importDecl.getAttribute(SchemaSymbols.ATT_SCHEMALOCATION); // expand it before passing it to the parser InputSource source = null; if (fEntityResolver != null) { source = fEntityResolver.resolveEntity("", location); } if (source == null) { location = expandSystemId(location, fCurrentSchemaURL); source = new InputSource(location); } else { // create a string for uniqueness of this imported schema in fImportLocations if (source.getPublicId () != null) location = source.getPublicId (); location += (',' + source.getSystemId ()); } if (fImportLocations.contains((Object)location)) { return; } fImportLocations.addElement((Object)location); // check to make sure we're not importing ourselves... if(source.getSystemId().equals(fCurrentSchemaURL)) { // REVISIT: localize return; } String namespaceString = importDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE); if(namespaceString.length() == 0) { if(fTargetNSURI == StringPool.EMPTY_STRING) { // REVISIT: localize reportGenericSchemaError("src-import.1.2: if the namespace attribute on an <import> element is not present, the <import>ing schema must have a targetNamespace"); } } else { if(fTargetNSURIString.equals(namespaceString.trim())) { // REVISIT: localize reportGenericSchemaError("src-import.1.1: the namespace attribute of an <import> element must not be the same as the targetNamespace of the <import>ing schema"); } } SchemaGrammar importedGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(namespaceString); if (importedGrammar == null) { importedGrammar = new SchemaGrammar(); } DOMParser parser = new IgnoreWhitespaceParser(); parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() { public void fatalError(SAXParseException ex) throws SAXException { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':').append(ex.getLineNumber()).append(':').append(ex.getColumnNumber()); String message = ex.getMessage(); if(message.toLowerCase().trim().endsWith("not found.")) { System.err.println("[Warning] "+ str.toString()+": "+ message); } else { // do standard thing System.err.println("[Fatal Error] "+ str.toString()+":"+message); throw ex; } } }); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://xml.org/sax/features/namespaces", true); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( source ); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar Element root = null; if (document != null) { root = document.getDocumentElement(); } if (root != null) { String targetNSURI = getTargetNamespaceString(root); if (!targetNSURI.equals(namespaceString) ) { // REVISIT: Localize reportGenericSchemaError("imported schema '"+location+"' has a different targetNameSpace '" +targetNSURI+"' from what is declared '"+namespaceString+"'."); } else { TraverseSchema impSchema = new TraverseSchema(root, fStringPool, importedGrammar, fGrammarResolver, fErrorReporter, location, fEntityResolver, fFullConstraintChecking, fGeneralAttrCheck); Enumeration ics = impSchema.fIdentityConstraints.keys(); while(ics.hasMoreElements()) { Object icsKey = ics.nextElement(); fIdentityConstraints.put(icsKey, impSchema.fIdentityConstraints.get(icsKey)); } Enumeration icNames = impSchema.fIdentityConstraintNames.keys(); while(icNames.hasMoreElements()) { String icsNameKey = (String)icNames.nextElement(); fIdentityConstraintNames.put(icsNameKey, impSchema.fIdentityConstraintNames.get(icsNameKey)); } } } else { reportGenericSchemaError("Could not get the doc root for imported Schema file: "+location); } } // utility method for finding the targetNamespace (and flagging errors if they occur) private String getTargetNamespaceString( Element root) throws Exception { String targetNSURI = ""; Attr targetNSAttr = root.getAttributeNode(SchemaSymbols.ATT_TARGETNAMESPACE); if(targetNSAttr != null) { targetNSURI=targetNSAttr.getValue(); if(targetNSURI.length() == 0) { // REVISIT: localize reportGenericSchemaError("sch-prop-correct.1: \"\" is not a legal value for the targetNamespace attribute; the attribute must either be absent or contain a nonempty value"); } } return targetNSURI; } // end getTargetNamespaceString(Element) /** * <annotation>(<appinfo> | <documentation>)*</annotation> * * @param annotationDecl: the DOM node corresponding to the <annotation> info item */ private void traverseAnnotationDecl(Element annotationDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(annotationDecl, scope); for(Element child = XUtil.getFirstChildElement(annotationDecl); child != null; child = XUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if(!((name.equals(SchemaSymbols.ELT_APPINFO)) || (name.equals(SchemaSymbols.ELT_DOCUMENTATION)))) { // REVISIT: Localize reportGenericSchemaError("an <annotation> can only contain <appinfo> and <documentation> elements"); } // General Attribute Checking attrValues = fGeneralAttrCheck.checkAttributes(child, scope); } } // // Evaluates content of Annotation if present. // // @param: elm - top element // @param: content - content must be annotation? or some other simple content // @param: isEmpty: -- true if the content allowed is (annotation?) only // false if must have some element (with possible preceding <annotation?>) // //REVISIT: this function should be used in all traverse* methods! private Element checkContent( Element elm, Element content, boolean isEmpty ) throws Exception { //isEmpty = true-> means content can be null! if ( content == null) { if (!isEmpty) { reportSchemaError(SchemaMessageProvider.ContentError, new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )}); } return null; } if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl( content ); content = XUtil.getNextSiblingElement(content); if (content == null ) { //must be followed by <simpleType?> if (!isEmpty) { reportSchemaError(SchemaMessageProvider.ContentError, new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )}); } return null; } if (content.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { reportSchemaError(SchemaMessageProvider.AnnotationError, new Object [] { elm.getAttribute( SchemaSymbols.ATT_NAME )}); return null; } //return null if expected only annotation?, else returns updated content } return content; } //@param: elm - top element //@param: baseTypeStr - type (base/itemType/memberTypes) //@param: baseRefContext: whether the caller is using this type as a base for restriction, union or list //return DatatypeValidator available for the baseTypeStr, null if not found or disallowed. // also throws an error if the base type won't allow itself to be used in this context. //REVISIT: this function should be used in some|all traverse* methods! private DatatypeValidator findDTValidator (Element elm, String baseTypeStr, int baseRefContext ) throws Exception{ int baseType = fStringPool.addSymbol( baseTypeStr ); String prefix = ""; DatatypeValidator baseValidator = null; String localpart = baseTypeStr; int colonptr = baseTypeStr.indexOf(":"); if ( colonptr > 0) { prefix = baseTypeStr.substring(0,colonptr); localpart = baseTypeStr.substring(colonptr+1); } String uri = resolvePrefixToURI(prefix); baseValidator = getDatatypeValidator(uri, localpart); if (baseValidator == null) { Element baseTypeNode = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { traverseSimpleTypeDecl( baseTypeNode ); baseValidator = getDatatypeValidator(uri, localpart); } } Integer finalValue; if ( baseValidator == null ) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { elm.getAttribute( SchemaSymbols.ATT_BASE ), elm.getAttribute(SchemaSymbols.ATT_NAME)}); } else { finalValue = (uri.equals("")? ((Integer)fSimpleTypeFinalRegistry.get(localpart)): ((Integer)fSimpleTypeFinalRegistry.get(uri + "," +localpart))); if((finalValue != null) && ((finalValue.intValue() & baseRefContext) != 0)) { //REVISIT: localize reportGenericSchemaError("the base type " + baseTypeStr + " does not allow itself to be used as the base for a restriction and/or as a type in a list and/or union"); return baseValidator; } } return baseValidator; } private void checkEnumerationRequiredNotation(String name, String type) throws Exception{ String localpart = type; int colonptr = type.indexOf(":"); if ( colonptr > 0) { localpart = type.substring(colonptr+1); } if (localpart.equals("NOTATION")) { reportGenericSchemaError("[enumeration-required-notation] It is an error for NOTATION to be used "+ "directly in a schema in element/attribute '"+name+"'"); } } // @used in traverseSimpleType // on return we need to pop the last simpleType name from // the name stack private int resetSimpleTypeNameStack(int returnValue){ if (!fSimpleTypeNameStack.empty()) { fSimpleTypeNameStack.pop(); } return returnValue; } // @used in traverseSimpleType // report an error cos-list-of-atomic and reset the last name of the list datatype we traversing private void reportCosListOfAtomic () throws Exception{ reportGenericSchemaError("cos-list-of-atomic: The itemType must have a {variety} of atomic or union (in which case all the {member type definitions} must be atomic)"); fListName=""; } // @used in traverseSimpleType // find if union datatype validator has list datatype member. private boolean isListDatatype (DatatypeValidator validator){ if (validator instanceof UnionDatatypeValidator) { Vector temp = ((UnionDatatypeValidator)validator).getBaseValidators(); for (int i=0;i<temp.size();i++) { if (temp.elementAt(i) instanceof ListDatatypeValidator) { return true; } if (temp.elementAt(i) instanceof UnionDatatypeValidator) { if (isListDatatype((DatatypeValidator)temp.elementAt(i))) { return true; } } } } return false; } /** * Traverse SimpleType declaration: * <simpleType * final = #all | list of (restriction, union or list) * id = ID * name = NCName> * Content: (annotation? , ((list | restriction | union))) * </simpleType> * traverse <list>|<restriction>|<union> * * @param simpleTypeDecl * @return */ private int traverseSimpleTypeDecl( Element simpleTypeDecl ) throws Exception { // General Attribute Checking int scope = isTopLevel(simpleTypeDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleTypeDecl, scope); String nameProperty = simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME ); String qualifiedName = nameProperty; //--------------------------------------------------- // set qualified name //--------------------------------------------------- if ( nameProperty.length() == 0) { // anonymous simpleType qualifiedName = "#S#"+(fSimpleTypeAnonCount++); fStringPool.addSymbol(qualifiedName); } else { if (fTargetNSURIString.length () != 0) { qualifiedName = fTargetNSURIString+","+qualifiedName; } fStringPool.addSymbol( nameProperty ); } //---------------------------------------------------------------------- //check if we have already traversed the same simpleType decl //---------------------------------------------------------------------- if (fDatatypeRegistry.getDatatypeValidator(qualifiedName)!=null) { return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName)); } else { if (fSimpleTypeNameStack.search(qualifiedName) != -1 ){ // cos-no-circular-unions && no circular definitions reportGenericSchemaError("cos-no-circular-unions: no circular definitions are allowed for an element '"+ nameProperty+"'"); return resetSimpleTypeNameStack(-1); } } //---------------------------------------------------------- // update _final_ registry //---------------------------------------------------------- Attr finalAttr = simpleTypeDecl.getAttributeNode(SchemaSymbols.ATT_FINAL); int finalProperty = 0; if(finalAttr != null) finalProperty = parseFinalSet(finalAttr.getValue()); else finalProperty = parseFinalSet(null); // if we have a nonzero final , store it in the hash... if(finalProperty != 0) fSimpleTypeFinalRegistry.put(qualifiedName, new Integer(finalProperty)); // ------------------------------- // remember name being traversed to // avoid circular definitions in union // ------------------------------- fSimpleTypeNameStack.push(qualifiedName); //---------------------------------------------------------------------- //annotation?,(list|restriction|union) //---------------------------------------------------------------------- Element content = XUtil.getFirstChildElement(simpleTypeDecl); content = checkContent(simpleTypeDecl, content, false); if (content == null) { return resetSimpleTypeNameStack(-1); } // General Attribute Checking scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope); //---------------------------------------------------------------------- //use content.getLocalName for the cases there "xsd:" is a prefix, ei. "xsd:list" //---------------------------------------------------------------------- String varietyProperty = content.getLocalName(); String baseTypeQNameProperty = null; Vector dTValidators = null; int size = 0; StringTokenizer unionMembers = null; boolean list = false; boolean union = false; boolean restriction = false; int numOfTypes = 0; //list/restriction = 1, union = "+" if (varietyProperty.equals(SchemaSymbols.ELT_LIST)) { //traverse List baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_ITEMTYPE ); list = true; if (fListName.length() != 0) { // parent is <list> datatype reportCosListOfAtomic(); return resetSimpleTypeNameStack(-1); } else { fListName = qualifiedName; } } else if (varietyProperty.equals(SchemaSymbols.ELT_RESTRICTION)) { //traverse Restriction baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_BASE ); restriction= true; } else if (varietyProperty.equals(SchemaSymbols.ELT_UNION)) { //traverse union union = true; baseTypeQNameProperty = content.getAttribute( SchemaSymbols.ATT_MEMBERTYPES); if (baseTypeQNameProperty.length() != 0) { unionMembers = new StringTokenizer( baseTypeQNameProperty ); size = unionMembers.countTokens(); } else { size = 1; //at least one must be seen as <simpleType> decl } dTValidators = new Vector (size, 2); } else { reportSchemaError(SchemaMessageProvider.FeatureUnsupported, new Object [] { varietyProperty }); return -1; } if(XUtil.getNextSiblingElement(content) != null) { // REVISIT: Localize reportGenericSchemaError("error in content of simpleType"); } int typeNameIndex; DatatypeValidator baseValidator = null; if ( baseTypeQNameProperty.length() == 0 ) { //--------------------------- //must 'see' <simpleType> //--------------------------- //content = {annotation?,simpleType?...} content = XUtil.getFirstChildElement(content); //check content (annotation?, ...) content = checkContent(simpleTypeDecl, content, false); if (content == null) { return resetSimpleTypeNameStack(-1); } if (content.getLocalName().equals( SchemaSymbols.ELT_SIMPLETYPE )) { typeNameIndex = traverseSimpleTypeDecl(content); if (typeNameIndex!=-1) { baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); if (baseValidator !=null && union) { dTValidators.addElement((DatatypeValidator)baseValidator); } } if ( typeNameIndex == -1 || baseValidator == null) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { content.getAttribute( SchemaSymbols.ATT_BASE ), content.getAttribute(SchemaSymbols.ATT_NAME) }); return resetSimpleTypeNameStack(-1); } } else { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); return resetSimpleTypeNameStack(-1); } } //end - must see simpleType? else { //----------------------------- //base was provided - get proper validator. //----------------------------- numOfTypes = 1; if (union) { numOfTypes= size; } //-------------------------------------------------------------------- // this loop is also where we need to find out whether the type being used as // a base (or itemType or whatever) allows such things. //-------------------------------------------------------------------- int baseRefContext = (restriction? SchemaSymbols.RESTRICTION:0); baseRefContext = baseRefContext | (union? SchemaSymbols.UNION:0); baseRefContext = baseRefContext | (list ? SchemaSymbols.LIST:0); for (int i=0; i<numOfTypes; i++) { //find all validators if (union) { baseTypeQNameProperty = unionMembers.nextToken(); } baseValidator = findDTValidator ( simpleTypeDecl, baseTypeQNameProperty, baseRefContext); if ( baseValidator == null) { return resetSimpleTypeNameStack(-1); } // ------------------------------ // (variety is list)cos-list-of-atomic // ------------------------------ if (fListName.length() != 0 ) { if (baseValidator instanceof ListDatatypeValidator) { reportCosListOfAtomic(); return resetSimpleTypeNameStack(-1); } //----------------------------------------------------- // if baseValidator is of type (union) need to look // at Union validators to make sure that List is not one of them //----------------------------------------------------- if (isListDatatype(baseValidator)) { reportCosListOfAtomic(); return resetSimpleTypeNameStack(-1); } } if (union) { dTValidators.addElement((DatatypeValidator)baseValidator); //add validator to structure } //REVISIT: Should we raise exception here? // if baseValidator.isInstanceOf(LIST) and UNION if ( list && (baseValidator instanceof UnionDatatypeValidator)) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ), simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)}); return -1; } } } //end - base is available // ------------------------------------------ // move to next child // <base==empty)->[simpleType]->[facets] OR // <base!=empty)->[facets] // ------------------------------------------ if (baseTypeQNameProperty.length() == 0) { content = XUtil.getNextSiblingElement( content ); } else { content = XUtil.getFirstChildElement(content); } // ------------------------------------------ //get more types for union if any // ------------------------------------------ if (union) { int index=size; if (baseTypeQNameProperty.length() != 0 ) { content = checkContent(simpleTypeDecl, content, true); } while (content!=null) { typeNameIndex = traverseSimpleTypeDecl(content); if (typeNameIndex!=-1) { baseValidator=fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); if (baseValidator != null) { if (fListName.length() != 0 && baseValidator instanceof ListDatatypeValidator) { reportCosListOfAtomic(); return resetSimpleTypeNameStack(-1); } dTValidators.addElement((DatatypeValidator)baseValidator); } } if ( baseValidator == null || typeNameIndex == -1) { reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_BASE ), simpleTypeDecl.getAttribute(SchemaSymbols.ATT_NAME)}); return (-1); } content = XUtil.getNextSiblingElement( content ); } } // end - traverse Union if (fListName.length() != 0) { // reset fListName, meaning that we are done with // traversing <list> and its itemType resolves to atomic value if (fListName.equals(qualifiedName)) { fListName = ""; } } int numFacets=0; fFacetData.clear(); if (restriction && content != null) { short flags = 0; // flag facets that have fixed="true" int numEnumerationLiterals = 0; Vector enumData = new Vector(); content = checkContent(simpleTypeDecl, content , true); StringBuffer pattern = null; String facet; while (content != null) { if (content.getNodeType() == Node.ELEMENT_NODE) { // General Attribute Checking contentAttrs = fGeneralAttrCheck.checkAttributes(content, scope); numFacets++; facet =content.getLocalName(); if (facet.equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; String enumVal = content.getAttribute(SchemaSymbols.ATT_VALUE); String localName; if (baseValidator instanceof NOTATIONDatatypeValidator) { String prefix = ""; String localpart = enumVal; int colonptr = enumVal.indexOf(":"); if ( colonptr > 0) { prefix = enumVal.substring(0,colonptr); localpart = enumVal.substring(colonptr+1); } String uriStr = (prefix.length() != 0)?resolvePrefixToURI(prefix):fTargetNSURIString; nameProperty=uriStr + ":" + localpart; localName = (String)fNotationRegistry.get(nameProperty); if(localName == null){ localName = traverseNotationFromAnotherSchema( localpart, uriStr); if (localName == null) { reportGenericSchemaError("Notation '" + localpart + "' not found in the grammar "+ uriStr); } } enumVal=nameProperty; } enumData.addElement(enumVal); checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true); } else if (facet.equals(SchemaSymbols.ELT_ANNOTATION) || facet.equals(SchemaSymbols.ELT_SIMPLETYPE)) { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); } else if (facet.equals(SchemaSymbols.ELT_PATTERN)) { if (pattern == null) { pattern = new StringBuffer (content.getAttribute( SchemaSymbols.ATT_VALUE )); } else { // --------------------------------------------- //datatypes: 5.2.4 pattern: src-multiple-pattern // --------------------------------------------- pattern.append("|"); pattern.append(content.getAttribute( SchemaSymbols.ATT_VALUE )); checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true); } } else { if ( fFacetData.containsKey(facet) ) reportSchemaError(SchemaMessageProvider.DatatypeError, new Object [] {"The facet '" + facet + "' is defined more than once."} ); fFacetData.put(facet,content.getAttribute( SchemaSymbols.ATT_VALUE )); if (content.getAttribute( SchemaSymbols.ATT_FIXED).equals("true") || content.getAttribute( SchemaSymbols.ATT_FIXED).equals("1")){ // -------------------------------------------- // set fixed facet flags // length - must remain const through derivation // thus we don't care if it fixed // -------------------------------------------- if ( facet.equals(SchemaSymbols.ELT_MINLENGTH) ) { flags |= DatatypeValidator.FACET_MINLENGTH; } else if (facet.equals(SchemaSymbols.ELT_MAXLENGTH)) { flags |= DatatypeValidator.FACET_MAXLENGTH; } else if (facet.equals(SchemaSymbols.ELT_MAXEXCLUSIVE)) { flags |= DatatypeValidator.FACET_MAXEXCLUSIVE; } else if (facet.equals(SchemaSymbols.ELT_MAXINCLUSIVE)) { flags |= DatatypeValidator.FACET_MAXINCLUSIVE; } else if (facet.equals(SchemaSymbols.ELT_MINEXCLUSIVE)) { flags |= DatatypeValidator.FACET_MINEXCLUSIVE; } else if (facet.equals(SchemaSymbols.ELT_MININCLUSIVE)) { flags |= DatatypeValidator.FACET_MININCLUSIVE; } else if (facet.equals(SchemaSymbols.ELT_TOTALDIGITS)) { flags |= DatatypeValidator.FACET_TOTALDIGITS; } else if (facet.equals(SchemaSymbols.ELT_FRACTIONDIGITS)) { flags |= DatatypeValidator.FACET_FRACTIONDIGITS; } else if (facet.equals(SchemaSymbols.ELT_WHITESPACE) && baseValidator instanceof StringDatatypeValidator) { flags |= DatatypeValidator.FACET_WHITESPACE; } } checkContent(simpleTypeDecl, XUtil.getFirstChildElement( content ), true); } } content = XUtil.getNextSiblingElement(content); } if (numEnumerationLiterals > 0) { fFacetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } if (pattern !=null) { fFacetData.put(SchemaSymbols.ELT_PATTERN, pattern.toString()); } if (flags != 0) { fFacetData.put(DatatypeValidator.FACET_FIXED, new Short(flags)); } } else if (list && content!=null) { // report error - must not have any children! if (baseTypeQNameProperty.length() != 0) { content = checkContent(simpleTypeDecl, content, true); if (content!=null) { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); } } else { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); //REVISIT: should we return? } } else if (union && content!=null) { //report error - must not have any children! if (baseTypeQNameProperty.length() != 0) { content = checkContent(simpleTypeDecl, content, true); if (content!=null) { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); } } else { reportSchemaError(SchemaMessageProvider.ListUnionRestrictionError, new Object [] { simpleTypeDecl.getAttribute( SchemaSymbols.ATT_NAME )}); //REVISIT: should we return? } } // ---------------------------------------------------------------------- // create & register validator for "generated" type if it doesn't exist // ---------------------------------------------------------------------- try { DatatypeValidator newValidator = fDatatypeRegistry.getDatatypeValidator( qualifiedName ); if( newValidator == null ) { // not previously registered if (list) { fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator, fFacetData,true); } else if (restriction) { fDatatypeRegistry.createDatatypeValidator( qualifiedName, baseValidator, fFacetData,false); } else { //union fDatatypeRegistry.createDatatypeValidator( qualifiedName, dTValidators); } } } catch (Exception e) { reportSchemaError(SchemaMessageProvider.DatatypeError,new Object [] { e.getMessage() }); } return resetSimpleTypeNameStack(fStringPool.addSymbol(qualifiedName)); } /* * <any * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * namespace = (##any | ##other) | List of (anyURI | (##targetNamespace | ##local)) * processContents = lax | skip | strict> * Content: (annotation?) * </any> */ private int traverseAny(Element child) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(child, scope); Element annotation = checkContent( child, XUtil.getFirstChildElement(child), true ); if(annotation != null ) { // REVISIT: Localize reportGenericSchemaError("<any> elements can contain at most one <annotation> element in their children"); } int anyIndex = -1; String namespace = child.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim(); String processContents = child.getAttribute("processContents").trim(); int processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY; int processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER; int processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS; if (processContents.length() > 0 && !processContents.equals("strict")) { if (processContents.equals("lax")) { processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_LAX; processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX; processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_LAX; } else if (processContents.equals("skip")) { processContentsAny = XMLContentSpec.CONTENTSPECNODE_ANY_SKIP; processContentsAnyOther = XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP; processContentsAnyLocal = XMLContentSpec.CONTENTSPECNODE_ANY_NS_SKIP; } } if (namespace.length() == 0 || namespace.equals("##any")) { anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAny, -1, StringPool.EMPTY_STRING, false); } else if (namespace.equals("##other")) { String uri = fTargetNSURIString; int uriIndex = fStringPool.addSymbol(uri); anyIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyOther, -1, uriIndex, false); } else if (namespace.length() > 0) { int uriIndex, leafIndex, choiceIndex; StringTokenizer tokenizer = new StringTokenizer(namespace); String token = tokenizer.nextToken(); if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) { choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false); } else { if (token.equals("##targetNamespace")) token = fTargetNSURIString; uriIndex = fStringPool.addSymbol(token); choiceIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false); } while (tokenizer.hasMoreElements()) { token = tokenizer.nextToken(); if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) { leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, StringPool.EMPTY_STRING, false); } else { if (token.equals("##targetNamespace")) token = fTargetNSURIString; uriIndex = fStringPool.addSymbol(token); leafIndex = fSchemaGrammar.addContentSpecNode(processContentsAnyLocal, -1, uriIndex, false); } choiceIndex = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, choiceIndex, leafIndex, false); } anyIndex = choiceIndex; } else { // REVISIT: Localize reportGenericSchemaError("Empty namespace attribute for any element"); } return anyIndex; } public DatatypeValidator getDatatypeValidator(String uri, String localpart) { DatatypeValidator dv = null; if (uri.length()==0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { dv = fDatatypeRegistry.getDatatypeValidator( localpart ); } else { dv = fDatatypeRegistry.getDatatypeValidator( uri+","+localpart ); } return dv; } /* * <anyAttribute * id = ID * namespace = ##any | ##other | ##local | list of {uri, ##targetNamespace}> * Content: (annotation?) * </anyAttribute> */ private XMLAttributeDecl traverseAnyAttribute(Element anyAttributeDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(anyAttributeDecl, scope); Element annotation = checkContent( anyAttributeDecl, XUtil.getFirstChildElement(anyAttributeDecl), true ); if(annotation != null ) { // REVISIT: Localize reportGenericSchemaError("<anyAttribute> elements can contain at most one <annotation> element in their children"); } XMLAttributeDecl anyAttDecl = new XMLAttributeDecl(); String processContents = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_PROCESSCONTENTS).trim(); String namespace = anyAttributeDecl.getAttribute(SchemaSymbols.ATT_NAMESPACE).trim(); // simplify! NG //String curTargetUri = anyAttributeDecl.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace"); String curTargetUri = fTargetNSURIString; if ( namespace.length() == 0 || namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDANY) ) { anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_ANY; } else if (namespace.equals(SchemaSymbols.ATTVAL_TWOPOUNDOTHER)) { anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_OTHER; anyAttDecl.name.uri = fStringPool.addSymbol(curTargetUri); } else if (namespace.length() > 0){ anyAttDecl.type = XMLAttributeDecl.TYPE_ANY_LIST; StringTokenizer tokenizer = new StringTokenizer(namespace); int aStringList = fStringPool.startStringList(); Vector tokens = new Vector(); int tokenStr; while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDLOCAL)) { tokenStr = fStringPool.EMPTY_STRING; } else { if (token.equals(SchemaSymbols.ATTVAL_TWOPOUNDTARGETNS)) token = curTargetUri; tokenStr = fStringPool.addSymbol(token); } if (!fStringPool.addStringToList(aStringList, tokenStr)){ reportGenericSchemaError("Internal StringPool error when reading the "+ "namespace attribute for anyattribute declaration"); } } fStringPool.finishStringList(aStringList); anyAttDecl.enumeration = aStringList; } else { // REVISIT: Localize reportGenericSchemaError("Empty namespace attribute for anyattribute declaration"); } // default processContents is "strict"; if (processContents.equals(SchemaSymbols.ATTVAL_SKIP)){ anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_SKIP; } else if (processContents.equals(SchemaSymbols.ATTVAL_LAX)) { anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_LAX; } else { anyAttDecl.defaultType |= XMLAttributeDecl.PROCESSCONTENTS_STRICT; } return anyAttDecl; } // Schema Component Constraint: Attribute Wildcard Intersection // For a wildcard's {namespace constraint} value to be the intensional intersection of two other such values (call them O1 and O2): the appropriate case among the following must be true: // 1 If O1 and O2 are the same value, then that value must be the value. // 2 If either O1 or O2 is any, then the other must be the value. // 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or �absent�), then that set, minus the negated namespace name if it was in the set, must be the value. // 4 If both O1 and O2 are sets of (namespace names or �absent�), then the intersection of those sets must be the value. // 5 If the two are negations of different namespace names, then the intersection is not expressible. // In the case where there are more than two values, the intensional intersection is determined by identifying the intensional intersection of two of the values as above, then the intensional intersection of that value with the third (providing the first intersection was expressible), and so on as required. private XMLAttributeDecl AWildCardIntersection(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) { // if either one is not expressible, the result is still not expressible if (oneAny.type == -1) { return oneAny; } if (anotherAny.type == -1) { return anotherAny; } // 1 If O1 and O2 are the same value, then that value must be the value. // this one is dealt with in different branches // 2 If either O1 or O2 is any, then the other must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return anotherAny; } if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return oneAny; } // 3 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or �absent�), then that set, minus the negated namespace name if it was in the set, must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST || oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST && anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { XMLAttributeDecl anyList, anyOther; if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { anyList = oneAny; anyOther = anotherAny; } else { anyList = anotherAny; anyOther = oneAny; } int[] uriList = fStringPool.stringListAsIntArray(anyList.enumeration); if (elementInSet(anyOther.name.uri, uriList)) { int newList = fStringPool.startStringList(); for (int i=0; i< uriList.length; i++) { if (uriList[i] != anyOther.name.uri ) { fStringPool.addStringToList(newList, uriList[i]); } } fStringPool.finishStringList(newList); anyList.enumeration = newList; } return anyList; } // 4 If both O1 and O2 are sets of (namespace names or �absent�), then the intersection of those sets must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST && anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { int[] result = intersect2sets(fStringPool.stringListAsIntArray(oneAny.enumeration), fStringPool.stringListAsIntArray(anotherAny.enumeration)); int newList = fStringPool.startStringList(); for (int i=0; i<result.length; i++) { fStringPool.addStringToList(newList, result[i]); } fStringPool.finishStringList(newList); oneAny.enumeration = newList; return oneAny; } // 5 If the two are negations of different namespace names, then the intersection is not expressible. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { if (oneAny.name.uri == anotherAny.name.uri) { return oneAny; } else { oneAny.type = -1; return oneAny; } } // should never go there; return oneAny; } // Schema Component Constraint: Attribute Wildcard Union // For a wildcard's {namespace constraint} value to be the intensional union of two other such values (call them O1 and O2): the appropriate case among the following must be true: // 1 If O1 and O2 are the same value, then that value must be the value. // 2 If either O1 or O2 is any, then any must be the value. // 3 If both O1 and O2 are sets of (namespace names or �absent�), then the union of those sets must be the value. // 4 If the two are negations of different namespace names, then any must be the value. // 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or �absent�), then The appropriate case among the following must be true: // 5.1 If the set includes the negated namespace name, then any must be the value. // 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value. // In the case where there are more than two values, the intensional union is determined by identifying the intensional union of two of the values as above, then the intensional union of that value with the third, and so on as required. private XMLAttributeDecl AWildCardUnion(XMLAttributeDecl oneAny, XMLAttributeDecl anotherAny) { // if either one is not expressible, the result is still not expressible if (oneAny.type == -1) { return oneAny; } if (anotherAny.type == -1) { return anotherAny; } // 1 If O1 and O2 are the same value, then that value must be the value. // this one is dealt with in different branches // 2 If either O1 or O2 is any, then any must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return oneAny; } if (anotherAny.type == XMLAttributeDecl.TYPE_ANY_ANY) { return anotherAny; } // 3 If both O1 and O2 are sets of (namespace names or �absent�), then the union of those sets must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST && anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { int[] result = union2sets(fStringPool.stringListAsIntArray(oneAny.enumeration), fStringPool.stringListAsIntArray(anotherAny.enumeration)); int newList = fStringPool.startStringList(); for (int i=0; i<result.length; i++) { fStringPool.addStringToList(newList, result[i]); } fStringPool.finishStringList(newList); oneAny.enumeration = newList; return oneAny; } // 4 If the two are negations of different namespace names, then any must be the value. if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { if (oneAny.name.uri == anotherAny.name.uri) { return oneAny; } else { oneAny.type = XMLAttributeDecl.TYPE_ANY_ANY; return oneAny; } } // 5 If either O1 or O2 is a pair of not and a namespace name and the other is a set of (namespace names or �absent�), then The appropriate case among the following must be true: if (oneAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && anotherAny.type == XMLAttributeDecl.TYPE_ANY_LIST || oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST && anotherAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { XMLAttributeDecl anyList, anyOther; if (oneAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { anyList = oneAny; anyOther = anotherAny; } else { anyList = anotherAny; anyOther = oneAny; } // 5.1 If the set includes the negated namespace name, then any must be the value. if (elementInSet(anyOther.name.uri, fStringPool.stringListAsIntArray(anyList.enumeration))) { anyOther.type = XMLAttributeDecl.TYPE_ANY_ANY; } // 5.2 If the set does not include the negated namespace name, then whichever of O1 or O2 is a pair of not and a namespace name must be the value. return anyOther; } // should never go there; return oneAny; } // Schema Component Constraint: Wildcard Subset // For a namespace constraint (call it sub) to be an intensional subset of another namespace constraint (call it super) one of the following must be true: // 1 super must be any. // 2 All of the following must be true: // 2.1 sub must be a pair of not and a namespace name or �absent�. // 2.2 super must be a pair of not and the same value. // 3 All of the following must be true: // 3.1 sub must be a set whose members are either namespace names or �absent�. // 3.2 One of the following must be true: // 3.2.1 super must be the same set or a superset thereof. // 3.2.2 super must be a pair of not and a namespace name or �absent� and that value must not be in sub's set. private boolean AWildCardSubset(XMLAttributeDecl subAny, XMLAttributeDecl superAny) { // if either one is not expressible, it can't be a subset if (subAny.type == -1 || superAny.type == -1) return false; // 1 super must be any. if (superAny.type == XMLAttributeDecl.TYPE_ANY_ANY) return true; // 2 All of the following must be true: // 2.1 sub must be a pair of not and a namespace name or �absent�. if (subAny.type == XMLAttributeDecl.TYPE_ANY_OTHER) { // 2.2 super must be a pair of not and the same value. if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && subAny.name.uri == superAny.name.uri) { return true; } } // 3 All of the following must be true: // 3.1 sub must be a set whose members are either namespace names or �absent�. if (subAny.type == XMLAttributeDecl.TYPE_ANY_LIST) { // 3.2 One of the following must be true: // 3.2.1 super must be the same set or a superset thereof. if (superAny.type == XMLAttributeDecl.TYPE_ANY_LIST && subset2sets(fStringPool.stringListAsIntArray(subAny.enumeration), fStringPool.stringListAsIntArray(superAny.enumeration))) { return true; } // 3.2.2 super must be a pair of not and a namespace name or �absent� and that value must not be in sub's set. if (superAny.type == XMLAttributeDecl.TYPE_ANY_OTHER && !elementInSet(superAny.name.uri, fStringPool.stringListAsIntArray(superAny.enumeration))) { return true; } } return false; } // Validation Rule: Wildcard allows Namespace Name // For a value which is either a namespace name or �absent� to be �valid� with respect to a wildcard constraint (the value of a {namespace constraint}) one of the following must be true: // 1 The constraint must be any. // 2 All of the following must be true: // 2.1 The constraint is a pair of not and a namespace name or �absent� ([Definition:] call this the namespace test). // 2.2 The value must not be identical to the �namespace test�. // 2.3 The value must not be �absent�. // 3 The constraint is a set, and the value is identical to one of the members of the set. private boolean AWildCardAllowsNameSpace(XMLAttributeDecl wildcard, String uri) { // if the constrain is not expressible, then nothing is allowed if (wildcard.type == -1) return false; // 1 The constraint must be any. if (wildcard.type == XMLAttributeDecl.TYPE_ANY_ANY) return true; int uriStr = fStringPool.addString(uri); // 2 All of the following must be true: // 2.1 The constraint is a pair of not and a namespace name or �absent� ([Definition:] call this the namespace test). if (wildcard.type == XMLAttributeDecl.TYPE_ANY_OTHER) { // 2.2 The value must not be identical to the �namespace test�. // 2.3 The value must not be �absent�. if (uriStr != wildcard.name.uri && uriStr != StringPool.EMPTY_STRING) return true; } // 3 The constraint is a set, and the value is identical to one of the members of the set. if (wildcard.type == XMLAttributeDecl.TYPE_ANY_LIST) { if (elementInSet(uriStr, fStringPool.stringListAsIntArray(wildcard.enumeration))) return true; } return false; } private boolean isAWildCard(XMLAttributeDecl a) { if (a.type == XMLAttributeDecl.TYPE_ANY_ANY ||a.type == XMLAttributeDecl.TYPE_ANY_LIST ||a.type == XMLAttributeDecl.TYPE_ANY_OTHER ) return true; else return false; } int[] intersect2sets(int[] one, int[] theOther){ int[] result = new int[(one.length>theOther.length?one.length:theOther.length)]; // simple implemention, int count = 0; for (int i=0; i<one.length; i++) { if (elementInSet(one[i], theOther)) result[count++] = one[i]; } int[] result2 = new int[count]; System.arraycopy(result, 0, result2, 0, count); return result2; } int[] union2sets(int[] one, int[] theOther){ int[] result1 = new int[one.length]; // simple implemention, int count = 0; for (int i=0; i<one.length; i++) { if (!elementInSet(one[i], theOther)) result1[count++] = one[i]; } int[] result2 = new int[count+theOther.length]; System.arraycopy(result1, 0, result2, 0, count); System.arraycopy(theOther, 0, result2, count, theOther.length); return result2; } boolean subset2sets(int[] subSet, int[] superSet){ for (int i=0; i<subSet.length; i++) { if (!elementInSet(subSet[i], superSet)) return false; } return true; } boolean elementInSet(int ele, int[] set){ boolean found = false; for (int i=0; i<set.length && !found; i++) { if (ele==set[i]) found = true; } return found; } // wrapper traverseComplexTypeDecl method private int traverseComplexTypeDecl( Element complexTypeDecl ) throws Exception { return traverseComplexTypeDecl (complexTypeDecl, false); } /** * Traverse ComplexType Declaration - Rec Implementation. * * <complexType * abstract = boolean * block = #all or (possibly empty) subset of {extension, restriction} * final = #all or (possibly empty) subset of {extension, restriction} * id = ID * mixed = boolean : false * name = NCName> * Content: (annotation? , (simpleContent | complexContent | * ( (group | all | choice | sequence)? , * ( (attribute | attributeGroup)* , anyAttribute?)))) * </complexType> * @param complexTypeDecl * @param forwardRef * @return */ private int traverseComplexTypeDecl( Element complexTypeDecl, boolean forwardRef) throws Exception { // General Attribute Checking int scope = isTopLevel(complexTypeDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexTypeDecl, scope); // ------------------------------------------------------------------ // Get the attributes of the type // ------------------------------------------------------------------ String isAbstract = complexTypeDecl.getAttribute( SchemaSymbols.ATT_ABSTRACT ); String blockSet = null; Attr blockAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_BLOCK ); if (blockAttr != null) blockSet = blockAttr.getValue(); String finalSet = null; Attr finalAttr = complexTypeDecl.getAttributeNode( SchemaSymbols.ATT_FINAL ); if (finalAttr != null) finalSet = finalAttr.getValue(); String typeId = complexTypeDecl.getAttribute( SchemaSymbols.ATTVAL_ID ); String typeName = complexTypeDecl.getAttribute(SchemaSymbols.ATT_NAME); String mixed = complexTypeDecl.getAttribute(SchemaSymbols.ATT_MIXED); boolean isNamedType = false; // ------------------------------------------------------------------ // Generate a type name, if one wasn't specified // ------------------------------------------------------------------ if (typeName.equals("")) { // gensym a unique name typeName = genAnonTypeName(complexTypeDecl); } if ( DEBUGGING ) System.out.println("traversing complex Type : " + typeName); fCurrentTypeNameStack.push(typeName); int typeNameIndex = fStringPool.addSymbol(typeName); // ------------------------------------------------------------------ // Check if the type has already been registered // ------------------------------------------------------------------ if (isTopLevel(complexTypeDecl)) { String fullName = fTargetNSURIString+","+typeName; ComplexTypeInfo temp = (ComplexTypeInfo) fComplexTypeRegistry.get(fullName); if (temp != null ) { // check for duplicate declarations if (!forwardRef) { if (temp.declSeen()) reportGenericSchemaError("sch-props-correct: Duplicate declaration for complexType " + typeName); else temp.setDeclSeen(); } return fStringPool.addSymbol(fullName); } else { // check if the type is the name of a simple type if (getDatatypeValidator(fTargetNSURIString,typeName)!=null) reportGenericSchemaError("sch-props-correct: Duplicate type declaration - type is " + typeName); } } int scopeDefined = fScopeCount++; int previousScope = fCurrentScope; fCurrentScope = scopeDefined; Element child = null; ComplexTypeInfo typeInfo = new ComplexTypeInfo(); try { // ------------------------------------------------------------------ // First, handle any ANNOTATION declaration and get next child // ------------------------------------------------------------------ child = checkContent(complexTypeDecl,XUtil.getFirstChildElement(complexTypeDecl), true); // ------------------------------------------------------------------ // Process the content of the complex type declaration // ------------------------------------------------------------------ if (child==null) { // // EMPTY complexType with complexContent // processComplexContent(typeNameIndex, child, typeInfo, null, false); } else { String childName = child.getLocalName(); int index = -2; if (childName.equals(SchemaSymbols.ELT_SIMPLECONTENT)) { // // SIMPLE CONTENT element // traverseSimpleContentDecl(typeNameIndex, child, typeInfo); if (XUtil.getNextSiblingElement(child) != null) throw new ComplexTypeRecoverableError( "Invalid child following the simpleContent child in the complexType"); } else if (childName.equals(SchemaSymbols.ELT_COMPLEXCONTENT)) { // // COMPLEX CONTENT element // traverseComplexContentDecl(typeNameIndex, child, typeInfo, mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false); if (XUtil.getNextSiblingElement(child) != null) throw new ComplexTypeRecoverableError( "Invalid child following the complexContent child in the complexType"); } else { // // We must have .... // GROUP, ALL, SEQUENCE or CHOICE, followed by optional attributes // Note that it's possible that only attributes are specified. // processComplexContent(typeNameIndex, child, typeInfo, null, mixed.equals(SchemaSymbols.ATTVAL_TRUE) ? true:false); } } typeInfo.blockSet = parseBlockSet(blockSet); // make sure block's value was absent, #all or in {extension, restriction} if( (blockSet != null ) && !blockSet.equals("") && (!blockSet.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((typeInfo.blockSet & SchemaSymbols.RESTRICTION) == 0) && ((typeInfo.blockSet & SchemaSymbols.EXTENSION) == 0)))) throw new ComplexTypeRecoverableError("The values of the 'block' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + blockSet + " was found"); typeInfo.finalSet = parseFinalSet(finalSet); // make sure final's value was absent, #all or in {extension, restriction} if( (finalSet != null ) && !finalSet.equals("") && (!finalSet.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((typeInfo.finalSet & SchemaSymbols.RESTRICTION) == 0) && ((typeInfo.finalSet & SchemaSymbols.EXTENSION) == 0)))) throw new ComplexTypeRecoverableError("The values of the 'final' attribute of a complexType must be either #all or a list of 'restriction' and 'extension'; " + finalSet + " was found"); } catch (ComplexTypeRecoverableError e) { String message = e.getMessage(); handleComplexTypeError(message,typeNameIndex,typeInfo); } // ------------------------------------------------------------------ // Finish the setup of the typeInfo and register the type // ------------------------------------------------------------------ typeInfo.scopeDefined = scopeDefined; if (isAbstract.equals(SchemaSymbols.ATTVAL_TRUE)) typeInfo.setIsAbstractType(); if (!forwardRef) typeInfo.setDeclSeen(); typeName = fTargetNSURIString + "," + typeName; typeInfo.typeName = new String(typeName); if ( DEBUGGING ) System.out.println(">>>add complex Type to Registry: " + typeName + " baseDTValidator=" + typeInfo.baseDataTypeValidator + " baseCTInfo=" + typeInfo.baseComplexTypeInfo + " derivedBy=" + typeInfo.derivedBy + " contentType=" + typeInfo.contentType + " contentSpecHandle=" + typeInfo.contentSpecHandle + " datatypeValidator=" + typeInfo.datatypeValidator + " scopeDefined=" + typeInfo.scopeDefined); fComplexTypeRegistry.put(typeName,typeInfo); // ------------------------------------------------------------------ // Before exiting, restore the scope, mainly for nested anonymous types // ------------------------------------------------------------------ fCurrentScope = previousScope; fCurrentTypeNameStack.pop(); checkRecursingComplexType(); //set template element's typeInfo fSchemaGrammar.setElementComplexTypeInfo(typeInfo.templateElementIndex, typeInfo); typeNameIndex = fStringPool.addSymbol(typeName); return typeNameIndex; } // end traverseComplexTypeDecl /** * Traverse SimpleContent Declaration * * <simpleContent * id = ID * {any attributes with non-schema namespace...}> * * Content: (annotation? , (restriction | extension)) * </simpleContent> * * <restriction * base = QNAME * id = ID * {any attributes with non-schema namespace...}> * * Content: (annotation?,(simpleType?, (minExclusive|minInclusive|maxExclusive * | maxInclusive | totalDigits | fractionDigits | length | minLength * | maxLength | encoding | period | duration | enumeration * | pattern | whiteSpace)*) ? , * ((attribute | attributeGroup)* , anyAttribute?)) * </restriction> * * <extension * base = QNAME * id = ID * {any attributes with non-schema namespace...}> * Content: (annotation? , ((attribute | attributeGroup)* , anyAttribute?)) * </extension> * * @param typeNameIndex * @param simpleContentTypeDecl * @param typeInfo * @return */ private void traverseSimpleContentDecl(int typeNameIndex, Element simpleContentDecl, ComplexTypeInfo typeInfo) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(simpleContentDecl, scope); String typeName = fStringPool.toString(typeNameIndex); // ----------------------------------------------------------------------- // Get attributes. // ----------------------------------------------------------------------- String simpleContentTypeId = simpleContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID); // ----------------------------------------------------------------------- // Set the content type to be simple, and initialize content spec handle // ----------------------------------------------------------------------- typeInfo.contentType = XMLElementDecl.TYPE_SIMPLE; typeInfo.contentSpecHandle = -1; Element simpleContent = checkContent(simpleContentDecl, XUtil.getFirstChildElement(simpleContentDecl),false); // If there are no children, return if (simpleContent==null) { throw new ComplexTypeRecoverableError(); } // General Attribute Checking attrValues = fGeneralAttrCheck.checkAttributes(simpleContent, scope); // ----------------------------------------------------------------------- // The content should be either "restriction" or "extension" // ----------------------------------------------------------------------- String simpleContentName = simpleContent.getLocalName(); if (simpleContentName.equals(SchemaSymbols.ELT_RESTRICTION)) typeInfo.derivedBy = SchemaSymbols.RESTRICTION; else if (simpleContentName.equals(SchemaSymbols.ELT_EXTENSION)) typeInfo.derivedBy = SchemaSymbols.EXTENSION; else { throw new ComplexTypeRecoverableError( "The content of the simpleContent element is invalid. The " + "content must be RESTRICTION or EXTENSION"); } // ----------------------------------------------------------------------- // Get the attributes of the restriction/extension element // ----------------------------------------------------------------------- String base = simpleContent.getAttribute(SchemaSymbols.ATT_BASE); String typeId = simpleContent.getAttribute(SchemaSymbols.ATTVAL_ID); // ----------------------------------------------------------------------- // Skip over any annotations in the restriction or extension elements // ----------------------------------------------------------------------- Element content = checkContent(simpleContent, XUtil.getFirstChildElement(simpleContent),true); // ----------------------------------------------------------------------- // Handle the base type name // ----------------------------------------------------------------------- if (base.length() == 0) { throw new ComplexTypeRecoverableError( "The BASE attribute must be specified for the " + "RESTRICTION or EXTENSION element"); } QName baseQName = parseBase(base); // check if we're extending a simpleType which has a "final" setting which precludes this Integer finalValue = (baseQName.uri == StringPool.EMPTY_STRING? ((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.localpart))): ((Integer)fSimpleTypeFinalRegistry.get(fStringPool.toString(baseQName.uri) + "," +fStringPool.toString(baseQName.localpart)))); if(finalValue != null && (finalValue.intValue() == typeInfo.derivedBy)) throw new ComplexTypeRecoverableError( "The simpleType " + base + " that " + typeName + " uses has a value of \"final\" which does not permit extension"); processBaseTypeInfo(baseQName,typeInfo); // check that the base isn't a complex type with complex content if (typeInfo.baseComplexTypeInfo != null) { if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_SIMPLE) { throw new ComplexTypeRecoverableError( "The type '"+ base +"' specified as the " + "base in the simpleContent element must not have complexContent"); } } // ----------------------------------------------------------------------- // Process the content of the derivation // ----------------------------------------------------------------------- Element attrNode = null; // // RESTRICTION // if (typeInfo.derivedBy==SchemaSymbols.RESTRICTION) { // //Schema Spec : Complex Type Definition Properties Correct : 2 // if (typeInfo.baseDataTypeValidator != null) { throw new ComplexTypeRecoverableError( "ct-props-correct.2: The type '" + base +"' is a simple type. It cannot be used in a "+ "derivation by RESTRICTION for a complexType"); } else { typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator; } // // Check that the base's final set does not include RESTRICTION // if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0) { throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + base + " or the schema"); } // ----------------------------------------------------------------------- // There may be a simple type definition in the restriction element // The data type validator will be based on it, if specified // ----------------------------------------------------------------------- if (content.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE )) { int simpleTypeNameIndex = traverseSimpleTypeDecl(content); if (simpleTypeNameIndex!=-1) { DatatypeValidator dv=fDatatypeRegistry.getDatatypeValidator( fStringPool.toString(simpleTypeNameIndex)); //check that this datatype validator is validly derived from the base //according to derivation-ok-restriction 5.1.1 if (!checkSimpleTypeDerivationOK(dv,typeInfo.baseDataTypeValidator)) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.5.1.1: The content type is not a valid restriction of the content type of the base"); } typeInfo.baseDataTypeValidator = dv; content = XUtil.getNextSiblingElement(content); } else { throw new ComplexTypeRecoverableError(); } } // // Build up facet information // int numEnumerationLiterals = 0; int numFacets = 0; Hashtable facetData = new Hashtable(); Vector enumData = new Vector(); Element child; // General Attribute Checking scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable contentAttrs; //REVISIT: there is a better way to do this, for (child = content; child != null && (child.getLocalName().equals(SchemaSymbols.ELT_MINEXCLUSIVE) || child.getLocalName().equals(SchemaSymbols.ELT_MININCLUSIVE) || child.getLocalName().equals(SchemaSymbols.ELT_MAXEXCLUSIVE) || child.getLocalName().equals(SchemaSymbols.ELT_MAXINCLUSIVE) || child.getLocalName().equals(SchemaSymbols.ELT_TOTALDIGITS) || child.getLocalName().equals(SchemaSymbols.ELT_FRACTIONDIGITS) || child.getLocalName().equals(SchemaSymbols.ELT_LENGTH) || child.getLocalName().equals(SchemaSymbols.ELT_MINLENGTH) || child.getLocalName().equals(SchemaSymbols.ELT_MAXLENGTH) || child.getLocalName().equals(SchemaSymbols.ELT_PERIOD) || child.getLocalName().equals(SchemaSymbols.ELT_DURATION) || child.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION) || child.getLocalName().equals(SchemaSymbols.ELT_PATTERN) || child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)); child = XUtil.getNextSiblingElement(child)) { if ( child.getNodeType() == Node.ELEMENT_NODE ) { Element facetElt = (Element) child; // General Attribute Checking contentAttrs = fGeneralAttrCheck.checkAttributes(facetElt, scope); numFacets++; if (facetElt.getLocalName().equals(SchemaSymbols.ELT_ENUMERATION)) { numEnumerationLiterals++; enumData.addElement(facetElt.getAttribute(SchemaSymbols.ATT_VALUE)); //Enumerations can have annotations ? ( 0 | 1 ) Element enumContent = XUtil.getFirstChildElement( facetElt ); if( enumContent != null && enumContent.getLocalName().equals ( SchemaSymbols.ELT_ANNOTATION )){ traverseAnnotationDecl( child ); } // TO DO: if Jeff check in new changes to TraverseSimpleType, copy them over } else { facetData.put(facetElt.getLocalName(), facetElt.getAttribute( SchemaSymbols.ATT_VALUE )); } } } // end of for loop thru facets if (numEnumerationLiterals > 0) { facetData.put(SchemaSymbols.ELT_ENUMERATION, enumData); } // // If there were facets, create a new data type validator, otherwise // the data type validator is from the base // if (numFacets > 0) { try{ typeInfo.datatypeValidator = fDatatypeRegistry.createDatatypeValidator( typeName, typeInfo.baseDataTypeValidator, facetData, false); } catch (Exception e) { throw new ComplexTypeRecoverableError(e.getMessage()); } } else typeInfo.datatypeValidator = typeInfo.baseDataTypeValidator; if (child != null) { // // Check that we have attributes // if (!isAttrOrAttrGroup(child)) { throw new ComplexTypeRecoverableError( "Invalid child in the RESTRICTION element of simpleContent"); } else attrNode = child; } } // end RESTRICTION // // EXTENSION // else { if (typeInfo.baseComplexTypeInfo != null) { typeInfo.baseDataTypeValidator = typeInfo.baseComplexTypeInfo.datatypeValidator; // // Check that the base's final set does not include EXTENSION // if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.EXTENSION) != 0) { throw new ComplexTypeRecoverableError("Derivation by extension is forbidden by either the base type " + base + " or the schema"); } } typeInfo.datatypeValidator = typeInfo.baseDataTypeValidator; // // Look for attributes // if (content != null) { // // Check that we have attributes // if (!isAttrOrAttrGroup(content)) { throw new ComplexTypeRecoverableError( "Only annotations and attributes are allowed in the " + "content of an EXTENSION element for a complexType with simpleContent"); } else { attrNode = content; } } } // ----------------------------------------------------------------------- // add a template element to the grammar element decl pool for the type // ----------------------------------------------------------------------- int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl( new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined, typeInfo.contentType, typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex( typeInfo.templateElementIndex); // ----------------------------------------------------------------------- // Process attributes // ----------------------------------------------------------------------- processAttributes(attrNode,baseQName,typeInfo); if (XUtil.getNextSiblingElement(simpleContent) != null) throw new ComplexTypeRecoverableError( "Invalid child following the RESTRICTION or EXTENSION element in the " + "complex type definition"); } // end traverseSimpleContentDecl /** * Traverse complexContent Declaration * * <complexContent * id = ID * mixed = boolean * {any attributes with non-schema namespace...}> * * Content: (annotation? , (restriction | extension)) * </complexContent> * * <restriction * base = QNAME * id = ID * {any attributes with non-schema namespace...}> * * Content: (annotation? , (group | all | choice | sequence)?, * ((attribute | attributeGroup)* , anyAttribute?)) * </restriction> * * <extension * base = QNAME * id = ID * {any attributes with non-schema namespace...}> * Content: (annotation? , (group | all | choice | sequence)?, * ((attribute | attributeGroup)* , anyAttribute?)) * </extension> * * @param typeNameIndex * @param simpleContentTypeDecl * @param typeInfo * @param mixedOnComplexTypeDecl * @return */ private void traverseComplexContentDecl(int typeNameIndex, Element complexContentDecl, ComplexTypeInfo typeInfo, boolean mixedOnComplexTypeDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(complexContentDecl, scope); String typeName = fStringPool.toString(typeNameIndex); // ----------------------------------------------------------------------- // Get the attributes // ----------------------------------------------------------------------- String typeId = complexContentDecl.getAttribute(SchemaSymbols.ATTVAL_ID); String mixed = complexContentDecl.getAttribute(SchemaSymbols.ATT_MIXED); // ----------------------------------------------------------------------- // Determine whether the content is mixed, or element-only // Setting here overrides any setting on the complex type decl // ----------------------------------------------------------------------- boolean isMixed = mixedOnComplexTypeDecl; if (mixed.equals(SchemaSymbols.ATTVAL_TRUE)) isMixed = true; else if (mixed.equals(SchemaSymbols.ATTVAL_FALSE)) isMixed = false; // ----------------------------------------------------------------------- // Since the type must have complex content, set the simple type validators // to null // ----------------------------------------------------------------------- typeInfo.datatypeValidator = null; typeInfo.baseDataTypeValidator = null; Element complexContent = checkContent(complexContentDecl, XUtil.getFirstChildElement(complexContentDecl),false); // If there are no children, return if (complexContent==null) { throw new ComplexTypeRecoverableError(); } // ----------------------------------------------------------------------- // The content should be either "restriction" or "extension" // ----------------------------------------------------------------------- String complexContentName = complexContent.getLocalName(); if (complexContentName.equals(SchemaSymbols.ELT_RESTRICTION)) typeInfo.derivedBy = SchemaSymbols.RESTRICTION; else if (complexContentName.equals(SchemaSymbols.ELT_EXTENSION)) typeInfo.derivedBy = SchemaSymbols.EXTENSION; else { throw new ComplexTypeRecoverableError( "The content of the complexContent element is invalid. " + "The content must be RESTRICTION or EXTENSION"); } // Get the attributes of the restriction/extension element String base = complexContent.getAttribute(SchemaSymbols.ATT_BASE); String complexContentTypeId=complexContent.getAttribute(SchemaSymbols.ATTVAL_ID); // Skip over any annotations in the restriction or extension elements Element content = checkContent(complexContent, XUtil.getFirstChildElement(complexContent),true); // ----------------------------------------------------------------------- // Handle the base type name // ----------------------------------------------------------------------- if (base.length() == 0) { throw new ComplexTypeRecoverableError( "The BASE attribute must be specified for the " + "RESTRICTION or EXTENSION element"); } QName baseQName = parseBase(base); // ------------------------------------------------------------- // check if the base is "anyType" // ------------------------------------------------------------- String baseTypeURI = fStringPool.toString(baseQName.uri); String baseLocalName = fStringPool.toString(baseQName.localpart); if (!(baseTypeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && baseLocalName.equals("anyType"))) { processBaseTypeInfo(baseQName,typeInfo); //Check that the base is a complex type if (typeInfo.baseComplexTypeInfo == null) { throw new ComplexTypeRecoverableError( "The base type specified in the complexContent element must be a complexType"); } } // ----------------------------------------------------------------------- // Process the elements that make up the content // ----------------------------------------------------------------------- processComplexContent(typeNameIndex,content,typeInfo,baseQName,isMixed); if (XUtil.getNextSiblingElement(complexContent) != null) throw new ComplexTypeRecoverableError( "Invalid child following the RESTRICTION or EXTENSION element in the " + "complex type definition"); } // end traverseComplexContentDecl /** * Handle complexType error * * @param message * @param typeNameIndex * @param typeInfo * @return */ private void handleComplexTypeError(String message, int typeNameIndex, ComplexTypeInfo typeInfo) throws Exception { String typeName = fStringPool.toString(typeNameIndex); if (message != null) { if (typeName.startsWith("#")) reportGenericSchemaError("Anonymous complexType: " + message); else reportGenericSchemaError("ComplexType '" + typeName + "': " + message); } // // Mock up the typeInfo structure so that there won't be problems during // validation // typeInfo.contentType = XMLElementDecl.TYPE_ANY; // this should match anything typeInfo.contentSpecHandle = -1; typeInfo.derivedBy = 0; typeInfo.datatypeValidator = null; typeInfo.attlistHead = -1; int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl( new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined, typeInfo.contentType, typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator); return; } /** * Generate a name for an anonymous type * * @param Element * @return String */ private String genAnonTypeName(Element complexTypeDecl) throws Exception { String typeName; // If the anonymous type is not nested within another type, we can // simply assign the type a numbered name // if (fCurrentTypeNameStack.empty()) typeName = "#"+fAnonTypeCount++; // Otherwise, we must generate a name that can be looked up later // Do this by concatenating outer type names with the name of the parent // element else { String parentName = ((Element)complexTypeDecl.getParentNode()).getAttribute( SchemaSymbols.ATT_NAME); typeName = parentName + "_AnonType"; int index=fCurrentTypeNameStack.size() -1; for (int i = index; i > -1; i--) { String parentType = (String)fCurrentTypeNameStack.elementAt(i); typeName = parentType + "_" + typeName; if (!(parentType.startsWith("#"))) break; } typeName = "#" + typeName; } return typeName; } /** * Parse base string * * @param base * @return QName */ private QName parseBase(String base) throws Exception { String prefix = ""; String localpart = base; int colonptr = base.indexOf(":"); if ( colonptr > 0) { prefix = base.substring(0,colonptr); localpart = base.substring(colonptr+1); } int nameIndex = fStringPool.addSymbol(base); int prefixIndex = fStringPool.addSymbol(prefix); int localpartIndex = fStringPool.addSymbol(localpart); int URIindex = fStringPool.addSymbol(resolvePrefixToURI(prefix)); return new QName(prefixIndex,localpartIndex,nameIndex,URIindex); } /** * Check if base is from another schema * * @param baseName * @return boolean */ private boolean baseFromAnotherSchema(QName baseName) throws Exception { String typeURI = fStringPool.toString(baseName.uri); if ( ! typeURI.equals(fTargetNSURIString) && ! typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0 ) //REVISIT, !!!! a hack: for schema that has no //target namespace, e.g. personal-schema.xml return true; else return false; } /** * Process "base" information for a complexType * * @param baseTypeInfo * @param baseName * @param typeInfo * @return */ private void processBaseTypeInfo(QName baseName, ComplexTypeInfo typeInfo) throws Exception { ComplexTypeInfo baseComplexTypeInfo = null; DatatypeValidator baseDTValidator = null; String typeURI = fStringPool.toString(baseName.uri); String localpart = fStringPool.toString(baseName.localpart); String base = fStringPool.toString(baseName.rawname); // ------------------------------------------------------------- // check if the base type is from another schema // ------------------------------------------------------------- if (baseFromAnotherSchema(baseName)) { baseComplexTypeInfo = getTypeInfoFromNS(typeURI, localpart); if (baseComplexTypeInfo == null) { baseDTValidator = getTypeValidatorFromNS(typeURI, localpart); if (baseDTValidator == null) { throw new ComplexTypeRecoverableError( "Could not find base type " +localpart + " in schema " + typeURI); } } } // ------------------------------------------------------------- // type must be from same schema // ------------------------------------------------------------- else { String fullBaseName = typeURI+","+localpart; // assume the base is a complexType and try to locate the base type first baseComplexTypeInfo= (ComplexTypeInfo) fComplexTypeRegistry.get(fullBaseName); // if not found, 2 possibilities: // 1: ComplexType in question has not been compiled yet; // 2: base is SimpleTYpe; if (baseComplexTypeInfo == null) { baseDTValidator = getDatatypeValidator(typeURI, localpart); if (baseDTValidator == null) { int baseTypeSymbol; Element baseTypeNode = getTopLevelComponentByName( SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (baseTypeNode != null) { // Before traversing the base, make sure we're not already // doing so.. // ct-props-correct 3 if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { throw new ComplexTypeRecoverableError( "ct-props-correct.3: Recursive type definition"); } baseTypeSymbol = traverseComplexTypeDecl( baseTypeNode, true ); baseComplexTypeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(baseTypeSymbol)); //REVISIT: should it be fullBaseName; } else { baseTypeNode = getTopLevelComponentByName( SchemaSymbols.ELT_SIMPLETYPE, localpart); if (baseTypeNode != null) { baseTypeSymbol = traverseSimpleTypeDecl( baseTypeNode ); baseDTValidator = getDatatypeValidator(typeURI, localpart); if (baseDTValidator == null) { //TO DO: signal error here. } } else { throw new ComplexTypeRecoverableError( "Base type could not be found : " + base); } } } } } // end else (type must be from same schema) typeInfo.baseComplexTypeInfo = baseComplexTypeInfo; typeInfo.baseDataTypeValidator = baseDTValidator; } // end processBaseTypeInfo /** * Process content which is complex * * (group | all | choice | sequence) ? , * ((attribute | attributeGroup)* , anyAttribute?)) * * @param typeNameIndex * @param complexContentChild * @param typeInfo * @return */ private void processComplexContent(int typeNameIndex, Element complexContentChild, ComplexTypeInfo typeInfo, QName baseName, boolean isMixed) throws Exception { Element attrNode = null; int index=-2; String typeName = fStringPool.toString(typeNameIndex); if (complexContentChild != null) { // ------------------------------------------------------------- // GROUP, ALL, SEQUENCE or CHOICE, followed by attributes, if specified. // Note that it's possible that only attributes are specified. // ------------------------------------------------------------- String childName = complexContentChild.getLocalName(); if (childName.equals(SchemaSymbols.ELT_GROUP)) { int groupIndex = traverseGroupDecl(complexContentChild); index = handleOccurrences(groupIndex, complexContentChild, hasAllContent(groupIndex) ? GROUP_REF_WITH_ALL : NOT_ALL_CONTEXT); attrNode = XUtil.getNextSiblingElement(complexContentChild); } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = handleOccurrences(traverseSequence(complexContentChild), complexContentChild); attrNode = XUtil.getNextSiblingElement(complexContentChild); } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = handleOccurrences(traverseChoice(complexContentChild), complexContentChild); attrNode = XUtil.getNextSiblingElement(complexContentChild); } else if (childName.equals(SchemaSymbols.ELT_ALL)) { index = handleOccurrences(traverseAll(complexContentChild), complexContentChild, PROCESSING_ALL); attrNode = XUtil.getNextSiblingElement(complexContentChild); } else if (isAttrOrAttrGroup(complexContentChild)) { // reset the contentType typeInfo.contentType = XMLElementDecl.TYPE_ANY; attrNode = complexContentChild; } else { throw new ComplexTypeRecoverableError( "Invalid child '"+ childName +"' in the complex type"); } } typeInfo.contentSpecHandle = index; // ----------------------------------------------------------------------- // Merge in information from base, if it exists // ----------------------------------------------------------------------- if (typeInfo.baseComplexTypeInfo != null) { int baseContentSpecHandle = typeInfo.baseComplexTypeInfo.contentSpecHandle; //------------------------------------------------------------- // RESTRICTION //------------------------------------------------------------- if (typeInfo.derivedBy == SchemaSymbols.RESTRICTION) { // check to see if the baseType permits derivation by restriction if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.RESTRICTION) != 0) throw new ComplexTypeRecoverableError("Derivation by restriction is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema"); // if the content is EMPTY, check that the base is correct // according to derivation-ok-restriction 5.2 if (typeInfo.contentSpecHandle==-2) { if (!(typeInfo.baseComplexTypeInfo.contentType==XMLElementDecl.TYPE_EMPTY || particleEmptiable(baseContentSpecHandle))) { throw new ComplexTypeRecoverableError("derivation-ok-restrictoin.5.2 Content type of complexType is EMPTY but base is not EMPTY or does not have a particle which is emptiable"); } } // // The hairy derivation by restriction particle constraints // derivation-ok-restriction 5.3 // else { try { checkParticleDerivationOK(typeInfo.contentSpecHandle,fCurrentScope, baseContentSpecHandle,typeInfo.baseComplexTypeInfo.scopeDefined, typeInfo.baseComplexTypeInfo); } catch (ParticleRecoverableError e) { String message = e.getMessage(); throw new ComplexTypeRecoverableError(message); } } } //------------------------------------------------------------- // EXTENSION //------------------------------------------------------------- else { // check to see if the baseType permits derivation by extension if((typeInfo.baseComplexTypeInfo.finalSet & SchemaSymbols.EXTENSION) != 0) throw new ComplexTypeRecoverableError("cos-ct-extends.1.1: Derivation by extension is forbidden by either the base type " + fStringPool.toString(baseName.localpart) + " or the schema"); // // Check if the contentType of the base is consistent with the new type // cos-ct-extends.1.4.2.2 if (typeInfo.baseComplexTypeInfo.contentType != XMLElementDecl.TYPE_EMPTY) { if (((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_CHILDREN) && isMixed) || ((typeInfo.baseComplexTypeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX) && !isMixed)) { throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.2.2.1: The content type of the base type " + fStringPool.toString(baseName.localpart) + " and derived type " + typeName + " must both be mixed or element-only"); } } // // Compose the final content model by concatenating the base and the // current in sequence // if (baseFromAnotherSchema(baseName)) { String baseSchemaURI = fStringPool.toString(baseName.uri); SchemaGrammar aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar( baseSchemaURI); baseContentSpecHandle = importContentSpec(aGrammar, baseContentSpecHandle); } if (typeInfo.contentSpecHandle == -2) { typeInfo.contentSpecHandle = baseContentSpecHandle; } else if (baseContentSpecHandle > -1) { if (typeInfo.contentSpecHandle > -1 && (hasAllContent(typeInfo.contentSpecHandle) || hasAllContent(baseContentSpecHandle))) { throw new ComplexTypeRecoverableError("cos-all-limited: An \"all\" model group that is part of a complex type definition must constitute the entire {content type} of the definition."); } typeInfo.contentSpecHandle = fSchemaGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_SEQ, baseContentSpecHandle, typeInfo.contentSpecHandle, false); } // // Check that there is a particle in the final content // cos-ct-extends.1.4.2.1 // LM - commented out until I get a clarification from HT // if (typeInfo.contentSpecHandle <0) { throw new ComplexTypeRecoverableError("cos-ct-extends.1.4.2.1: The content of a type derived by EXTENSION must contain a particle"); } } } else { typeInfo.derivedBy = 0; } // ------------------------------------------------------------- // Set the content type // ------------------------------------------------------------- if (isMixed) { // if there are no children, detect an error // See the definition of content type in Structures 3.4.1 if (typeInfo.contentSpecHandle == -2) { throw new ComplexTypeRecoverableError("Type '" + typeName + "': The content of a mixed complexType must not be empty"); } else typeInfo.contentType = XMLElementDecl.TYPE_MIXED_COMPLEX; } else if (typeInfo.contentSpecHandle == -2) typeInfo.contentType = XMLElementDecl.TYPE_EMPTY; else typeInfo.contentType = XMLElementDecl.TYPE_CHILDREN; // ------------------------------------------------------------- // add a template element to the grammar element decl pool. // ------------------------------------------------------------- int templateElementNameIndex = fStringPool.addSymbol("$"+typeName); typeInfo.templateElementIndex = fSchemaGrammar.addElementDecl( new QName(-1, templateElementNameIndex,typeNameIndex,fTargetNSURI), (fTargetNSURI==StringPool.EMPTY_STRING) ? StringPool.EMPTY_STRING : fCurrentScope, typeInfo.scopeDefined, typeInfo.contentType, typeInfo.contentSpecHandle, -1, typeInfo.datatypeValidator); typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex( typeInfo.templateElementIndex); // ------------------------------------------------------------- // Now, check attributes and handle // ------------------------------------------------------------- if (attrNode !=null) { if (!isAttrOrAttrGroup(attrNode)) { throw new ComplexTypeRecoverableError( "Invalid child "+ attrNode.getLocalName() + " in the complexType or complexContent"); } else processAttributes(attrNode,baseName,typeInfo); } else if (typeInfo.baseComplexTypeInfo != null) processAttributes(null,baseName,typeInfo); } // end processComplexContent /** * Process attributes of a complex type * * @param attrNode * @param typeInfo * @return */ private void processAttributes(Element attrNode, QName baseName, ComplexTypeInfo typeInfo) throws Exception { XMLAttributeDecl attWildcard = null; Vector anyAttDecls = new Vector(); Element child; for (child = attrNode; child != null; child = XUtil.getNextSiblingElement(child)) { String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_ATTRIBUTE)) { traverseAttributeDecl(child, typeInfo, false); } else if ( childName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child,typeInfo,anyAttDecls); } else if ( childName.equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { attWildcard = traverseAnyAttribute(child); } else { throw new ComplexTypeRecoverableError( "Invalid child among the children of the complexType definition"); } } if (attWildcard != null) { XMLAttributeDecl fromGroup = null; final int count = anyAttDecls.size(); if ( count > 0) { fromGroup = (XMLAttributeDecl) anyAttDecls.elementAt(0); for (int i=1; i<count; i++) { fromGroup = AWildCardIntersection( fromGroup,(XMLAttributeDecl)anyAttDecls.elementAt(i)); } } if (fromGroup != null) { int saveProcessContents = attWildcard.defaultType; attWildcard = AWildCardIntersection(attWildcard, fromGroup); attWildcard.defaultType = saveProcessContents; } } else { //REVISIT: unclear in the Scheme Structures 4.3.3 what to do in this case if (anyAttDecls.size()>0) { attWildcard = (XMLAttributeDecl)anyAttDecls.elementAt(0); } } // // merge in base type's attribute decls // XMLAttributeDecl baseAttWildcard = null; ComplexTypeInfo baseTypeInfo = typeInfo.baseComplexTypeInfo; SchemaGrammar aGrammar=null; if (baseTypeInfo != null && baseTypeInfo.attlistHead > -1 ) { int attDefIndex = baseTypeInfo.attlistHead; aGrammar = fSchemaGrammar; String baseTypeSchemaURI = baseFromAnotherSchema(baseName)? fStringPool.toString(baseName.uri):null; if (baseTypeSchemaURI != null) { aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(baseTypeSchemaURI); } if (aGrammar == null) { //reportGenericSchemaError("In complexType "+typeName+", can NOT find the grammar "+ // "with targetNamespace" + baseTypeSchemaURI+ // "for the base type"); } else while ( attDefIndex > -1 ) { fTempAttributeDecl.clear(); aGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl); if (fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_ANY ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_LIST ||fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER ) { if (attWildcard == null) { baseAttWildcard = fTempAttributeDecl; } attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } // if found a duplicate, if it is derived by restriction, // then skip the one from the base type int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, fTempAttributeDecl.name); if ( temp > -1) { if (typeInfo.derivedBy==SchemaSymbols.EXTENSION) { reportGenericSchemaError("Attribute that appeared in the base should nnot appear in a derivation by extension"); } else { attDefIndex = fSchemaGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } } fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, fTempAttributeDecl.name, fTempAttributeDecl.type, fTempAttributeDecl.enumeration, fTempAttributeDecl.defaultType, fTempAttributeDecl.defaultValue, fTempAttributeDecl.datatypeValidator, fTempAttributeDecl.list); attDefIndex = aGrammar.getNextAttributeDeclIndex(attDefIndex); } } // att wildcard will inserted after all attributes were processed if (attWildcard != null) { if (attWildcard.type != -1) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attWildcard.name, attWildcard.type, attWildcard.enumeration, attWildcard.defaultType, attWildcard.defaultValue, attWildcard.datatypeValidator, attWildcard.list); } else { //REVISIT: unclear in Schema spec if should report error here. reportGenericSchemaError("The intensional intersection for {attribute wildcard}s must be expressible"); } } else if (baseAttWildcard != null) { fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, baseAttWildcard.name, baseAttWildcard.type, baseAttWildcard.enumeration, baseAttWildcard.defaultType, baseAttWildcard.defaultValue, baseAttWildcard.datatypeValidator, baseAttWildcard.list); } typeInfo.attlistHead = fSchemaGrammar.getFirstAttributeDeclIndex (typeInfo.templateElementIndex); // For derivation by restriction, ensure that the resulting attribute list // satisfies the constraints in derivation-ok-restriction 2,3,4 if ((typeInfo.derivedBy==SchemaSymbols.RESTRICTION) && (typeInfo.attlistHead>-1 && baseTypeInfo != null)) { checkAttributesDerivationOKRestriction(typeInfo.attlistHead,fSchemaGrammar, attWildcard,baseTypeInfo.attlistHead,aGrammar,baseAttWildcard); } } // end processAttributes // Check that the attributes of a type derived by restriction satisfy the // constraints of derivation-ok-restriction private void checkAttributesDerivationOKRestriction(int dAttListHead, SchemaGrammar dGrammar, XMLAttributeDecl dAttWildCard, int bAttListHead, SchemaGrammar bGrammar, XMLAttributeDecl bAttWildCard) throws ComplexTypeRecoverableError { int attDefIndex = dAttListHead; if (bAttListHead < 0) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.2: Base type definition does not have any attributes"); } // Loop thru the attributes while ( attDefIndex > -1 ) { fTempAttributeDecl.clear(); dGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl); if (isAWildCard(fTempAttributeDecl)) { attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex); continue; } int bAttDefIndex = bGrammar.findAttributeDecl(bAttListHead, fTempAttributeDecl.name); if (bAttDefIndex > -1) { fTemp2AttributeDecl.clear(); bGrammar.getAttributeDecl(bAttDefIndex, fTemp2AttributeDecl); // derivation-ok-restriction. Constraint 2.1.1 if ((fTemp2AttributeDecl.defaultType & XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) > 0 && (fTempAttributeDecl.defaultType & XMLAttributeDecl.DEFAULT_TYPE_REQUIRED) <= 0) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.1: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation has an inconsistent REQUIRED setting to that of attribute in base"); } // // derivation-ok-restriction. Constraint 2.1.2 // if (!(checkSimpleTypeDerivationOK( fTempAttributeDecl.datatypeValidator, fTemp2AttributeDecl.datatypeValidator))) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.2: Type of attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' in derivation must be a restriction of type of attribute in base"); } // // derivation-ok-restriction. Constraint 2.1.3 // if ((fTemp2AttributeDecl.defaultType & XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) { if (!((fTempAttributeDecl.defaultType & XMLAttributeDecl.DEFAULT_TYPE_FIXED) > 0) || !fTempAttributeDecl.defaultValue.equals(fTemp2AttributeDecl.defaultValue)) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.1.3: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' is either not fixed, or is not fixed with the same value as the attribute in the base"); } } } else { // // derivation-ok-restriction. Constraint 2.2 // if ((bAttWildCard==null) || !AWildCardAllowsNameSpace(bAttWildCard, dGrammar.getTargetNamespaceURI())) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.2.2: Attribute '" + fStringPool.toString(fTempAttributeDecl.name.localpart) + "' has a target namespace which is not valid with respect to a base type definition's wildcard or, the base does not contain a wildcard"); } } attDefIndex = dGrammar.getNextAttributeDeclIndex(attDefIndex); } // derivation-ok-restriction. Constraint 4 if (dAttWildCard!=null) { if (bAttWildCard==null) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.1: An attribute wildcard is present in the derived type, but not the base"); } if (!AWildCardSubset(dAttWildCard,bAttWildCard)) { throw new ComplexTypeRecoverableError("derivation-ok-restriction.4.2: The attribute wildcard in the derived type is not a valid subset of that in the base"); } } } private boolean isAttrOrAttrGroup(Element e) { String elementName = e.getLocalName(); if (elementName.equals(SchemaSymbols.ELT_ATTRIBUTE) || elementName.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) || elementName.equals(SchemaSymbols.ELT_ANYATTRIBUTE)) return true; else return false; } private void checkRecursingComplexType() throws Exception { if ( fCurrentTypeNameStack.empty() ) { if (! fElementRecurseComplex.isEmpty() ) { int count= fElementRecurseComplex.size(); for (int i = 0; i<count; i++) { ElementInfo eobj = (ElementInfo)fElementRecurseComplex.elementAt(i); int elementIndex = eobj.elementIndex; String typeName = eobj.typeName; ComplexTypeInfo typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fTargetNSURIString+","+typeName); if (typeInfo==null) { throw new Exception ( "Internal Error in void checkRecursingComplexType(). " ); } else { // update the element decl with info from the type fSchemaGrammar.getElementDecl(elementIndex, fTempElementDecl); fTempElementDecl.type = typeInfo.contentType; fTempElementDecl.contentSpecIndex = typeInfo.contentSpecHandle; fTempElementDecl.datatypeValidator = typeInfo.datatypeValidator; fSchemaGrammar.setElementDecl(elementIndex, fTempElementDecl); fSchemaGrammar.setFirstAttributeDeclIndex(elementIndex, typeInfo.attlistHead); fSchemaGrammar.setElementComplexTypeInfo(elementIndex,typeInfo); } } fElementRecurseComplex.removeAllElements(); } } } // Check that the particle defined by the derived ct tree is a valid restriction of // that specified by baseContentSpecIndex. derivedScope and baseScope are the // scopes of the particles, respectively. bInfo is supplied when the base particle // is from a base type definition, and may be null - it helps determine other scopes // that elements should be looked up in. private void checkParticleDerivationOK(int derivedContentSpecIndex, int derivedScope, int baseContentSpecIndex, int baseScope, ComplexTypeInfo bInfo) throws Exception { // Only do this if full checking is enabled if (!fFullConstraintChecking) return; // Check for pointless occurrences of all, choice, sequence. The result is the // contentspec which is not pointless. If the result is a non-pointless // group, Vector is filled in with the children of interest int csIndex1 = derivedContentSpecIndex; fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1); int csIndex2 = baseContentSpecIndex; fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2); Vector tempVector1 = new Vector(); Vector tempVector2 = new Vector(); if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ || tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_CHOICE || tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_ALL) { csIndex1 = checkForPointlessOccurrences(csIndex1,tempVector1); } if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ || tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_CHOICE || tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL) { csIndex2 = checkForPointlessOccurrences(csIndex2,tempVector2); } fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1); fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2); switch (tempContentSpec1.type & 0x0f) { case XMLContentSpec.CONTENTSPECNODE_LEAF: { switch (tempContentSpec2.type & 0x0f) { // Elt:Elt NameAndTypeOK case XMLContentSpec.CONTENTSPECNODE_LEAF: { checkNameAndTypeOK(csIndex1, derivedScope, csIndex2, baseScope, bInfo); return; } // Elt:Any NSCompat case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { checkNSCompat(csIndex1, derivedScope, csIndex2); return; } // Elt:All RecurseAsIfGroup case XMLContentSpec.CONTENTSPECNODE_CHOICE: case XMLContentSpec.CONTENTSPECNODE_SEQ: case XMLContentSpec.CONTENTSPECNODE_ALL: { checkRecurseAsIfGroup(csIndex1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } default: { throw new ParticleRecoverableError("internal Xerces error"); } } } case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { switch (tempContentSpec2.type & 0x0f) { // Any:Any NSSubset case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { checkNSSubset(csIndex1, csIndex2); return; } case XMLContentSpec.CONTENTSPECNODE_CHOICE: case XMLContentSpec.CONTENTSPECNODE_SEQ: case XMLContentSpec.CONTENTSPECNODE_ALL: case XMLContentSpec.CONTENTSPECNODE_LEAF: { throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Any: Choice,Seq,All,Elt"); } default: { throw new ParticleRecoverableError("internal Xerces error"); } } } case XMLContentSpec.CONTENTSPECNODE_ALL: { switch (tempContentSpec2.type & 0x0f) { // All:Any NSRecurseCheckCardinality case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2); return; } case XMLContentSpec.CONTENTSPECNODE_ALL: { checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } case XMLContentSpec.CONTENTSPECNODE_CHOICE: case XMLContentSpec.CONTENTSPECNODE_SEQ: case XMLContentSpec.CONTENTSPECNODE_LEAF: { throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: All:Choice,Seq,Elt"); } default: { throw new ParticleRecoverableError("internal Xerces error"); } } } case XMLContentSpec.CONTENTSPECNODE_CHOICE: { switch (tempContentSpec2.type & 0x0f) { // Choice:Any NSRecurseCheckCardinality case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2); return; } case XMLContentSpec.CONTENTSPECNODE_CHOICE: { checkRecurseLax(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } case XMLContentSpec.CONTENTSPECNODE_ALL: case XMLContentSpec.CONTENTSPECNODE_SEQ: case XMLContentSpec.CONTENTSPECNODE_LEAF: { throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Choice:All,Seq,Leaf"); } default: { throw new ParticleRecoverableError("internal Xerces error"); } } } case XMLContentSpec.CONTENTSPECNODE_SEQ: { switch (tempContentSpec2.type & 0x0f) { // Choice:Any NSRecurseCheckCardinality case XMLContentSpec.CONTENTSPECNODE_ANY: case XMLContentSpec.CONTENTSPECNODE_ANY_OTHER: case XMLContentSpec.CONTENTSPECNODE_ANY_NS: { checkNSRecurseCheckCardinality(csIndex1, tempVector1, derivedScope, csIndex2); return; } case XMLContentSpec.CONTENTSPECNODE_ALL: { checkRecurseUnordered(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } case XMLContentSpec.CONTENTSPECNODE_SEQ: { checkRecurse(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } case XMLContentSpec.CONTENTSPECNODE_CHOICE: { checkMapAndSum(csIndex1, tempVector1, derivedScope, csIndex2, tempVector2, baseScope, bInfo); return; } case XMLContentSpec.CONTENTSPECNODE_LEAF: { throw new ParticleRecoverableError("cos-particle-restrict: Forbidden restriction: Seq:Elt"); } default: { throw new ParticleRecoverableError("internal Xerces error"); } } } } } private int checkForPointlessOccurrences(int csIndex, Vector tempVector) { // Note: instead of using a Vector, we should use a growable array of int. // To be cleaned up in release 1.4.1. (LM) fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); if (tempContentSpec1.otherValue == -2) { gatherChildren(tempContentSpec1.type,tempContentSpec1.value,tempVector); if (tempVector.size() == 1) { Integer returnVal = (Integer)(tempVector.elementAt(0)); return returnVal.intValue(); } } int type = tempContentSpec1.type; int value = tempContentSpec1.value; int otherValue = tempContentSpec1.otherValue; gatherChildren(type,value, tempVector); gatherChildren(type,otherValue, tempVector); return csIndex; } private void gatherChildren(int parentType, int csIndex, Vector tempVector) { fSchemaGrammar.getContentSpec(csIndex, tempContentSpec1); int min = fSchemaGrammar.getContentSpecMinOccurs(csIndex); int max = fSchemaGrammar.getContentSpecMaxOccurs(csIndex); int left = tempContentSpec1.value; int right = tempContentSpec1.otherValue; int type = tempContentSpec1.type; if (type == XMLContentSpec.CONTENTSPECNODE_LEAF || (type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY || (type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_NS || (type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER ) { tempVector.addElement(new Integer(csIndex)); } else if (! (min==1 && max==1)) { tempVector.addElement(new Integer(csIndex)); } else if (right == -2) { gatherChildren(type,left,tempVector); } else if (parentType == type) { gatherChildren(type,left,tempVector); gatherChildren(type,right,tempVector); } else { tempVector.addElement(new Integer(csIndex)); } } private void checkNameAndTypeOK(int csIndex1, int derivedScope, int csIndex2, int baseScope, ComplexTypeInfo bInfo) throws Exception { fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1); fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2); int localpart1 = tempContentSpec1.value; int uri1 = tempContentSpec1.otherValue; int localpart2 = tempContentSpec2.value; int uri2 = tempContentSpec2.otherValue; int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); //start the checking... if (!(localpart1==localpart2 && uri1==uri2)) { // we have non-matching names. Check substitution groups. if (fSComp == null) fSComp = new SubstitutionGroupComparator(fGrammarResolver,fStringPool,fErrorReporter); if (!checkSubstitutionGroups(localpart1,uri1,localpart2,uri2)) throw new ParticleRecoverableError("rcase-nameAndTypeOK.1: Element name/uri in restriction does not match that of corresponding base element"); } if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.3: Element occurrence range not a restriction of base element's range: element is " + fStringPool.toString(localpart1)); } SchemaGrammar aGrammar = fSchemaGrammar; // get the element decl indices for the remainder... String schemaURI = fStringPool.toString(uri1); if ( !schemaURI.equals(fTargetNSURIString) && schemaURI.length() != 0 ) aGrammar= (SchemaGrammar) fGrammarResolver.getGrammar(schemaURI); int eltndx1 = findElement(derivedScope, localpart1, aGrammar, null); if (eltndx1 < 0) return; int eltndx2 = findElement(baseScope, localpart2, aGrammar, bInfo); if (eltndx2 < 0) return; int miscFlags1 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx1); int miscFlags2 = ((SchemaGrammar) aGrammar).getElementDeclMiscFlags(eltndx2); boolean element1IsNillable = (miscFlags1 & SchemaSymbols.NILLABLE) !=0; boolean element2IsNillable = (miscFlags2 & SchemaSymbols.NILLABLE) !=0; boolean element2IsFixed = (miscFlags2 & SchemaSymbols.FIXED) !=0; boolean element1IsFixed = (miscFlags1 & SchemaSymbols.FIXED) !=0; String element1Value = aGrammar.getElementDefaultValue(eltndx1); String element2Value = aGrammar.getElementDefaultValue(eltndx2); if (! (element2IsNillable || !element1IsNillable)) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.2: Element " +fStringPool.toString(localpart1) + " is nillable in the restriction but not the base"); } if (! (element2Value == null || !element2IsFixed || (element1IsFixed && element1Value.equals(element2Value)))) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.4: Element " +fStringPool.toString(localpart1) + " is either not fixed, or is not fixed with the same value as in the base"); } // check disallowed substitutions int blockSet1 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx1); int blockSet2 = ((SchemaGrammar) aGrammar).getElementDeclBlockSet(eltndx2); if (((blockSet1 & blockSet2)!=blockSet2) || (blockSet1==0 && blockSet2!=0)) throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Element " +fStringPool.toString(localpart1) + "'s disallowed subsitutions are not a superset of those of the base element's"); // Need element decls for the remainder of the checks aGrammar.getElementDecl(eltndx1, fTempElementDecl); aGrammar.getElementDecl(eltndx2, fTempElementDecl2); // check identity constraints checkIDConstraintRestriction(fTempElementDecl, fTempElementDecl2, aGrammar, localpart1, localpart2); // check that the derived element's type is derived from the base's. - TO BE DONE checkTypesOK(fTempElementDecl,fTempElementDecl2,eltndx1,eltndx2,aGrammar,fStringPool.toString(localpart1)); } private void checkTypesOK(XMLElementDecl derived, XMLElementDecl base, int dndx, int bndx, SchemaGrammar aGrammar, String elementName) throws Exception { ComplexTypeInfo tempType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(dndx); if (derived.type == XMLElementDecl.TYPE_SIMPLE ) { if (base.type != XMLElementDecl.TYPE_SIMPLE) throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derive from that of the base"); if (tempType == null) { if (!(checkSimpleTypeDerivationOK(derived.datatypeValidator, base.datatypeValidator))) throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base"); return; } } ComplexTypeInfo bType=((SchemaGrammar)aGrammar).getElementComplexTypeInfo(bndx); for(; tempType != null; tempType = tempType.baseComplexTypeInfo) { if (tempType.derivedBy != SchemaSymbols.RESTRICTION) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base"); } if (tempType.typeName.equals(bType.typeName)) break; } if(tempType == null) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.6: Derived element " + elementName + " has a type that does not derives from that of the base"); } } private void checkIDConstraintRestriction(XMLElementDecl derivedElemDecl, XMLElementDecl baseElemDecl, SchemaGrammar grammar, int derivedElemName, int baseElemName) throws Exception { // this method throws no errors if the ID constraints on // the derived element are a logical subset of those on the // base element--that is, those that are present are // identical to ones in the base element. Vector derivedUnique = derivedElemDecl.unique; Vector baseUnique = baseElemDecl.unique; if(derivedUnique.size() > baseUnique.size()) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has fewer <unique> Identity Constraints than the base element"+ fStringPool.toString(baseElemName)); } else { boolean found = true; for(int i=0; i<derivedUnique.size() && found; i++) { Unique id = (Unique)derivedUnique.elementAt(i); found = false; for(int j=0; j<baseUnique.size(); j++) { if(id.equals((Unique)baseUnique.elementAt(j))) { found = true; break; } } } if(!found) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has a <unique> Identity Constraint that does not appear on the base element"+ fStringPool.toString(baseElemName)); } } Vector derivedKey = derivedElemDecl.key; Vector baseKey = baseElemDecl.key; if(derivedKey.size() > baseKey.size()) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has fewer <key> Identity Constraints than the base element"+ fStringPool.toString(baseElemName)); } else { boolean found = true; for(int i=0; i<derivedKey.size() && found; i++) { Key id = (Key)derivedKey.elementAt(i); found = false; for(int j=0; j<baseKey.size(); j++) { if(id.equals((Key)baseKey.elementAt(j))) { found = true; break; } } } if(!found) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has a <key> Identity Constraint that does not appear on the base element"+ fStringPool.toString(baseElemName)); } } Vector derivedKeyRef = derivedElemDecl.keyRef; Vector baseKeyRef = baseElemDecl.keyRef; if(derivedKeyRef.size() > baseKeyRef.size()) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has fewer <keyref> Identity Constraints than the base element"+ fStringPool.toString(baseElemName)); } else { boolean found = true; for(int i=0; i<derivedKeyRef.size() && found; i++) { KeyRef id = (KeyRef)derivedKeyRef.elementAt(i); found = false; for(int j=0; j<baseKeyRef.size(); j++) { if(id.equals((KeyRef)baseKeyRef.elementAt(j))) { found = true; break; } } } if(!found) { throw new ParticleRecoverableError("rcase-nameAndTypeOK.5: derived element " + fStringPool.toString(derivedElemName) + " has a <keyref> Identity Constraint that does not appear on the base element"+ fStringPool.toString(baseElemName)); } } } // checkIDConstraintRestriction private boolean checkSubstitutionGroups(int local1, int uri1, int local2, int uri2) throws Exception { // check if either name is in the other's substitution group QName name1 = new QName(-1,local1,local1,uri1); QName name2 = new QName(-1,local2,local2,uri2); if (fSComp.isEquivalentTo(name1,name2) || fSComp.isEquivalentTo(name2,name1)) return true; else return false; } private boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) { if ((min1 >= min2) && ((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) || (max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2))) return true; else return false; } private int findElement(int scope, int nameIndex, SchemaGrammar gr, ComplexTypeInfo bInfo) { // check for element at given scope first int elementDeclIndex = gr.getElementDeclIndex(nameIndex,scope); // if not found, check at global scope if (elementDeclIndex == -1) { elementDeclIndex = gr.getElementDeclIndex(nameIndex, -1); // if still not found, and base is specified, look it up there if (elementDeclIndex == -1 && bInfo != null) { ComplexTypeInfo baseInfo = bInfo; while (baseInfo != null) { elementDeclIndex = gr.getElementDeclIndex(nameIndex,baseInfo.scopeDefined); if (elementDeclIndex > -1) break; baseInfo = baseInfo.baseComplexTypeInfo; } } } return elementDeclIndex; } private void checkNSCompat(int csIndex1, int derivedScope, int csIndex2) throws Exception { int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-NSCompat.2: Element occurrence range not a restriction of base any element's range"); } fSchemaGrammar.getContentSpec(csIndex1, tempContentSpec1); int uri = tempContentSpec1.otherValue; // check wildcard subset if (!wildcardEltAllowsNamespace(csIndex2, uri)) throw new ParticleRecoverableError("rcase-NSCompat.1: Element's namespace not allowed by wildcard in base"); } private boolean wildcardEltAllowsNamespace(int wildcardNode, int uriIndex) { fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1); if ((tempContentSpec1.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY) return true; if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) { if (uriIndex == tempContentSpec1.otherValue) return true; } else { // must be ANY_OTHER if (uriIndex != tempContentSpec1.otherValue && uriIndex != StringPool.EMPTY_STRING) return true; } return false; } private void checkNSSubset(int csIndex1, int csIndex2) throws Exception { int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range"); } if (!wildcardEltSubset(csIndex1, csIndex2)) throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base"); } private boolean wildcardEltSubset(int wildcardNode, int wildcardBaseNode) { fSchemaGrammar.getContentSpec(wildcardNode, tempContentSpec1); fSchemaGrammar.getContentSpec(wildcardBaseNode, tempContentSpec2); if ((tempContentSpec2.type & 0x0f) == XMLContentSpec.CONTENTSPECNODE_ANY) return true; if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) { if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER && tempContentSpec1.otherValue == tempContentSpec2.otherValue) return true; } if ((tempContentSpec1.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS) { if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_NS && tempContentSpec1.otherValue == tempContentSpec2.otherValue) return true; if ((tempContentSpec2.type & 0x0f)==XMLContentSpec.CONTENTSPECNODE_ANY_OTHER && tempContentSpec1.otherValue != tempContentSpec2.otherValue) return true; } return false; } private void checkRecurseAsIfGroup(int csIndex1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception { fSchemaGrammar.getContentSpec(csIndex2, tempContentSpec2); // Treat the element as if it were in a group of the same type as csindex2 int indexOfGrp=fSchemaGrammar.addContentSpecNode(tempContentSpec2.type, csIndex1,-2, false); Vector tmpVector = new Vector(); tmpVector.addElement(new Integer(csIndex1)); if (tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_ALL || tempContentSpec2.type == XMLContentSpec.CONTENTSPECNODE_SEQ) checkRecurse(indexOfGrp, tmpVector, derivedScope, csIndex2, tempVector2, baseScope, bInfo); else checkRecurseLax(indexOfGrp, tmpVector, derivedScope, csIndex2, tempVector2, baseScope, bInfo); tmpVector = null; } private void checkNSRecurseCheckCardinality(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2) throws Exception { // Implement total range check int min1 = minEffectiveTotalRange(csIndex1); int max1 = maxEffectiveTotalRange(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-NSSubset.2: Wildcard's occurrence range not a restriction of base wildcard's range"); } if (!wildcardEltSubset(csIndex1, csIndex2)) throw new ParticleRecoverableError("rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base"); // Check that each member of the group is a valid restriction of the wildcard int count = tempVector1.size(); for (int i = 0; i < count; i++) { Integer particle1 = (Integer)tempVector1.elementAt(i); checkParticleDerivationOK(particle1.intValue(),derivedScope,csIndex2,-1,null); } } private void checkRecurse(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception { int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-Recurse.1: Occurrence range of group is not a valid restriction of occurence range of base group"); } int count1= tempVector1.size(); int count2= tempVector2.size(); int current = 0; label: for (int i = 0; i<count1; i++) { Integer particle1 = (Integer)tempVector1.elementAt(i); for (int j = current; j<count2; j++) { Integer particle2 = (Integer)tempVector2.elementAt(j); current +=1; try { checkParticleDerivationOK(particle1.intValue(),derivedScope, particle2.intValue(), baseScope, bInfo); continue label; } catch (ParticleRecoverableError e) { if (!particleEmptiable(particle2.intValue())) throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles"); } } throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles"); } // Now, see if there are some elements in the base we didn't match up for (int j=current; j < count2; j++) { Integer particle2 = (Integer)tempVector2.elementAt(j); if (!particleEmptiable(particle2.intValue())) { throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles"); } } } private void checkRecurseUnordered(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception { int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-RecurseUnordered.1: Occurrence range of group is not a valid restriction of occurence range of base group"); } int count1= tempVector1.size(); int count2 = tempVector2.size(); boolean foundIt[] = new boolean[count2]; label: for (int i = 0; i<count1; i++) { Integer particle1 = (Integer)tempVector1.elementAt(i); for (int j = 0; j<count2; j++) { Integer particle2 = (Integer)tempVector2.elementAt(j); try { checkParticleDerivationOK(particle1.intValue(),derivedScope, particle2.intValue(), baseScope, bInfo); if (foundIt[j]) throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles"); else foundIt[j]=true; continue label; } catch (ParticleRecoverableError e) { } } // didn't find a match. Detect an error throw new ParticleRecoverableError("rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles"); } } private void checkRecurseLax(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception { int min1 = fSchemaGrammar.getContentSpecMinOccurs(csIndex1); int max1 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex1); int min2 = fSchemaGrammar.getContentSpecMinOccurs(csIndex2); int max2 = fSchemaGrammar.getContentSpecMaxOccurs(csIndex2); // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new ParticleRecoverableError("rcase-RecurseLax.1: Occurrence range of group is not a valid restriction of occurence range of base group"); } int count1= tempVector1.size(); int count2 = tempVector2.size(); int current = 0; label: for (int i = 0; i<count1; i++) { Integer particle1 = (Integer)tempVector1.elementAt(i); for (int j = current; j<count2; j++) { Integer particle2 = (Integer)tempVector2.elementAt(j); current +=1; try { checkParticleDerivationOK(particle1.intValue(),derivedScope, particle2.intValue(), baseScope, bInfo); continue label; } catch (ParticleRecoverableError e) { } } // didn't find a match. Detect an error throw new ParticleRecoverableError("rcase-Recurse.2: There is not a complete functional mapping between the particles"); } } private void checkMapAndSum(int csIndex1, Vector tempVector1, int derivedScope, int csIndex2, Vector tempVector2, int baseScope, ComplexTypeInfo bInfo) throws Exception { // See if the sequence group particle is a valid restriction of one of the particles // of the choice // This isn't what the spec says, but I can't make heads or tails of the // algorithm in structures int count2 = tempVector2.size(); boolean foundit = false; for (int i=0; i<count2; i++) { Integer particle = (Integer)tempVector2.elementAt(i); fSchemaGrammar.getContentSpec(particle.intValue(),tempContentSpec1); if (tempContentSpec1.type == XMLContentSpec.CONTENTSPECNODE_SEQ) try { checkParticleDerivationOK(csIndex1,derivedScope,particle.intValue(), baseScope, bInfo); foundit = true; break; } catch (ParticleRecoverableError e) { } } if (!foundit) throw new ParticleRecoverableError("rcase-MapAndSum: There is not a complete functional mapping between the particles"); } private int importContentSpec(SchemaGrammar aGrammar, int contentSpecHead ) throws Exception { XMLContentSpec ctsp = new XMLContentSpec(); aGrammar.getContentSpec(contentSpecHead, ctsp); int left = -1; int right = -1; if ( ctsp.type == ctsp.CONTENTSPECNODE_LEAF || (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY || (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_NS || (ctsp.type & 0x0f) == ctsp.CONTENTSPECNODE_ANY_OTHER ) { return fSchemaGrammar.addContentSpecNode(ctsp.type, ctsp.value, ctsp.otherValue, false); } else if (ctsp.type == -1) // case where type being extended has no content return -2; else { if ( ctsp.value == -1 ) { left = -1; } else { left = importContentSpec(aGrammar, ctsp.value); } if ( ctsp.otherValue == -1 ) { right = -1; } else { right = importContentSpec(aGrammar, ctsp.otherValue); } return fSchemaGrammar.addContentSpecNode(ctsp.type, left, right, false); } } private int handleOccurrences(int index, Element particle) throws Exception { // Pass through, indicating we're not processing an <all> return handleOccurrences(index, particle, NOT_ALL_CONTEXT); } // Checks constraints for minOccurs, maxOccurs and expands content model // accordingly private int handleOccurrences(int index, Element particle, int allContextFlags) throws Exception { // if index is invalid, return if (index < 0) return index; String minOccurs = particle.getAttribute(SchemaSymbols.ATT_MINOCCURS).trim(); String maxOccurs = particle.getAttribute(SchemaSymbols.ATT_MAXOCCURS).trim(); boolean processingAll = ((allContextFlags & PROCESSING_ALL) != 0); boolean groupRefWithAll = ((allContextFlags & GROUP_REF_WITH_ALL) != 0); boolean isGroupChild = ((allContextFlags & CHILD_OF_GROUP) != 0); // Neither minOccurs nor maxOccurs may be specified // for the child of a model group definition. if (isGroupChild && (!minOccurs.equals("") || !maxOccurs.equals(""))) { reportSchemaError(SchemaMessageProvider.MinMaxOnGroupChild, null); minOccurs = (maxOccurs = "1"); } // If minOccurs=maxOccurs=0, no component is specified if(minOccurs.equals("0") && maxOccurs.equals("0")){ return -2; } int min=1, max=1; if (minOccurs.equals("")) { minOccurs = "1"; } if (maxOccurs.equals("")) { maxOccurs = "1"; } // For the elements referenced in an <all>, minOccurs attribute // must be zero or one, and maxOccurs attribute must be one. if (processingAll || groupRefWithAll) { if ((groupRefWithAll || !minOccurs.equals("0")) && !minOccurs.equals("1")) { int minMsg = processingAll ? SchemaMessageProvider.BadMinMaxForAll : SchemaMessageProvider.BadMinMaxForGroupWithAll; reportSchemaError(minMsg, new Object [] { "minOccurs", minOccurs }); minOccurs = "1"; } if (!maxOccurs.equals("1")) { int maxMsg = processingAll ? SchemaMessageProvider.BadMinMaxForAll : SchemaMessageProvider.BadMinMaxForGroupWithAll; reportSchemaError(maxMsg, new Object [] { "maxOccurs", maxOccurs }); maxOccurs = "1"; } } try { min = Integer.parseInt(minOccurs); } catch (Exception e){ reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "}); } if (maxOccurs.equals("unbounded")) { max = SchemaSymbols.OCCURRENCE_UNBOUNDED; } else { try { max = Integer.parseInt(maxOccurs); } catch (Exception e){ reportSchemaError(SchemaMessageProvider.GenericError, new Object [] { "illegal value for minOccurs or maxOccurs : '" +e.getMessage()+ "' "}); } // Check that minOccurs isn't greater than maxOccurs. // p-props-correct 2.1 if (min > max) { reportGenericSchemaError("p-props-correct:2.1 Value of minOccurs '" + minOccurs + "' must not be greater than value of maxOccurs '" + maxOccurs +"'"); } if (max < 1) { reportGenericSchemaError("p-props-correct:2.2 Value of maxOccurs " + maxOccurs + " is invalid. It must be greater than or equal to 1"); } } if (fSchemaGrammar.getDeferContentSpecExpansion()) { fSchemaGrammar.setContentSpecMinOccurs(index,min); fSchemaGrammar.setContentSpecMaxOccurs(index,max); return index; } else { return fSchemaGrammar.expandContentModel(index,min,max); } } /** * Traverses Schema attribute declaration. * * <attribute * default = string * fixed = string * form = (qualified | unqualified) * id = ID * name = NCName * ref = QName * type = QName * use = (optional | prohibited | required) : optional * {any attributes with non-schema namespace ...}> * Content: (annotation? , simpleType?) * <attribute/> * * @param attributeDecl: the declaration of the attribute under * consideration * @param typeInfo: Contains the index of the element to which * the attribute declaration is attached. * @param referredTo: true iff traverseAttributeDecl was called because * of encountering a ``ref''property (used * to suppress error-reporting). * @return 0 if the attribute schema is validated successfully, otherwise -1 * @exception Exception */ private int traverseAttributeDecl( Element attrDecl, ComplexTypeInfo typeInfo, boolean referredTo ) throws Exception { // General Attribute Checking int scope = isTopLevel(attrDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrDecl, scope); ////// Get declared fields of the attribute String defaultStr = attrDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String fixedStr = attrDecl.getAttribute(SchemaSymbols.ATT_FIXED); String formStr = attrDecl.getAttribute(SchemaSymbols.ATT_FORM);//form attribute String attNameStr = attrDecl.getAttribute(SchemaSymbols.ATT_NAME); String refStr = attrDecl.getAttribute(SchemaSymbols.ATT_REF); String datatypeStr = attrDecl.getAttribute(SchemaSymbols.ATT_TYPE); String useStr = attrDecl.getAttribute(SchemaSymbols.ATT_USE); Element simpleTypeChild = findAttributeSimpleType(attrDecl); Attr defaultAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT); Attr fixedAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FIXED); Attr formAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_FORM); Attr attNameAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_NAME); Attr refAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_REF); Attr datatypeAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_TYPE); Attr useAtt = attrDecl.getAttributeNode(SchemaSymbols.ATT_USE); checkEnumerationRequiredNotation(attNameStr, datatypeStr); ////// define attribute declaration Schema components int attName; // attribute name indexed in the string pool int uriIndex; // indexed for target namespace uri QName attQName; // QName combining attName and uriIndex // attribute type int attType; boolean attIsList = false; int dataTypeSymbol = -1; String localpart = null; // validator DatatypeValidator dv; boolean dvIsDerivedFromID = false; // value constraints and use type int attValueAndUseType = 0; int attValueConstraint = -1; // indexed value in a string pool ////// Check W3C's PR-Structure 3.2.3 // --- Constraints on XML Representations of Attribute Declarations boolean isAttrTopLevel = isTopLevel(attrDecl); boolean isOptional = false; boolean isProhibited = false; boolean isRequired = false; StringBuffer errorContext = new StringBuffer(30); errorContext.append(" -- "); if(typeInfo == null) { errorContext.append("(global attribute) "); } else if(typeInfo.typeName == null) { errorContext.append("(local attribute) "); } else { errorContext.append("(attribute) ").append(typeInfo.typeName).append("/"); } errorContext.append(attNameStr).append(' ').append(refStr); if(useStr.equals("") || useStr.equals(SchemaSymbols.ATTVAL_OPTIONAL)) { attValueAndUseType |= XMLAttributeDecl.USE_TYPE_OPTIONAL; isOptional = true; } else if(useStr.equals(SchemaSymbols.ATTVAL_PROHIBITED)) { attValueAndUseType |= XMLAttributeDecl.USE_TYPE_PROHIBITED; isProhibited = true; } else if(useStr.equals(SchemaSymbols.ATTVAL_REQUIRED)) { attValueAndUseType |= XMLAttributeDecl.USE_TYPE_REQUIRED; isRequired = true; } else { reportGenericSchemaError("An attribute cannot declare \"" + SchemaSymbols.ATT_USE + "\" as \"" + useStr + "\"" + errorContext); } if(defaultAtt != null && fixedAtt != null) { reportGenericSchemaError("src-attribute.1: \"" + SchemaSymbols.ATT_DEFAULT + "\" and \"" + SchemaSymbols.ATT_FIXED + "\" cannot be both present" + errorContext); } else if(defaultAtt != null && !isOptional) { reportGenericSchemaError("src-attribute.2: If both \"" + SchemaSymbols.ATT_DEFAULT + "\" and \"" + SchemaSymbols.ATT_USE + "\" " + "are present for an attribute declaration, \"" + SchemaSymbols.ATT_USE + "\" can only be \"" + SchemaSymbols.ATTVAL_OPTIONAL + "\", not \"" + useStr + "\"." + errorContext); } if(!isAttrTopLevel) { if((refAtt == null) == (attNameAtt == null)) { reportGenericSchemaError("src-attribute.3.1: When the attribute's parent is not <schema> , one of \"" + SchemaSymbols.ATT_REF + "\" and \"" + SchemaSymbols.ATT_NAME + "\" should be declared, but not both."+ errorContext); return -1; } else if((refAtt != null) && (simpleTypeChild != null || formAtt != null || datatypeAtt != null)) { reportGenericSchemaError("src-attribute.3.2: When the attribute's parent is not <schema> and \"" + SchemaSymbols.ATT_REF + "\" is present, " + "all of <" + SchemaSymbols.ELT_SIMPLETYPE + ">, " + SchemaSymbols.ATT_FORM + " and " + SchemaSymbols.ATT_TYPE + " must be absent."+ errorContext); } } if(datatypeAtt != null && simpleTypeChild != null) { reportGenericSchemaError("src-attribute.4: \"" + SchemaSymbols.ATT_TYPE + "\" and <" + SchemaSymbols.ELT_SIMPLETYPE + "> cannot both be present"+ errorContext); } ////// Check W3C's PR-Structure 3.2.2 // --- XML Representation of Attribute Declaration Schema Components // check case-dependent attribute declaration schema components if (isAttrTopLevel) { //// global attributes // set name component attName = fStringPool.addSymbol(attNameStr); if(fTargetNSURIString.length() == 0) { uriIndex = StringPool.EMPTY_STRING; } else { uriIndex = fTargetNSURI; } // attQName = new QName(-1,attName,attName,uriIndex); // Above line replaced by following 2 to work around a JIT problem. attQName = new QName(); attQName.setValues(-1,attName,attName,uriIndex); } else if(refAtt == null) { //// local attributes // set name component attName = fStringPool.addSymbol(attNameStr); if((formStr.length() > 0 && formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)) || (formStr.length() == 0 && fAttributeDefaultQualified)) { uriIndex = fTargetNSURI; } else { uriIndex = StringPool.EMPTY_STRING; } // attQName = new QName(-1,attName,attName,uriIndex); // Above line replaced by following 2 to work around a JIT problem. attQName = new QName(); attQName.setValues(-1,attName,attName,uriIndex); } else { //// locally referenced global attributes String prefix; int colonptr = refStr.indexOf(":"); if ( colonptr > 0) { prefix = refStr.substring(0,colonptr); localpart = refStr.substring(colonptr+1); } else { prefix = ""; localpart = refStr; } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo); return 0; } Element referredAttribute = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTE,localpart); if (referredAttribute != null) { // don't need to traverse ref'd attribute if we're global; just make sure it's there... traverseAttributeDecl(referredAttribute, typeInfo, true); Attr referFixedAttr = referredAttribute.getAttributeNode(SchemaSymbols.ATT_FIXED); String referFixed = referFixedAttr == null ? null : referFixedAttr.getValue(); if (referFixed != null && (defaultAtt != null || fixedAtt != null && !referFixed.equals(fixedStr))) { reportGenericSchemaError("au-props-correct.2: If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}" + errorContext); } // this nasty hack needed to ``override'' the // global attribute with "use" and "fixed" on the ref'ing attribute if(!isOptional || fixedStr.length() > 0) { int referredAttName = fStringPool.addSymbol(referredAttribute.getAttribute(SchemaSymbols.ATT_NAME)); uriIndex = StringPool.EMPTY_STRING; if ( fTargetNSURIString.length() > 0) { uriIndex = fTargetNSURI; } QName referredAttQName = new QName(-1,referredAttName,referredAttName,uriIndex); int tempIndex = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, referredAttQName); XMLAttributeDecl referredAttrDecl = new XMLAttributeDecl(); fSchemaGrammar.getAttributeDecl(tempIndex, referredAttrDecl); boolean updated = false; int useDigits = XMLAttributeDecl.USE_TYPE_OPTIONAL | XMLAttributeDecl.USE_TYPE_PROHIBITED | XMLAttributeDecl.USE_TYPE_REQUIRED; int valueDigits = XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT | XMLAttributeDecl.VALUE_CONSTRAINT_FIXED; if(!isOptional && (referredAttrDecl.defaultType & useDigits) != (attValueAndUseType & useDigits)) { if(referredAttrDecl.defaultType != XMLAttributeDecl.USE_TYPE_PROHIBITED) { referredAttrDecl.defaultType |= useDigits; referredAttrDecl.defaultType ^= useDigits; // clear the use referredAttrDecl.defaultType |= (attValueAndUseType & useDigits); updated = true; } } if(fixedStr.length() > 0) { if((referredAttrDecl.defaultType & XMLAttributeDecl.VALUE_CONSTRAINT_FIXED) == 0) { referredAttrDecl.defaultType |= valueDigits; referredAttrDecl.defaultType ^= valueDigits; // clear the value referredAttrDecl.defaultType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED; referredAttrDecl.defaultValue = fixedStr; updated = true; } } if(updated) { fSchemaGrammar.setAttributeDecl(typeInfo.templateElementIndex, tempIndex, referredAttrDecl); } } } else if (fAttributeDeclRegistry.get(localpart) != null) { addAttributeDeclFromAnotherSchema(localpart, uriStr, typeInfo); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attribute " + refStr + errorContext); } return 0; } if (uriIndex == fXsiURI) { reportGenericSchemaError("no-xsi: The {target namespace} of an attribute declaration must not match " + SchemaSymbols.URI_XSI + errorContext); } // validation of attribute type is same for each case of declaration if (simpleTypeChild != null) { attType = XMLAttributeDecl.TYPE_SIMPLE; dataTypeSymbol = traverseSimpleTypeDecl(simpleTypeChild); localpart = fStringPool.toString(dataTypeSymbol); dv = fDatatypeRegistry.getDatatypeValidator(localpart); } else if (datatypeStr.length() != 0) { dataTypeSymbol = fStringPool.addSymbol(datatypeStr); String prefix; int colonptr = datatypeStr.indexOf(":"); if ( colonptr > 0) { prefix = datatypeStr.substring(0,colonptr); localpart = datatypeStr.substring(colonptr+1); } else { prefix = ""; localpart = datatypeStr; } String typeURI = resolvePrefixToURI(prefix); if ( typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) || typeURI.length()==0) { dv = getDatatypeValidator("", localpart); if (localpart.equals("ID")) { attType = XMLAttributeDecl.TYPE_ID; } else if (localpart.equals("IDREF")) { attType = XMLAttributeDecl.TYPE_IDREF; } else if (localpart.equals("IDREFS")) { attType = XMLAttributeDecl.TYPE_IDREF; attIsList = true; } else if (localpart.equals("ENTITY")) { attType = XMLAttributeDecl.TYPE_ENTITY; } else if (localpart.equals("ENTITIES")) { attType = XMLAttributeDecl.TYPE_ENTITY; attIsList = true; } else if (localpart.equals("NMTOKEN")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; } else if (localpart.equals("NMTOKENS")) { attType = XMLAttributeDecl.TYPE_NMTOKEN; attIsList = true; } else if (localpart.equals(SchemaSymbols.ELT_NOTATION)) { attType = XMLAttributeDecl.TYPE_NOTATION; } else { attType = XMLAttributeDecl.TYPE_SIMPLE; if (dv == null && typeURI.length() == 0) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); }else if (!referredTo) { // REVISIT: Localize reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+localpart+")"+ errorContext); } } } } else { //isn't of the schema for schemas namespace... attType = XMLAttributeDecl.TYPE_SIMPLE; // check if the type is from the same Schema dv = getDatatypeValidator(typeURI, localpart); if (dv == null && typeURI.equals(fTargetNSURIString) ) { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); }else if (!referredTo) { // REVISIT: Localize reportGenericSchemaError("simpleType not found : " + "("+typeURI+":"+ localpart+")"+ errorContext); } } } } else { attType = XMLAttributeDecl.TYPE_SIMPLE; localpart = "string"; dataTypeSymbol = fStringPool.addSymbol(localpart); dv = fDatatypeRegistry.getDatatypeValidator(localpart); } // if(...Type) // validation of data constraint is same for each case of declaration if(defaultStr.length() > 0) { attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_DEFAULT; attValueConstraint = fStringPool.addString(defaultStr); } else if(fixedStr.length() > 0) { attValueAndUseType |= XMLAttributeDecl.VALUE_CONSTRAINT_FIXED; attValueConstraint = fStringPool.addString(fixedStr); } ////// Check W3C's PR-Structure 3.2.6 // --- Constraints on Attribute Declaration Schema Components // check default value is valid for the datatype. if (attType == XMLAttributeDecl.TYPE_SIMPLE && attValueConstraint != -1) { try { if (dv != null) { if(defaultStr.length() > 0) { //REVISIT dv.validate(defaultStr, null); } else { dv.validate(fixedStr, null); } } else if (!referredTo) reportSchemaError(SchemaMessageProvider.NoValidatorFor, new Object [] { datatypeStr }); } catch (InvalidDatatypeValueException idve) { if (!referredTo) reportSchemaError(SchemaMessageProvider.IncorrectDefaultType, new Object [] { attrDecl.getAttribute(SchemaSymbols.ATT_NAME), idve.getMessage() }); //a-props-correct.2 } catch (Exception e) { e.printStackTrace(); System.out.println("Internal error in attribute datatype validation"); } } // check the coexistence of ID and value constraint dvIsDerivedFromID = ((dv != null) && dv instanceof IDDatatypeValidator); if (dvIsDerivedFromID && attValueConstraint != -1) { reportGenericSchemaError("a-props-correct.3: If type definition is or is derived from ID ," + "there must not be a value constraint" + errorContext); } if (attNameStr.equals("xmlns")) { reportGenericSchemaError("no-xmlns: The {name} of an attribute declaration must not match 'xmlns'" + errorContext); } ////// every contraints were matched. Now register the attribute declaration //put the top-levels in the attribute decl registry. if (isAttrTopLevel) { fTempAttributeDecl.datatypeValidator = dv; fTempAttributeDecl.name.setValues(attQName); fTempAttributeDecl.type = attType; fTempAttributeDecl.defaultType = attValueAndUseType; fTempAttributeDecl.list = attIsList; if (attValueConstraint != -1 ) { fTempAttributeDecl.defaultValue = fStringPool.toString(attValueConstraint); } fAttributeDeclRegistry.put(attNameStr, new XMLAttributeDecl(fTempAttributeDecl)); } // add attribute to attr decl pool in fSchemaGrammar, if (typeInfo != null) { // check that there aren't duplicate attributes int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, attQName); if (temp > -1) { reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " + fStringPool.toString(attQName.rawname) + " in type definition"); } // check that there aren't multiple attributes with type derived from ID if (dvIsDerivedFromID) { if (typeInfo.containsAttrTypeID()) { reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition."); } typeInfo.setContainsAttrTypeID(); } fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, attQName, attType, dataTypeSymbol, attValueAndUseType, fStringPool.toString( attValueConstraint), dv, attIsList); } return 0; } // end of method traverseAttribute private int addAttributeDeclFromAnotherSchema( String name, String uriStr, ComplexTypeInfo typeInfo) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError( "no attribute named \"" + name + "\" was defined in schema : " + uriStr); return -1; } Hashtable attrRegistry = aGrammar.getAttributeDeclRegistry(); if (attrRegistry == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute named \"" + name + "\" was defined in schema : " + uriStr); return -1; } XMLAttributeDecl tempAttrDecl = (XMLAttributeDecl) attrRegistry.get(name); if (tempAttrDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute named \"" + name + "\" was defined in schema : " + uriStr); return -1; } if (typeInfo!= null) { // check that there aren't duplicate attributes int temp = fSchemaGrammar.getAttributeDeclIndex(typeInfo.templateElementIndex, tempAttrDecl.name); if (temp > -1) { reportGenericSchemaError("ct-props-correct.4: Duplicate attribute " + fStringPool.toString(tempAttrDecl.name.rawname) + " in type definition"); } // check that there aren't multiple attributes with type derived from ID if (tempAttrDecl.datatypeValidator != null && tempAttrDecl.datatypeValidator instanceof IDDatatypeValidator) { if (typeInfo.containsAttrTypeID()) { reportGenericSchemaError("ct-props-correct.5: More than one attribute derived from type ID cannot appear in the same complex type definition"); } typeInfo.setContainsAttrTypeID(); } fSchemaGrammar.addAttDef( typeInfo.templateElementIndex, tempAttrDecl.name, tempAttrDecl.type, -1, tempAttrDecl.defaultType, tempAttrDecl.defaultValue, tempAttrDecl.datatypeValidator, tempAttrDecl.list); } return 0; } /* * * <attributeGroup * id = ID * name = NCName * ref = QName> * Content: (annotation?, (attribute|attributeGroup)*, anyAttribute?) * </> * */ private int traverseAttributeGroupDecl( Element attrGrpDecl, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception { // General Attribute Checking int scope = isTopLevel(attrGrpDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(attrGrpDecl, scope); // attributeGroup name String attGrpNameStr = attrGrpDecl.getAttribute(SchemaSymbols.ATT_NAME); int attGrpName = fStringPool.addSymbol(attGrpNameStr); String ref = attrGrpDecl.getAttribute(SchemaSymbols.ATT_REF); Element child = checkContent( attrGrpDecl, XUtil.getFirstChildElement(attrGrpDecl), true ); if (!ref.equals("")) { if(isTopLevel(attrGrpDecl)) // REVISIT: localize reportGenericSchemaError ( "An attributeGroup with \"ref\" present must not have <schema> or <redefine> as its parent"); if(!attGrpNameStr.equals("")) // REVISIT: localize reportGenericSchemaError ( "attributeGroup " + attGrpNameStr + " cannot refer to another attributeGroup, but it refers to " + ref); if (XUtil.getFirstChildElement(attrGrpDecl) != null || attrGrpDecl.getNodeValue() != null) // REVISIT: localize reportGenericSchemaError ( "An attributeGroup with \"ref\" present must be empty"); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { traverseAttributeGroupDeclFromAnotherSchema(localpart, uriStr, typeInfo, anyAttDecls); return -1; // TO DO // REVISIT: different NS, not supported yet. // REVISIT: Localize //reportGenericSchemaError("Feature not supported: see an attribute from different NS"); } else { Element parent = (Element)attrGrpDecl.getParentNode(); if (parent.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) && parent.getAttribute(SchemaSymbols.ATT_NAME).equals(localpart)) { if (!((Element)parent.getParentNode()).getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) { reportGenericSchemaError("src-attribute_group.3: Circular group reference is disallowed outside <redefine> -- "+ref); } return -1; } } if(typeInfo != null) { // only do this if we're traversing because we were ref'd here; when we come // upon this decl by itself we're just validating. Element referredAttrGrp = getTopLevelComponentByName(SchemaSymbols.ELT_ATTRIBUTEGROUP,localpart); if (referredAttrGrp != null) { traverseAttributeGroupDecl(referredAttrGrp, typeInfo, anyAttDecls); } else { // REVISIT: Localize reportGenericSchemaError ( "Couldn't find top level attributeGroup " + ref); } return -1; } } else if (attGrpNameStr.equals("")) // REVISIT: localize reportGenericSchemaError ( "an attributeGroup must have a name or a ref attribute present"); for (; child != null ; child = XUtil.getNextSiblingElement(child)) { if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ traverseAttributeDecl(child, typeInfo, false); } else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { NamespacesScope currScope = (NamespacesScope)fNamespacesScope.clone(); // if(typeInfo != null) // only do this if we're traversing because we were ref'd here; when we come // upon this decl by itself we're just validating. traverseAttributeGroupDecl(child, typeInfo,anyAttDecls); fNamespacesScope = currScope; } else break; } if (child != null) { if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { if (anyAttDecls != null) { anyAttDecls.addElement(traverseAnyAttribute(child)); } if (XUtil.getNextSiblingElement(child) != null) // REVISIT: localize reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))"); return -1; } else // REVISIT: localize reportGenericSchemaError ( "src-attribute_group.0: The content of an attributeGroup declaration must match (annotation?, ((attribute | attributeGroup)*, anyAttribute?))"); } return -1; } // end of method traverseAttributeGroup private int traverseAttributeGroupDeclFromAnotherSchema( String attGrpName , String uriStr, ComplexTypeInfo typeInfo, Vector anyAttDecls ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || aGrammar == null || ! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseAttributeGroupDeclFromAnotherSchema, schema uri : " + uriStr); return -1; } // attribute name Element attGrpDecl = (Element) aGrammar.topLevelAttrGrpDecls.get((Object)attGrpName); if (attGrpDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no attribute group named \"" + attGrpName + "\" was defined in schema : " + uriStr); return -1; } NamespacesScope saveNSMapping = fNamespacesScope; int saveTargetNSUri = fTargetNSURI; fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()); fNamespacesScope = aGrammar.getNamespacesScope(); // attribute type int attType = -1; int enumeration = -1; Element child = checkContent(attGrpDecl, XUtil.getFirstChildElement(attGrpDecl), true); for (; child != null ; child = XUtil.getNextSiblingElement(child)) { //child attribute couldn't be a top-level attribute DEFINITION, if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTE) ){ String childAttName = child.getAttribute(SchemaSymbols.ATT_NAME); if ( childAttName.length() > 0 ) { Hashtable attDeclRegistry = aGrammar.getAttributeDeclRegistry(); if ((attDeclRegistry != null) && (attDeclRegistry.get((Object)childAttName) != null) ){ addAttributeDeclFromAnotherSchema(childAttName, uriStr, typeInfo); return -1; } else { traverseAttributeDecl(child, typeInfo, false); } } else traverseAttributeDecl(child, typeInfo, false); } else if ( child.getLocalName().equals(SchemaSymbols.ELT_ATTRIBUTEGROUP) ) { traverseAttributeGroupDecl(child, typeInfo, anyAttDecls); } else if ( child.getLocalName().equals(SchemaSymbols.ELT_ANYATTRIBUTE) ) { anyAttDecls.addElement(traverseAnyAttribute(child)); break; } else { // REVISIT: Localize reportGenericSchemaError("Invalid content for attributeGroup"); } } fNamespacesScope = saveNSMapping; fTargetNSURI = saveTargetNSUri; if(child != null) { // REVISIT: Localize reportGenericSchemaError("Invalid content for attributeGroup"); } return -1; } // end of method traverseAttributeGroupFromAnotherSchema // This simple method takes an attribute declaration as a parameter and // returns null if there is no simpleType defined or the simpleType // declaration if one exists. It also throws an error if more than one // <annotation> or <simpleType> group is present. private Element findAttributeSimpleType(Element attrDecl) throws Exception { Element child = checkContent(attrDecl, XUtil.getFirstChildElement(attrDecl), true); // if there is only a annotatoin, then no simpleType if (child == null) return null; // if the current one is not simpleType, or there are more elements, // report an error if (!child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE) || XUtil.getNextSiblingElement(child) != null) //REVISIT: localize reportGenericSchemaError("src-attribute.0: the content must match (annotation?, (simpleType?)) -- attribute declaration '"+ attrDecl.getAttribute(SchemaSymbols.ATT_NAME)+"'"); if (child.getLocalName().equals(SchemaSymbols.ELT_SIMPLETYPE)) return child; return null; } // end findAttributeSimpleType /** * Traverse element declaration: * <element * abstract = boolean * block = #all or (possibly empty) subset of {substitutionGroup, extension, restriction} * default = string * substitutionGroup = QName * final = #all or (possibly empty) subset of {extension, restriction} * fixed = string * form = qualified | unqualified * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * nillable = boolean * ref = QName * type = QName> * Content: (annotation? , (simpleType | complexType)? , (unique | key | keyref)*) * </element> * * * The following are identity-constraint definitions * <unique * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </unique> * * <key * id = ID * name = NCName> * Content: (annotation? , (selector , field+)) * </key> * * <keyref * id = ID * name = NCName * refer = QName> * Content: (annotation? , (selector , field+)) * </keyref> * * <selector> * Content: XPathExprApprox : An XPath expression * </selector> * * <field> * Content: XPathExprApprox : An XPath expression * </field> * * * @param elementDecl * @return * @exception Exception */ private QName traverseElementDecl(Element elementDecl) throws Exception { // General Attribute Checking int scope = isTopLevel(elementDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope); int contentSpecType = -1; int contentSpecNodeIndex = -1; int typeNameIndex = -1; int scopeDefined = -2; //signal a error if -2 gets gets through //cause scope can never be -2. DatatypeValidator dv = null; String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT); String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK); String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL); String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED); String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM); String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS); String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS); String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME); String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE); String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF); String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP); String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE); checkEnumerationRequiredNotation(nameStr, typeStr); if ( DEBUGGING ) System.out.println("traversing element decl : " + nameStr ); Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT); Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK); Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT); Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL); Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED); Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM); Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS); Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS); Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME); Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE); Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF); Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP); Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE); if(defaultAtt != null && fixedAtt != null) // REVISIT: localize reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time"); String fromAnotherSchema = null; if (isTopLevel(elementDecl)) { if(nameAtt == null) // REVISIT: localize reportGenericSchemaError("globally-declared element must have a name"); else if (refAtt != null) // REVISIT: localize reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute"); int nameIndex = fStringPool.addSymbol(nameStr); int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE); if (eltKey > -1 ) { return new QName(-1,nameIndex,nameIndex,fTargetNSURI); } } // parse out 'block', 'final', 'nillable', 'abstract' if (blockAtt == null) blockStr = null; int blockSet = parseBlockSet(blockStr); if( (blockStr != null) && !blockStr.equals("") && (!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((blockSet & SchemaSymbols.RESTRICTION) == 0) && (((blockSet & SchemaSymbols.EXTENSION) == 0) && ((blockSet & SchemaSymbols.SUBSTITUTION) == 0))))) reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found"); if (finalAtt == null) finalStr = null; int finalSet = parseFinalSet(finalStr); if( (finalStr != null) && !finalStr.equals("") && (!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((finalSet & SchemaSymbols.RESTRICTION) == 0) && ((finalSet & SchemaSymbols.EXTENSION) == 0)))) reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found"); boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; int elementMiscFlags = 0; if (isNillable) { elementMiscFlags += SchemaSymbols.NILLABLE; } if (isAbstract) { elementMiscFlags += SchemaSymbols.ABSTRACT; } // make the property of the element's value being fixed also appear in elementMiscFlags if(fixedAtt != null) elementMiscFlags += SchemaSymbols.FIXED; //if this is a reference to a global element if (refAtt != null) { //REVISIT top level check for ref if (abstractAtt != null || blockAtt != null || defaultAtt != null || finalAtt != null || fixedAtt != null || formAtt != null || nillableAtt != null || substitutionGroupAtt != null || typeAtt != null) reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2 if (nameAtt != null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute"); Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { if (XUtil.getNextSiblingElement(child) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); else traverseAnnotationDecl(child); } else if (child != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = refStr; int colonptr = refStr.indexOf(":"); if ( colonptr > 0) { prefix = refStr.substring(0,colonptr); localpart = refStr.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriString = resolvePrefixToURI(prefix); QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1, localpartIndex, fStringPool.addSymbol(refStr), uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING); //if from another schema, just return the element QName if (! uriString.equals(fTargetNSURIString) ) { return eltName; } int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE); //if not found, traverse the top level element that if referenced if (elementIndex == -1 ) { Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart); if (targetElement == null ) { // REVISIT: Localize reportGenericSchemaError("Element " + localpart + " not found in the Schema"); //REVISIT, for now, the QName anyway return eltName; //return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString)); } else { // do nothing here, other wise would cause infinite loop for // <element name="recur"><complexType><element ref="recur"> ... //eltName= traverseElementDecl(targetElement); } } return eltName; } else if (nameAtt == null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present"); // Handle the substitutionGroup Element substitutionGroupElementDecl = null; int substitutionGroupElementDeclIndex = -1; boolean noErrorSoFar = true; // // resolving the type for this element right here // ComplexTypeInfo typeInfo = null; // element has a single child element, either a datatype or a type, null if primitive Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child); child = XUtil.getNextSiblingElement(child); } if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) // REVISIT: Localize reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item"); boolean haveAnonType = false; // Handle Anonymous type if there is one if (child != null) { String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute"); } else { // Determine what the type name will be String anonTypeName = genAnonTypeName(child); if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) { // A recursing element using an anonymous type int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,anonTypeName)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl(child); if (typeNameIndex != -1 ) { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'"); } } } haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute"); } else typeNameIndex = traverseSimpleTypeDecl(child); if (typeNameIndex != -1) { dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'"); } contentSpecType = XMLElementDecl.TYPE_SIMPLE; haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (typeAtt == null) { // "ur-typed" leaf contentSpecType = XMLElementDecl.TYPE_ANY; //REVISIT: is this right? //contentSpecType = fStringPool.addSymbol("UR_TYPE"); // set occurrence count contentSpecNodeIndex = -1; } // see if there's something here; it had better be key, keyref or unique. if (child != null) childName = child.getLocalName(); while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY)) || (childName.equals(SchemaSymbols.ELT_KEYREF)) || (childName.equals(SchemaSymbols.ELT_UNIQUE)))) { child = XUtil.getNextSiblingElement(child); if (child != null) { childName = child.getLocalName(); } } if (child != null) { // REVISIT: Localize noErrorSoFar = false; reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)"); } } // handle type="" here if (haveAnonType && (typeAtt != null)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError( "src-element.3: Element '"+ nameStr + "' have both a type attribute and a annoymous type child" ); } // type specified as an attribute and no child is type decl. else if (typeAtt != null) { String prefix = ""; String localpart = typeStr; int colonptr = typeStr.indexOf(":"); if ( colonptr > 0) { prefix = typeStr.substring(0,colonptr); localpart = typeStr.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); // check if the type is from the same Schema if ( !typeURI.equals(fTargetNSURIString) && !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI. fromAnotherSchema = typeURI; typeInfo = getTypeInfoFromNS(typeURI, localpart); if (typeInfo == null) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type " +localpart + " in schema " + typeURI); } } } else { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart); if (typeInfo == null) { dv = getDatatypeValidator(typeURI, localpart); if (dv == null ) if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } else { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (topleveltype != null) { if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { //then we found a recursive element using complexType. // REVISIT: this will be broken when recursing happens between 2 schemas int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,localpart)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl( topleveltype, true ); typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } } else { topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { typeNameIndex = traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } } } } } } // now we need to make sure that our substitution (if any) // is valid, now that we have all the requisite type-related info. String substitutionGroupUri = null; String substitutionGroupLocalpart = null; String substitutionGroupFullName = null; ComplexTypeInfo substitutionGroupEltTypeInfo = null; DatatypeValidator substitutionGroupEltDV = null; SchemaGrammar subGrammar = fSchemaGrammar; boolean ignoreSub = false; if ( substitutionGroupStr.length() > 0 ) { if(refAtt != null) // REVISIT: Localize reportGenericSchemaError("a local element cannot have a substitutionGroup"); substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr)); substitutionGroupLocalpart = getLocalPart(substitutionGroupStr); substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart; if ( !substitutionGroupUri.equals(fTargetNSURIString) ) { Grammar grammar = fGrammarResolver.getGrammar(substitutionGroupUri); if (grammar != null && grammar instanceof SchemaGrammar) { subGrammar = (SchemaGrammar) grammar; substitutionGroupElementDeclIndex = subGrammar.getElementDeclIndex(fStringPool.addSymbol(substitutionGroupUri), fStringPool.addSymbol(substitutionGroupLocalpart), TOP_LEVEL_SCOPE); if (substitutionGroupElementDeclIndex<=-1) { // REVISIT: localize noErrorSoFar = false; reportGenericSchemaError("couldn't find substitutionGroup " + substitutionGroupLocalpart + " referenced by element " + nameStr + " in the SchemaGrammar "+substitutionGroupUri); } else { substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltTypeInfo == null) { substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } else { // REVISIT: locallize noErrorSoFar = false; reportGenericSchemaError("couldn't find a schema grammar with target namespace " + substitutionGroupUri); } } else { substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart); if (substitutionGroupElementDecl == null) { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("unable to locate substitutionGroup affiliation element " +substitutionGroupStr +" in element declaration " +nameStr); } } else { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { // check for mutual recursion! if(fSubstitutionGroupRecursionRegistry.contains(substitutionGroupElementDecl.getAttribute("name"))) { ignoreSub = true; } else { - fSubstitutionGroupRecursionRegistry.addElement(substitutionGroupElementDecl.getAttribute("name")); + fSubstitutionGroupRecursionRegistry.addElement(substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); traverseElementDecl(substitutionGroupElementDecl); substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); - fSubstitutionGroupRecursionRegistry.remove(substitutionGroupElementDecl.getAttribute("name")); + fSubstitutionGroupRecursionRegistry.removeElement((Object)substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); } } } if (!ignoreSub && substitutionGroupElementDeclIndex != -1) { substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex ); if (substitutionGroupEltTypeInfo == null) { fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl); substitutionGroupEltDV = fTempElementDecl.datatypeValidator; if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } if(!ignoreSub) checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, subGrammar, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV); } // this element is ur-type, check its substitutionGroup affiliation. // if there is substitutionGroup affiliation and not type definition found for this element, // then grab substitutionGroup affiliation's type and give it to this element if ( noErrorSoFar && typeInfo == null && dv == null ) { typeInfo = substitutionGroupEltTypeInfo; dv = substitutionGroupEltDV; } if (typeInfo == null && dv==null) { if (noErrorSoFar) { // Actually this Element's type definition is ur-type; contentSpecType = XMLElementDecl.TYPE_ANY; // REVISIT, need to wait till we have wildcards implementation. // ADD attribute wildcards here } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError ("untyped element : " + nameStr ); } } // if element belongs to a compelx type if (typeInfo!=null) { contentSpecNodeIndex = typeInfo.contentSpecHandle; contentSpecType = typeInfo.contentType; scopeDefined = typeInfo.scopeDefined; dv = typeInfo.datatypeValidator; } // if element belongs to a simple type if (dv!=null) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; if (typeInfo == null) { fromAnotherSchema = null; // not to switch schema in this case } } // Now we can handle validation etc. of default and fixed attributes, // since we finally have all the type information. if(fixedAtt != null) defaultStr = fixedStr; if(!defaultStr.equals("")) { if(typeInfo != null && (typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE && typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX && typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) { // REVISIT: Localize reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model"); } if(typeInfo != null && (typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE || typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) { if (!particleEmptiable(typeInfo.contentSpecHandle)) reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable"); } try { if(dv != null) { dv.validate(defaultStr, null); } } catch (InvalidDatatypeValueException ide) { reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr); } } if (!defaultStr.equals("") && dv != null && dv instanceof IDDatatypeValidator) { reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr); } // // Create element decl // int elementNameIndex = fStringPool.addSymbol(nameStr); int localpartIndex = elementNameIndex; int uriIndex = StringPool.EMPTY_STRING; int enclosingScope = fCurrentScope; //refer to 4.3.2 in "XML Schema Part 1: Structures" if ( isTopLevel(elementDecl)) { uriIndex = fTargetNSURI; enclosingScope = TOP_LEVEL_SCOPE; } else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) && (( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified ))) { uriIndex = fTargetNSURI; } //There can never be two elements with the same name and different type in the same scope. int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope); if ( existSuchElementIndex > -1) { fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl); DatatypeValidator edv = fTempElementDecl.datatypeValidator; ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex); if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo)) || ((edv != null)&&(edv != dv)) ) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("duplicate element decl in the same scope : " + fStringPool.toString(localpartIndex)); } } QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex); // add element decl to pool int attrListHead = -1 ; // copy up attribute decls from type object if (typeInfo != null) { attrListHead = typeInfo.attlistHead; } int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined, contentSpecType, contentSpecNodeIndex, attrListHead, dv); if ( DEBUGGING ) { /***/ System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+"," + fStringPool.toString(eltQName.localpart) + ")"+ " eltType:"+typeStr+" contentSpecType:"+contentSpecType+ " SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope + " scopeDefined: " +scopeDefined+"\n"); /***/ } fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); // REVISIT: should we report error if typeInfo was null? // mark element if its type belongs to different Schema. fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema); // set BlockSet, FinalSet, Nillable and Abstract for this element decl fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet); fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet); fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags); fSchemaGrammar.setElementDefault(elementIndex, defaultStr); // setSubstitutionGroupElementFullName fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName); // // key/keyref/unique processing // Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS); if (ic != null) { Integer elementIndexObj = new Integer(elementIndex); Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj); if (identityConstraints == null) { identityConstraints = new Vector(); fIdentityConstraints.put(elementIndexObj, identityConstraints); } while (ic != null) { if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: adding ic for later traversal: "+ic); } identityConstraints.addElement(ic); ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS); } } return eltQName; }// end of method traverseElementDecl(Element) private void traverseIdentityNameConstraintsFor(int elementIndex, Vector identityConstraints) throws Exception { // iterate over identity constraints for this element int size = identityConstraints != null ? identityConstraints.size() : 0; if (size > 0) { // REVISIT: Use cached copy. -Ac XMLElementDecl edecl = new XMLElementDecl(); fSchemaGrammar.getElementDecl(elementIndex, edecl); for (int i = 0; i < size; i++) { Element ic = (Element)identityConstraints.elementAt(i); String icName = ic.getLocalName(); if ( icName.equals(SchemaSymbols.ELT_KEY) ) { traverseKey(ic, edecl); } else if ( icName.equals(SchemaSymbols.ELT_UNIQUE) ) { traverseUnique(ic, edecl); } fSchemaGrammar.setElementDecl(elementIndex, edecl); } // loop over vector elements } // if size > 0 } // traverseIdentityNameConstraints(Vector) private void traverseIdentityRefConstraintsFor(int elementIndex, Vector identityConstraints) throws Exception { // iterate over identity constraints for this element int size = identityConstraints != null ? identityConstraints.size() : 0; if (size > 0) { // REVISIT: Use cached copy. -Ac XMLElementDecl edecl = new XMLElementDecl(); fSchemaGrammar.getElementDecl(elementIndex, edecl); for (int i = 0; i < size; i++) { Element ic = (Element)identityConstraints.elementAt(i); String icName = ic.getLocalName(); if ( icName.equals(SchemaSymbols.ELT_KEYREF) ) { traverseKeyRef(ic, edecl); } fSchemaGrammar.setElementDecl(elementIndex, edecl); } // loop over vector elements } // if size > 0 } // traverseIdentityRefConstraints(Vector) private void traverseUnique(Element uElem, XMLElementDecl eDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(uElem, scope); // create identity constraint String uName = uElem.getAttribute(SchemaSymbols.ATT_NAME); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: traverseUnique(\""+uElem.getNodeName()+"\") ["+uName+']'); } String eName = getElementNameFor(uElem); Unique unique = new Unique(uName, eName); if(fIdentityConstraintNames.get(fTargetNSURIString+","+uName) != null) { reportGenericSchemaError("More than one identity constraint named " + uName); } fIdentityConstraintNames.put(fTargetNSURIString+","+uName, unique); // get selector and fields traverseIdentityConstraint(unique, uElem); // add to element decl eDecl.unique.addElement(unique); } // traverseUnique(Element,XMLElementDecl) private void traverseKey(Element kElem, XMLElementDecl eDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(kElem, scope); // create identity constraint String kName = kElem.getAttribute(SchemaSymbols.ATT_NAME); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: traverseKey(\""+kElem.getNodeName()+"\") ["+kName+']'); } String eName = getElementNameFor(kElem); Key key = new Key(kName, eName); if(fIdentityConstraintNames.get(fTargetNSURIString+","+kName) != null) { reportGenericSchemaError("More than one identity constraint named " + kName); } fIdentityConstraintNames.put(fTargetNSURIString+","+kName, key); // get selector and fields traverseIdentityConstraint(key, kElem); // add to element decl eDecl.key.addElement(key); } // traverseKey(Element,XMLElementDecl) private void traverseKeyRef(Element krElem, XMLElementDecl eDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(krElem, scope); // create identity constraint String krName = krElem.getAttribute(SchemaSymbols.ATT_NAME); String kName = krElem.getAttribute(SchemaSymbols.ATT_REFER); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: traverseKeyRef(\""+krElem.getNodeName()+"\") ["+krName+','+kName+']'); } if(fIdentityConstraintNames.get(fTargetNSURIString+","+krName) != null) { reportGenericSchemaError("More than one identity constraint named " + krName); } // verify that key reference "refer" attribute is valid String prefix = ""; String localpart = kName; int colonptr = kName.indexOf(":"); if ( colonptr > 0) { prefix = kName.substring(0,colonptr); localpart = kName.substring(colonptr+1); } String uriStr = resolvePrefixToURI(prefix); IdentityConstraint kId = (IdentityConstraint)fIdentityConstraintNames.get(uriStr+","+localpart); if (kId== null) { reportSchemaError(SchemaMessageProvider.KeyRefReferNotFound, new Object[]{krName,kName}); return; } String eName = getElementNameFor(krElem); KeyRef keyRef = new KeyRef(krName, kId, eName); // add to element decl traverseIdentityConstraint(keyRef, krElem); // add key reference to element decl eDecl.keyRef.addElement(keyRef); // store in fIdentityConstraintNames so can flag schemas in which multiple // keyrefs with the same name are present. fIdentityConstraintNames.put(fTargetNSURIString+","+krName, keyRef); } // traverseKeyRef(Element,XMLElementDecl) private void traverseIdentityConstraint(IdentityConstraint ic, Element icElem) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(icElem, scope); // check for <annotation> and get selector Element sElem = XUtil.getFirstChildElement(icElem); if(sElem == null) { // REVISIT: localize reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)"); return; } sElem = checkContent( icElem, sElem, false); // General Attribute Checking attrValues = fGeneralAttrCheck.checkAttributes(sElem, scope); if(!sElem.getLocalName().equals(SchemaSymbols.ELT_SELECTOR)) { // REVISIT: localize reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)"); } // and make sure <selector>'s content is fine: checkContent(icElem, XUtil.getFirstChildElement(sElem), true); String sText = sElem.getAttribute(SchemaSymbols.ATT_XPATH); sText = sText.trim(); Selector.XPath sXpath = null; try { // REVISIT: Must get ruling from XML Schema working group // regarding whether steps in the XPath must be // fully qualified if the grammar has a target // namespace. -Ac // RESOLUTION: Yes. sXpath = new Selector.XPath(sText, fStringPool, fNamespacesScope); Selector selector = new Selector(sXpath, ic); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: selector: "+selector); } ic.setSelector(selector); } catch (XPathException e) { // REVISIT: Add error message. reportGenericSchemaError(e.getMessage()); return; } // get fields Element fElem = XUtil.getNextSiblingElement(sElem); if(fElem == null) { // REVISIT: localize reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)"); } while (fElem != null) { // General Attribute Checking attrValues = fGeneralAttrCheck.checkAttributes(fElem, scope); if(!fElem.getLocalName().equals(SchemaSymbols.ELT_FIELD)) // REVISIT: localize reportGenericSchemaError("The content of an identity constraint must match (annotation?, selector, field+)"); // and make sure <field>'s content is fine: checkContent(icElem, XUtil.getFirstChildElement(fElem), true); String fText = fElem.getAttribute(SchemaSymbols.ATT_XPATH); fText = fText.trim(); try { // REVISIT: Must get ruling from XML Schema working group // regarding whether steps in the XPath must be // fully qualified if the grammar has a target // namespace. -Ac // RESOLUTION: Yes. Field.XPath fXpath = new Field.XPath(fText, fStringPool, fNamespacesScope); // REVISIT: Get datatype validator. -Ac // cannot statically determine type of field; not just because of descendant/union // but because of <any> and <anyAttribute>. - NG // DatatypeValidator validator = getDatatypeValidatorFor(parent, sXpath, fXpath); // if (DEBUG_IC_DATATYPES) { // System.out.println("<ICD>: datatype validator: "+validator); // } // must find DatatypeValidator in the Validator... Field field = new Field(fXpath, ic); if (DEBUG_IDENTITY_CONSTRAINTS) { System.out.println("<IC>: field: "+field); } ic.addField(field); } catch (XPathException e) { // REVISIT: Add error message. reportGenericSchemaError(e.getMessage()); return; } fElem = XUtil.getNextSiblingElement(fElem); } } // traverseIdentityConstraint(IdentityConstraint,Element) /* This code is no longer used because datatypes can't be found statically for ID constraints. private DatatypeValidator getDatatypeValidatorFor(Element element, Selector.XPath sxpath, Field.XPath fxpath) throws Exception { // variables String ename = element.getAttribute("name"); if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: XMLValidator#getDatatypeValidatorFor("+ ename+','+sxpath+','+fxpath+')'); } int localpart = fStringPool.addSymbol(ename); String targetNamespace = fSchemaRootElement.getAttribute("targetNamespace"); int uri = fStringPool.addSymbol(targetNamespace); int edeclIndex = fSchemaGrammar.getElementDeclIndex(uri, localpart, Grammar.TOP_LEVEL_SCOPE); // walk selector XPath.LocationPath spath = sxpath.getLocationPath(); XPath.Step[] ssteps = spath.steps; for (int i = 0; i < ssteps.length; i++) { XPath.Step step = ssteps[i]; XPath.Axis axis = step.axis; XPath.NodeTest nodeTest = step.nodeTest; switch (axis.type) { case XPath.Axis.ATTRIBUTE: { // REVISIT: Add message. -Ac reportGenericSchemaError("not allowed to select attribute"); return null; } case XPath.Axis.CHILD: { int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex); if (index == -1) { index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE); } if (index == -1) { // REVISIT: Add message. -Ac reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"'); return null; } edeclIndex = index; break; } case XPath.Axis.SELF: { // no-op break; } default: { // REVISIT: Add message. -Ac reportGenericSchemaError("invalid selector axis"); return null; } } } // walk field XPath.LocationPath fpath = fxpath.getLocationPath(); XPath.Step[] fsteps = fpath.steps; for (int i = 0; i < fsteps.length; i++) { XPath.Step step = fsteps[i]; XPath.Axis axis = step.axis; XPath.NodeTest nodeTest = step.nodeTest; switch (axis.type) { case XPath.Axis.ATTRIBUTE: { if (i != fsteps.length - 1) { // REVISIT: Add message. -Ac reportGenericSchemaError("attribute must be last step"); return null; } // look up validator int adeclIndex = fSchemaGrammar.getAttributeDeclIndex(edeclIndex, nodeTest.name); if (adeclIndex == -1) { // REVISIT: Add message. -Ac reportGenericSchemaError("no such attribute \""+fStringPool.toString(nodeTest.name.rawname)+'"'); } XMLAttributeDecl adecl = new XMLAttributeDecl(); fSchemaGrammar.getAttributeDecl(adeclIndex, adecl); DatatypeValidator validator = adecl.datatypeValidator; return validator; } case XPath.Axis.CHILD: { int index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, edeclIndex); if (index == -1) { index = fSchemaGrammar.getElementDeclIndex(nodeTest.name, Grammar.TOP_LEVEL_SCOPE); } if (index == -1) { // REVISIT: Add message. -Ac reportGenericSchemaError("no such element \""+fStringPool.toString(nodeTest.name.rawname)+'"'); return null; } edeclIndex = index; if (i < fsteps.length - 1) { break; } // NOTE: Let fall through to self case so that we // avoid duplicating code. -Ac } case XPath.Axis.SELF: { // look up validator, if needed if (i == fsteps.length - 1) { XMLElementDecl edecl = new XMLElementDecl(); fSchemaGrammar.getElementDecl(edeclIndex, edecl); if (edecl.type != XMLElementDecl.TYPE_SIMPLE) { // REVISIT: Add message. -Ac reportGenericSchemaError("selected element is not of simple type"); return null; } DatatypeValidator validator = edecl.datatypeValidator; if (validator == null) validator = new StringDatatypeValidator(); return validator; } break; } default: { // REVISIT: Add message. -Ac reportGenericSchemaError("invalid selector axis"); return null; } } } // no validator! // REVISIT: Add message. -Ac reportGenericSchemaError("No datatype validator for field "+fxpath+ " of element "+ename); return null; } // getDatatypeValidatorFor(XPath):DatatypeValidator */ // back in to live code... private String getElementNameFor(Element icnode) { Element enode = (Element)icnode.getParentNode(); String ename = enode.getAttribute("name"); if (ename.length() == 0) { ename = enode.getAttribute("ref"); } return ename; } // getElementNameFor(Element):String int getLocalPartIndex(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return fStringPool.addSymbol(localpart); } String getLocalPart(String fullName){ int colonAt = fullName.indexOf(":"); String localpart = fullName; if ( colonAt > -1 ) { localpart = fullName.substring(colonAt+1); } return localpart; } int getPrefixIndex(String fullName){ int colonAt = fullName.indexOf(":"); String prefix = ""; if ( colonAt > -1 ) { prefix = fullName.substring(0,colonAt); } return fStringPool.addSymbol(prefix); } String getPrefix(String fullName){ int colonAt = fullName.indexOf(":"); String prefix = ""; if ( colonAt > -1 ) { prefix = fullName.substring(0,colonAt); } return prefix; } private void checkSubstitutionGroupOK(Element elementDecl, Element substitutionGroupElementDecl, boolean noErrorSoFar, int substitutionGroupElementDeclIndex, SchemaGrammar substitutionGroupGrammar, ComplexTypeInfo typeInfo, ComplexTypeInfo substitutionGroupEltTypeInfo, DatatypeValidator dv, DatatypeValidator substitutionGroupEltDV) throws Exception { // here we must do two things: // 1. Make sure there actually *is* a relation between the types of // the element being nominated and the element doing the nominating; // (see PR 3.3.6 point #3 in the first tableau, for instance; this // and the corresponding tableaux from 3.4.6 and 3.14.6 rule out the nominated // element having an anonymous type declaration. // 2. Make sure the nominated element allows itself to be nominated by // an element with the given type-relation. // Note: we assume that (complex|simple)Type processing checks // whether the type in question allows itself to // be modified as this element desires. // Check for type relationship; // that is, make sure that the type we're deriving has some relationship // to substitutionGroupElt's type. if (typeInfo != null) { int derivationMethod = typeInfo.derivedBy; if(typeInfo.baseComplexTypeInfo == null) { if (typeInfo.baseDataTypeValidator != null) { // take care of complexType based on simpleType case... DatatypeValidator dTemp = typeInfo.baseDataTypeValidator; for(; dTemp != null; dTemp = dTemp.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTemp == substitutionGroupEltDV) break; } if (dTemp == null) { if(substitutionGroupEltDV instanceof UnionDatatypeValidator) { // dv must derive from one of its members... Vector subUnionMemberDV = ((UnionDatatypeValidator)substitutionGroupEltDV).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); boolean found = false; for (int i=0; i<subUnionSize && !found; i++) { DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i); DatatypeValidator dTempOrig = typeInfo.baseDataTypeValidator; for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTempSub == dTempOrig) { found = true; break; } } } if(!found) { // REVISIT: localize reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group"); noErrorSoFar = false; } } else { // REVISIT: localize reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group"); noErrorSoFar = false; } } else { // now let's see if substitutionGroup element allows this: if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) { noErrorSoFar = false; // REVISIT: localize reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " cannot be part of the substitution group headed by " + substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); } } } else { // REVISIT: localize reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " which is part of a substitution must have a type which derives from the type of the element at the head of the substitution group"); noErrorSoFar = false; } } else { String eltBaseName = typeInfo.baseComplexTypeInfo.typeName; ComplexTypeInfo subTypeInfo = substitutionGroupEltTypeInfo; for (; subTypeInfo != null && !subTypeInfo.typeName.equals(eltBaseName); subTypeInfo = subTypeInfo.baseComplexTypeInfo); if (subTypeInfo == null) { // then this type isn't in the chain... // REVISIT: localize reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type whose base is " + eltBaseName + "; this basetype does not derive from the type of the element at the head of the substitution group"); noErrorSoFar = false; } else { // type is fine; does substitutionElement allow this? if((derivationMethod & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) { noErrorSoFar = false; // REVISIT: localize reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " cannot be part of the substitution group headed by " + substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); } } } } else if (dv != null) { // do simpleType case... // first, check for type relation. if (!(checkSimpleTypeDerivationOK(dv,substitutionGroupEltDV))) { // REVISIT: localize reportGenericSchemaError("Element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " has a type which does not derive from the type of the element at the head of the substitution group"); noErrorSoFar = false; } else { // now let's see if substitutionGroup element allows this: if((SchemaSymbols.RESTRICTION & substitutionGroupGrammar.getElementDeclFinalSet(substitutionGroupElementDeclIndex)) != 0) { noErrorSoFar = false; // REVISIT: localize reportGenericSchemaError("element " + elementDecl.getAttribute(SchemaSymbols.ATT_NAME) + " cannot be part of the substitution group headed by " + substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); } } } } // // A utility method to check whether a particular datatypevalidator d, was validly // derived from another datatypevalidator, b // private boolean checkSimpleTypeDerivationOK(DatatypeValidator d, DatatypeValidator b) { DatatypeValidator dTemp = d; for(; dTemp != null; dTemp = dTemp.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTemp == b) break; } if (dTemp == null) { // now if b is a union, then we can // derive from it if we derive from any of its members' types. if(b instanceof UnionDatatypeValidator) { // d must derive from one of its members... Vector subUnionMemberDV = ((UnionDatatypeValidator)b).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); boolean found = false; for (int i=0; i<subUnionSize && !found; i++) { DatatypeValidator dTempSub = (DatatypeValidator)subUnionMemberDV.elementAt(i); DatatypeValidator dTempOrig = d; for(; dTempOrig != null; dTempOrig = dTempOrig.getBaseValidator()) { // WARNING!!! This uses comparison by reference andTemp is thus inherently suspect! if(dTempSub == dTempOrig) { found = true; break; } } } if(!found) { return false; } } else { return false; } } return true; } // this originally-simple method is much -complicated by the fact that, when we're // redefining something, we've not only got to look at the space of the thing // we're redefining but at the original schema too. // The idea is to start from the top, then go down through // our list of schemas until we find what we aant. // This should not often be necessary, because we've processed // all redefined schemas, but three are conditions in which // not all elements so redefined may have been promoted to // the topmost level. private Element getTopLevelComponentByName(String componentCategory, String name) throws Exception { Element child = null; SchemaInfo curr = fSchemaInfoListRoot; for (; curr != null || curr == fSchemaInfoListRoot; curr = curr.getNext()) { if (curr != null) curr.restore(); if ( componentCategory.equals(SchemaSymbols.ELT_GROUP) ) { child = (Element) fSchemaGrammar.topLevelGroupDecls.get(name); } else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP ) && fSchemaInfoListRoot == null ) { child = (Element) fSchemaGrammar.topLevelAttrGrpDecls.get(name); } else if ( componentCategory.equals(SchemaSymbols.ELT_ATTRIBUTE ) ) { child = (Element) fSchemaGrammar.topLevelAttrDecls.get(name); } if (child != null ) { break; } child = XUtil.getFirstChildElement(fSchemaRootElement); if (child == null) { continue; } while (child != null ){ if ( child.getLocalName().equals(componentCategory)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) { break; } } else if (fRedefineSucceeded && child.getLocalName().equals(SchemaSymbols.ELT_REDEFINE)) { Element gChild = XUtil.getFirstChildElement(child); while (gChild != null ){ if (gChild.getLocalName().equals(componentCategory)) { if (gChild.getAttribute(SchemaSymbols.ATT_NAME).equals(name)) { break; } } gChild = XUtil.getNextSiblingElement(gChild); } if (gChild != null) { child = gChild; break; } } child = XUtil.getNextSiblingElement(child); } if (child != null || fSchemaInfoListRoot == null) break; } // have to reset fSchemaInfoList if(curr != null) curr.restore(); else if (fSchemaInfoListRoot != null) fSchemaInfoListRoot.restore(); return child; } private boolean isTopLevel(Element component) { String parentName = component.getParentNode().getLocalName(); return (parentName.endsWith(SchemaSymbols.ELT_SCHEMA)) || (parentName.endsWith(SchemaSymbols.ELT_REDEFINE)) ; } DatatypeValidator getTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception { // The following impl is for the case where every Schema Grammar has its own instance of DatatypeRegistry. // Now that we have only one DataTypeRegistry used by all schemas. this is not needed. /***** Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; DatatypeValidator dv = (DatatypeValidator) fSchemaGrammar.getDatatypeRegistry().getDatatypeValidator(localpart); return dv; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeValidatorFromNS"); } return null; /*****/ return getDatatypeValidator(newSchemaURI, localpart); } ComplexTypeInfo getTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; ComplexTypeInfo typeInfo = (ComplexTypeInfo) sGrammar.getComplexTypeRegistry().get(newSchemaURI+","+localpart); return typeInfo; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getTypeInfoFromNS"); } return null; } DatatypeValidator getElementDeclTypeValidatorFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI), fStringPool.addSymbol(localpart), TOP_LEVEL_SCOPE); DatatypeValidator dv = null; if (eltIndex>-1) { sGrammar.getElementDecl(eltIndex, fTempElementDecl); dv = fTempElementDecl.datatypeValidator; } else { reportGenericSchemaError("could not find global element : '" + localpart + " in the SchemaGrammar "+newSchemaURI); } return dv; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getELementDeclTypeValidatorFromNS"); } return null; } ComplexTypeInfo getElementDeclTypeInfoFromNS(String newSchemaURI, String localpart) throws Exception { Grammar grammar = fGrammarResolver.getGrammar(newSchemaURI); if (grammar != null && grammar instanceof SchemaGrammar) { SchemaGrammar sGrammar = (SchemaGrammar) grammar; int eltIndex = sGrammar.getElementDeclIndex(fStringPool.addSymbol(newSchemaURI), fStringPool.addSymbol(localpart), TOP_LEVEL_SCOPE); ComplexTypeInfo typeInfo = null; if (eltIndex>-1) { typeInfo = sGrammar.getElementComplexTypeInfo(eltIndex); } else { reportGenericSchemaError("could not find global element : '" + localpart + " in the SchemaGrammar "+newSchemaURI); } return typeInfo; } else { reportGenericSchemaError("could not resolve URI : " + newSchemaURI + " to a SchemaGrammar in getElementDeclTypeInfoFromNS"); } return null; } /** * Traverses notation declaration * and saves it in a registry. * Notations are stored in registry with the following * key: "uri:localname" * * @param notation child <notation> * @return local name of notation * @exception Exception */ private String traverseNotationDecl( Element notation ) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(notation, scope); String name = notation.getAttribute(SchemaSymbols.ATT_NAME); String qualifiedName =name; if (fTargetNSURIString.length () != 0) { qualifiedName = fTargetNSURIString+":"+name; } if (fNotationRegistry.get(qualifiedName)!=null) { return name; } String publicId = notation.getAttribute(SchemaSymbols.ATT_PUBLIC); String systemId = notation.getAttribute(SchemaSymbols.ATT_SYSTEM); if (publicId.length() == 0 && systemId.length() == 0) { //REVISIT: update error messages reportGenericSchemaError("<notation> declaration is invalid"); } if (name.equals("")) { //REVISIT: update error messages reportGenericSchemaError("<notation> declaration does not have a name"); } fNotationRegistry.put(qualifiedName, name); //we don't really care if something inside <notation> is wrong.. checkContent( notation, XUtil.getFirstChildElement(notation), true ); //REVISIT: wait for DOM L3 APIs to pass info to application //REVISIT: SAX2 does not support notations. API should be changed. return name; } /** * This methods will traverse notation from current schema, * as well as from included or imported schemas * * @param notationName * localName of notation * @param uriStr uriStr for schema grammar * @return return local name for Notation (if found), otherwise * return empty string; * @exception Exception */ private String traverseNotationFromAnotherSchema( String notationName , String uriStr ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseNotationDeclFromAnotherSchema, "+ "schema uri: " + uriStr +", groupName: " + notationName); return ""; } String savedNSURIString = fTargetNSURIString; fTargetNSURIString = fStringPool.toString(fStringPool.addSymbol(aGrammar.getTargetNamespaceURI())); if (DEBUGGING) { System.out.println("[traverseFromAnotherSchema]: " + fTargetNSURIString); } String qualifiedName = fTargetNSURIString + ":" + notationName; String localName = (String)fNotationRegistry.get(qualifiedName); if(localName != null ) // we've already traversed this notation return localName; //notation decl has not been traversed yet Element notationDecl = (Element) aGrammar.topLevelNotationDecls.get((Object)notationName); if (notationDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no notation named \"" + notationName + "\" was defined in schema : " + uriStr); return ""; } localName = traverseNotationDecl(notationDecl); fTargetNSURIString = savedNSURIString; return localName; } // end of method traverseNotationFromAnotherSchema /** * Traverse Group Declaration. * * <group * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger * name = NCName * ref = QName> * Content: (annotation? , (all | choice | sequence)?) * <group/> * * @param elementDecl * @return * @exception Exception */ private int traverseGroupDecl( Element groupDecl ) throws Exception { // General Attribute Checking int scope = isTopLevel(groupDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(groupDecl, scope); String groupName = groupDecl.getAttribute(SchemaSymbols.ATT_NAME); String ref = groupDecl.getAttribute(SchemaSymbols.ATT_REF); Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true ); if (!ref.equals("")) { if (isTopLevel(groupDecl)) // REVISIT: localize reportGenericSchemaError ( "A group with \"ref\" present must not have <schema> or <redefine> as its parent"); if (!groupName.equals("")) // REVISIT: localize reportGenericSchemaError ( "group " + groupName + " cannot refer to another group, but it refers to " + ref); // there should be no children for <group ref="..."> if (XUtil.getFirstChildElement(groupDecl)!=null) reportGenericSchemaError ( "A group with \"ref\" present must not have children"); String prefix = ""; String localpart = ref; int colonptr = ref.indexOf(":"); if ( colonptr > 0) { prefix = ref.substring(0,colonptr); localpart = ref.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriStr = resolvePrefixToURI(prefix); if (!uriStr.equals(fTargetNSURIString)) { return traverseGroupDeclFromAnotherSchema(localpart, uriStr); } Object contentSpecHolder = fGroupNameRegistry.get(uriStr + "," + localpart); if(contentSpecHolder != null ) { // we may have already traversed this group boolean fail = false; int contentSpecHolderIndex = 0; try { contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue(); } catch (ClassCastException c) { fail = true; } if(!fail) { return contentSpecHolderIndex; } } // Check if we are in the middle of traversing this group (i.e. circular references) if (fCurrentGroupNameStack.search((Object)localpart) > - 1) { reportGenericSchemaError("mg-props-correct: Circular definition for group " + localpart); return -2; } int contentSpecIndex = -1; Element referredGroup = getTopLevelComponentByName(SchemaSymbols.ELT_GROUP,localpart); if (referredGroup == null) { // REVISIT: Localize reportGenericSchemaError("Group " + localpart + " not found in the Schema"); //REVISIT, this should be some custom Exception //throw new RuntimeException("Group " + localpart + " not found in the Schema"); } else { contentSpecIndex = traverseGroupDecl(referredGroup); } return contentSpecIndex; } else if (groupName.equals("")) // REVISIT: Localize reportGenericSchemaError("a <group> must have a name or a ref present"); String qualifiedGroupName = fTargetNSURIString + "," + groupName; Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName); if(contentSpecHolder != null ) { // we may have already traversed this group boolean fail = false; int contentSpecHolderIndex = 0; try { contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue(); } catch (ClassCastException c) { fail = true; } if(!fail) { return contentSpecHolderIndex; } } // if we're here then we're traversing a top-level group that we've never seen before. // Push the group name onto a stack, so that we can check for circular groups fCurrentGroupNameStack.push(groupName); // Save the scope and set the current scope to -1 int savedScope = fCurrentScope; fCurrentScope = -1; int index = -2; boolean illegalChild = false; String childName = (child != null) ? child.getLocalName() : ""; if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); } else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) { illegalChild = true; reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } //Must have all or choice or sequence child. if (child == null) { reportGenericSchemaError("Named group must contain an 'all', 'choice' or 'sequence' child"); } else if (XUtil.getNextSiblingElement(child) != null) { illegalChild = true; reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if ( ! illegalChild && child != null) { index = handleOccurrences(index, child, CHILD_OF_GROUP); } contentSpecHolder = new Integer(index); fCurrentGroupNameStack.pop(); fCurrentScope = savedScope; fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder); return index; } private int traverseGroupDeclFromAnotherSchema( String groupName , String uriStr ) throws Exception { SchemaGrammar aGrammar = (SchemaGrammar) fGrammarResolver.getGrammar(uriStr); if (uriStr == null || aGrammar==null ||! (aGrammar instanceof SchemaGrammar) ) { // REVISIT: Localize reportGenericSchemaError("!!Schema not found in #traverseGroupDeclFromAnotherSchema, "+ "schema uri: " + uriStr +", groupName: " + groupName); return -1; } Element groupDecl = (Element) aGrammar.topLevelGroupDecls.get((Object)groupName); if (groupDecl == null) { // REVISIT: Localize reportGenericSchemaError( "no group named \"" + groupName + "\" was defined in schema : " + uriStr); return -1; } NamespacesScope saveNSMapping = fNamespacesScope; int saveTargetNSUri = fTargetNSURI; fTargetNSURI = fStringPool.addSymbol(aGrammar.getTargetNamespaceURI()); fNamespacesScope = aGrammar.getNamespacesScope(); Element child = checkContent( groupDecl, XUtil.getFirstChildElement(groupDecl), true ); String qualifiedGroupName = fTargetNSURIString + "," + groupName; Object contentSpecHolder = fGroupNameRegistry.get(qualifiedGroupName); if(contentSpecHolder != null ) { // we may have already traversed this group boolean fail = false; int contentSpecHolderIndex = 0; try { contentSpecHolderIndex = ((Integer)contentSpecHolder).intValue(); } catch (ClassCastException c) { fail = true; } if(!fail) { return contentSpecHolderIndex; } } // ------------------------------------ // if we're here then we're traversing a top-level group that we've never seen before. int index = -2; boolean illegalChild = false; String childName = (child != null) ? child.getLocalName() : ""; if (childName.equals(SchemaSymbols.ELT_ALL)) { index = traverseAll(child); } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); } else if (!childName.equals("") || (child != null && XUtil.getNextSiblingElement(child) != null)) { illegalChild = true; reportSchemaError(SchemaMessageProvider.GroupContentRestricted, new Object [] { "group", childName }); } if ( ! illegalChild && child != null) { index = handleOccurrences( index, child); } contentSpecHolder = new Integer(index); fGroupNameRegistry.put(qualifiedGroupName, contentSpecHolder); fNamespacesScope = saveNSMapping; fTargetNSURI = saveTargetNSUri; return index; } // end of method traverseGroupDeclFromAnotherSchema /** * * Traverse the Sequence declaration * * <sequence * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </sequence> * **/ int traverseSequence (Element sequenceDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(sequenceDecl, scope); Element child = checkContent(sequenceDecl, XUtil.getFirstChildElement(sequenceDecl), true); int csnType = XMLContentSpec.CONTENTSPECNODE_SEQ; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; boolean seeParticle = false; String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); // A content type of all can only appear // as the content type of a complex type definition. if (hasAllContent(index)) { reportSchemaError(SchemaMessageProvider.AllContentLimited, new Object [] { "sequence" }); continue; } seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError( SchemaMessageProvider.SeqChoiceContentRestricted, new Object [] { "sequence", childName }); continue; } if (index != -2) hadContent = true; if (seeParticle) { index = handleOccurrences( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent) { if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion()) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); } return left; } /** * * Traverse the Choice declaration * * <choice * id = ID * maxOccurs = string * minOccurs = nonNegativeInteger> * Content: (annotation? , (element | group | choice | sequence | any)*) * </choice> * **/ int traverseChoice (Element choiceDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(choiceDecl, scope); // REVISIT: traverseChoice, traverseSequence can be combined Element child = checkContent(choiceDecl, XUtil.getFirstChildElement(choiceDecl), true); int csnType = XMLContentSpec.CONTENTSPECNODE_CHOICE; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; boolean seeParticle = false; String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_GROUP)) { index = traverseGroupDecl(child); // A model group whose {compositor} is "all" can only appear // as the {content type} of a complex type definition. if (hasAllContent(index)) { reportSchemaError(SchemaMessageProvider.AllContentLimited, new Object [] { "choice" }); continue; } seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { index = traverseChoice(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { index = traverseSequence(child); seeParticle = true; } else if (childName.equals(SchemaSymbols.ELT_ANY)) { index = traverseAny(child); seeParticle = true; } else { reportSchemaError( SchemaMessageProvider.SeqChoiceContentRestricted, new Object [] { "choice", childName }); continue; } if (index != -2) hadContent = true; if (seeParticle) { index = handleOccurrences( index, child); } if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent) { if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion()) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); } return left; } /** * * Traverse the "All" declaration * * <all * id = ID * maxOccurs = 1 : 1 * minOccurs = (0 | 1) : 1> * Content: (annotation? , element*) * </all> **/ int traverseAll(Element allDecl) throws Exception { // General Attribute Checking int scope = GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(allDecl, scope); Element child = checkContent(allDecl, XUtil.getFirstChildElement(allDecl), true); int csnType = XMLContentSpec.CONTENTSPECNODE_ALL; int left = -2; int right = -2; boolean hadContent = false; for (; child != null; child = XUtil.getNextSiblingElement(child)) { int index = -2; String childName = child.getLocalName(); // Only elements are allowed in <all> if (childName.equals(SchemaSymbols.ELT_ELEMENT)) { QName eltQName = traverseElementDecl(child); index = fSchemaGrammar.addContentSpecNode( XMLContentSpec.CONTENTSPECNODE_LEAF, eltQName.localpart, eltQName.uri, false); index = handleOccurrences(index, child, PROCESSING_ALL); } else { reportSchemaError(SchemaMessageProvider.AllContentRestricted, new Object [] { childName }); continue; } hadContent = true; if (left == -2) { left = index; } else if (right == -2) { right = index; } else { left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); right = index; } } if (hadContent) { if (right != -2 || fSchemaGrammar.getDeferContentSpecExpansion()) left = fSchemaGrammar.addContentSpecNode(csnType, left, right, false); } return left; } // Determines whether a content spec tree represents an "all" content model private boolean hasAllContent(int contentSpecIndex) { // If the content is not empty, is the top node ALL? if (contentSpecIndex > -1) { XMLContentSpec content = new XMLContentSpec(); fSchemaGrammar.getContentSpec(contentSpecIndex, content); // An ALL node could be optional, so we have to be prepared // to look one level below a ZERO_OR_ONE node for an ALL. if (content.type == XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE) { fSchemaGrammar.getContentSpec(content.value, content); } return (content.type == XMLContentSpec.CONTENTSPECNODE_ALL); } return false; } // utilities from Tom Watson's SchemaParser class // TO DO: Need to make this more conformant with Schema int type parsing private int parseInt (String intString) throws Exception { if ( intString.equals("*") ) { return SchemaSymbols.INFINITY; } else { return Integer.parseInt (intString); } } private int parseSimpleFinal (String finalString) throws Exception { if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.ENUMERATION+SchemaSymbols.RESTRICTION+SchemaSymbols.LIST; } else { int enumerate = 0; int restrict = 0; int list = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ("restriction in set twice"); } } else if ( token.equals (SchemaSymbols.ELT_LIST) ) { if ( list == 0 ) { list = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ("list in set twice"); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid value (" + finalString + ")" ); } } return enumerate+list; } } private int parseDerivationSet (String finalString) throws Exception { if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION; } else { int extend = 0; int restrict = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "extension already in set" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "restriction already in set" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } return extend+restrict; } } private int parseBlockSet (String blockString) throws Exception { if( blockString == null) return fBlockDefault; else if ( blockString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.SUBSTITUTION+SchemaSymbols.EXTENSION+SchemaSymbols.RESTRICTION; } else { int extend = 0; int restrict = 0; int substitute = 0; StringTokenizer t = new StringTokenizer (blockString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ATTVAL_SUBSTITUTION) ) { if ( substitute == 0 ) { substitute = SchemaSymbols.SUBSTITUTION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'substitution' already in the list" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'extension' is already in the list" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'restriction' is already in the list" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid block value (" + blockString + ")" ); } } int defaultVal = extend+restrict+substitute; return (defaultVal == 0 ? fBlockDefault : defaultVal); } } private int parseFinalSet (String finalString) throws Exception { if( finalString == null) { return fFinalDefault; } else if ( finalString.equals (SchemaSymbols.ATTVAL_POUNDALL) ) { return SchemaSymbols.EXTENSION+SchemaSymbols.LIST+SchemaSymbols.RESTRICTION+SchemaSymbols.UNION; } else { int extend = 0; int restrict = 0; int list = 0; int union = 0; StringTokenizer t = new StringTokenizer (finalString, " "); while (t.hasMoreTokens()) { String token = t.nextToken (); if ( token.equals (SchemaSymbols.ELT_UNION) ) { if ( union == 0 ) { union = SchemaSymbols.UNION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'union' is already in the list" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_EXTENSION) ) { if ( extend == 0 ) { extend = SchemaSymbols.EXTENSION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'extension' is already in the list" ); } } else if ( token.equals (SchemaSymbols.ELT_LIST) ) { if ( list == 0 ) { list = SchemaSymbols.LIST; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'list' is already in the list" ); } } else if ( token.equals (SchemaSymbols.ATTVAL_RESTRICTION) ) { if ( restrict == 0 ) { restrict = SchemaSymbols.RESTRICTION; } else { // REVISIT: Localize reportGenericSchemaError ( "The value 'restriction' is already in the list" ); } } else { // REVISIT: Localize reportGenericSchemaError ( "Invalid final value (" + finalString + ")" ); } } int defaultVal = extend+restrict+list+union; return (defaultVal == 0 ? fFinalDefault : defaultVal); } } private void reportGenericSchemaError (String error) throws Exception { if (fErrorReporter == null) { System.err.println("__TraverseSchemaError__ : " + error); } else { reportSchemaError (SchemaMessageProvider.GenericError, new Object[] { error }); } } private void reportSchemaError(int major, Object args[]) throws Exception { if (fErrorReporter == null) { System.out.println("__TraverseSchemaError__ : " + SchemaMessageProvider.fgMessageKeys[major]); for (int i=0; i< args.length ; i++) { System.out.println((String)args[i]); } } else { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, major, SchemaMessageProvider.MSG_NONE, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } /** Don't check the following code in because it creates a dependency on the serializer, preventing to package the parser without the serializer //Unit Test here public static void main(String args[] ) { if( args.length != 1 ) { System.out.println( "Error: Usage java TraverseSchema yourFile.xsd" ); System.exit(0); } DOMParser parser = new IgnoreWhitespaceParser(); parser.setEntityResolver( new Resolver() ); parser.setErrorHandler( new ErrorHandler() ); try { parser.setFeature("http://xml.org/sax/features/validation", false); parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false); }catch( org.xml.sax.SAXNotRecognizedException e ) { e.printStackTrace(); }catch( org.xml.sax.SAXNotSupportedException e ) { e.printStackTrace(); } try { parser.parse( args[0]); }catch( IOException e ) { e.printStackTrace(); }catch( SAXException e ) { e.printStackTrace(); } Document document = parser.getDocument(); //Our Grammar OutputFormat format = new OutputFormat( document ); java.io.StringWriter outWriter = new java.io.StringWriter(); XMLSerializer serial = new XMLSerializer( outWriter,format); TraverseSchema tst = null; try { Element root = document.getDocumentElement();// This is what we pass to TraverserSchema //serial.serialize( root ); //System.out.println(outWriter.toString()); tst = new TraverseSchema( root, new StringPool(), new SchemaGrammar(), (GrammarResolver) new GrammarResolverImpl() ); } catch (Exception e) { e.printStackTrace(System.err); } parser.getDocument(); } **/ static class Resolver implements EntityResolver { private static final String SYSTEM[] = { "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd", "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd", "http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent", }; private static final String PATH[] = { "structures.dtd", "datatypes.dtd", "versionInfo.ent", }; public InputSource resolveEntity(String publicId, String systemId) throws IOException { // looking for the schema DTDs? for (int i = 0; i < SYSTEM.length; i++) { if (systemId.equals(SYSTEM[i])) { InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i])); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } // use default resolution return null; } // resolveEntity(String,String):InputSource } // class Resolver static class ErrorHandler implements org.xml.sax.ErrorHandler { /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); throw ex; } // // Private methods // /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId_ = ex.getSystemId(); if (systemId_ != null) { int index = systemId_.lastIndexOf('/'); if (index != -1) systemId_ = systemId_.substring(index + 1); str.append(systemId_); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String } static class IgnoreWhitespaceParser extends DOMParser { public void ignorableWhitespace(char ch[], int start, int length) {} public void ignorableWhitespace(int dataIdx) {} } // class IgnoreWhitespaceParser // When in a <redefine>, type definitions being used (and indeed // refs to <group>'s and <attributeGroup>'s) may refer to info // items either in the schema being redefined, in the <redefine>, // or else in the schema doing the redefining. Because of this // latter we have to be prepared sometimes to look for our type // definitions outside the schema stored in fSchemaRootElement. // This simple class does this; it's just a linked list that // lets us look at the <schema>'s on the queue; note also that this // should provide us with a mechanism to handle nested <redefine>'s. // It's also a handy way of saving schema info when importing/including; saves some code. public class SchemaInfo { private Element saveRoot; private SchemaInfo nextRoot; private SchemaInfo prevRoot; private String savedSchemaURL = fCurrentSchemaURL; private boolean saveElementDefaultQualified = fElementDefaultQualified; private boolean saveAttributeDefaultQualified = fAttributeDefaultQualified; private int saveScope = fCurrentScope; private int saveBlockDefault = fBlockDefault; private int saveFinalDefault = fFinalDefault; private NamespacesScope saveNamespacesScope = fNamespacesScope; public SchemaInfo ( boolean saveElementDefaultQualified, boolean saveAttributeDefaultQualified, int saveBlockDefault, int saveFinalDefault, int saveScope, String savedSchemaURL, Element saveRoot, NamespacesScope saveNamespacesScope, SchemaInfo nextRoot, SchemaInfo prevRoot) { this.saveElementDefaultQualified = saveElementDefaultQualified; this.saveAttributeDefaultQualified = saveAttributeDefaultQualified; this.saveBlockDefault = saveBlockDefault; this.saveFinalDefault = saveFinalDefault; this.saveScope = saveScope ; this.savedSchemaURL = savedSchemaURL; this.saveRoot = saveRoot ; if(saveNamespacesScope != null) this.saveNamespacesScope = (NamespacesScope)saveNamespacesScope.clone(); this.nextRoot = nextRoot; this.prevRoot = prevRoot; } public void setNext (SchemaInfo next) { nextRoot = next; } public SchemaInfo getNext () { return nextRoot; } public void setPrev (SchemaInfo prev) { prevRoot = prev; } public String getCurrentSchemaURL() { return savedSchemaURL; } public SchemaInfo getPrev () { return prevRoot; } public Element getRoot() { return saveRoot; } // NOTE: this has side-effects!!! public void restore() { fCurrentSchemaURL = savedSchemaURL; fCurrentScope = saveScope; fElementDefaultQualified = saveElementDefaultQualified; fAttributeDefaultQualified = saveAttributeDefaultQualified; fBlockDefault = saveBlockDefault; fFinalDefault = saveFinalDefault; fNamespacesScope = (NamespacesScope)saveNamespacesScope.clone(); fSchemaRootElement = saveRoot; } } // class SchemaInfo } // class TraverseSchema
false
true
private QName traverseElementDecl(Element elementDecl) throws Exception { // General Attribute Checking int scope = isTopLevel(elementDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope); int contentSpecType = -1; int contentSpecNodeIndex = -1; int typeNameIndex = -1; int scopeDefined = -2; //signal a error if -2 gets gets through //cause scope can never be -2. DatatypeValidator dv = null; String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT); String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK); String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL); String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED); String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM); String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS); String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS); String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME); String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE); String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF); String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP); String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE); checkEnumerationRequiredNotation(nameStr, typeStr); if ( DEBUGGING ) System.out.println("traversing element decl : " + nameStr ); Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT); Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK); Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT); Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL); Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED); Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM); Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS); Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS); Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME); Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE); Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF); Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP); Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE); if(defaultAtt != null && fixedAtt != null) // REVISIT: localize reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time"); String fromAnotherSchema = null; if (isTopLevel(elementDecl)) { if(nameAtt == null) // REVISIT: localize reportGenericSchemaError("globally-declared element must have a name"); else if (refAtt != null) // REVISIT: localize reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute"); int nameIndex = fStringPool.addSymbol(nameStr); int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE); if (eltKey > -1 ) { return new QName(-1,nameIndex,nameIndex,fTargetNSURI); } } // parse out 'block', 'final', 'nillable', 'abstract' if (blockAtt == null) blockStr = null; int blockSet = parseBlockSet(blockStr); if( (blockStr != null) && !blockStr.equals("") && (!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((blockSet & SchemaSymbols.RESTRICTION) == 0) && (((blockSet & SchemaSymbols.EXTENSION) == 0) && ((blockSet & SchemaSymbols.SUBSTITUTION) == 0))))) reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found"); if (finalAtt == null) finalStr = null; int finalSet = parseFinalSet(finalStr); if( (finalStr != null) && !finalStr.equals("") && (!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((finalSet & SchemaSymbols.RESTRICTION) == 0) && ((finalSet & SchemaSymbols.EXTENSION) == 0)))) reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found"); boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; int elementMiscFlags = 0; if (isNillable) { elementMiscFlags += SchemaSymbols.NILLABLE; } if (isAbstract) { elementMiscFlags += SchemaSymbols.ABSTRACT; } // make the property of the element's value being fixed also appear in elementMiscFlags if(fixedAtt != null) elementMiscFlags += SchemaSymbols.FIXED; //if this is a reference to a global element if (refAtt != null) { //REVISIT top level check for ref if (abstractAtt != null || blockAtt != null || defaultAtt != null || finalAtt != null || fixedAtt != null || formAtt != null || nillableAtt != null || substitutionGroupAtt != null || typeAtt != null) reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2 if (nameAtt != null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute"); Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { if (XUtil.getNextSiblingElement(child) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); else traverseAnnotationDecl(child); } else if (child != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = refStr; int colonptr = refStr.indexOf(":"); if ( colonptr > 0) { prefix = refStr.substring(0,colonptr); localpart = refStr.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriString = resolvePrefixToURI(prefix); QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1, localpartIndex, fStringPool.addSymbol(refStr), uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING); //if from another schema, just return the element QName if (! uriString.equals(fTargetNSURIString) ) { return eltName; } int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE); //if not found, traverse the top level element that if referenced if (elementIndex == -1 ) { Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart); if (targetElement == null ) { // REVISIT: Localize reportGenericSchemaError("Element " + localpart + " not found in the Schema"); //REVISIT, for now, the QName anyway return eltName; //return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString)); } else { // do nothing here, other wise would cause infinite loop for // <element name="recur"><complexType><element ref="recur"> ... //eltName= traverseElementDecl(targetElement); } } return eltName; } else if (nameAtt == null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present"); // Handle the substitutionGroup Element substitutionGroupElementDecl = null; int substitutionGroupElementDeclIndex = -1; boolean noErrorSoFar = true; // // resolving the type for this element right here // ComplexTypeInfo typeInfo = null; // element has a single child element, either a datatype or a type, null if primitive Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child); child = XUtil.getNextSiblingElement(child); } if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) // REVISIT: Localize reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item"); boolean haveAnonType = false; // Handle Anonymous type if there is one if (child != null) { String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute"); } else { // Determine what the type name will be String anonTypeName = genAnonTypeName(child); if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) { // A recursing element using an anonymous type int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,anonTypeName)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl(child); if (typeNameIndex != -1 ) { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'"); } } } haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute"); } else typeNameIndex = traverseSimpleTypeDecl(child); if (typeNameIndex != -1) { dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'"); } contentSpecType = XMLElementDecl.TYPE_SIMPLE; haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (typeAtt == null) { // "ur-typed" leaf contentSpecType = XMLElementDecl.TYPE_ANY; //REVISIT: is this right? //contentSpecType = fStringPool.addSymbol("UR_TYPE"); // set occurrence count contentSpecNodeIndex = -1; } // see if there's something here; it had better be key, keyref or unique. if (child != null) childName = child.getLocalName(); while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY)) || (childName.equals(SchemaSymbols.ELT_KEYREF)) || (childName.equals(SchemaSymbols.ELT_UNIQUE)))) { child = XUtil.getNextSiblingElement(child); if (child != null) { childName = child.getLocalName(); } } if (child != null) { // REVISIT: Localize noErrorSoFar = false; reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)"); } } // handle type="" here if (haveAnonType && (typeAtt != null)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError( "src-element.3: Element '"+ nameStr + "' have both a type attribute and a annoymous type child" ); } // type specified as an attribute and no child is type decl. else if (typeAtt != null) { String prefix = ""; String localpart = typeStr; int colonptr = typeStr.indexOf(":"); if ( colonptr > 0) { prefix = typeStr.substring(0,colonptr); localpart = typeStr.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); // check if the type is from the same Schema if ( !typeURI.equals(fTargetNSURIString) && !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI. fromAnotherSchema = typeURI; typeInfo = getTypeInfoFromNS(typeURI, localpart); if (typeInfo == null) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type " +localpart + " in schema " + typeURI); } } } else { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart); if (typeInfo == null) { dv = getDatatypeValidator(typeURI, localpart); if (dv == null ) if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } else { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (topleveltype != null) { if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { //then we found a recursive element using complexType. // REVISIT: this will be broken when recursing happens between 2 schemas int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,localpart)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl( topleveltype, true ); typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } } else { topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { typeNameIndex = traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } } } } } } // now we need to make sure that our substitution (if any) // is valid, now that we have all the requisite type-related info. String substitutionGroupUri = null; String substitutionGroupLocalpart = null; String substitutionGroupFullName = null; ComplexTypeInfo substitutionGroupEltTypeInfo = null; DatatypeValidator substitutionGroupEltDV = null; SchemaGrammar subGrammar = fSchemaGrammar; boolean ignoreSub = false; if ( substitutionGroupStr.length() > 0 ) { if(refAtt != null) // REVISIT: Localize reportGenericSchemaError("a local element cannot have a substitutionGroup"); substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr)); substitutionGroupLocalpart = getLocalPart(substitutionGroupStr); substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart; if ( !substitutionGroupUri.equals(fTargetNSURIString) ) { Grammar grammar = fGrammarResolver.getGrammar(substitutionGroupUri); if (grammar != null && grammar instanceof SchemaGrammar) { subGrammar = (SchemaGrammar) grammar; substitutionGroupElementDeclIndex = subGrammar.getElementDeclIndex(fStringPool.addSymbol(substitutionGroupUri), fStringPool.addSymbol(substitutionGroupLocalpart), TOP_LEVEL_SCOPE); if (substitutionGroupElementDeclIndex<=-1) { // REVISIT: localize noErrorSoFar = false; reportGenericSchemaError("couldn't find substitutionGroup " + substitutionGroupLocalpart + " referenced by element " + nameStr + " in the SchemaGrammar "+substitutionGroupUri); } else { substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltTypeInfo == null) { substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } else { // REVISIT: locallize noErrorSoFar = false; reportGenericSchemaError("couldn't find a schema grammar with target namespace " + substitutionGroupUri); } } else { substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart); if (substitutionGroupElementDecl == null) { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("unable to locate substitutionGroup affiliation element " +substitutionGroupStr +" in element declaration " +nameStr); } } else { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { // check for mutual recursion! if(fSubstitutionGroupRecursionRegistry.contains(substitutionGroupElementDecl.getAttribute("name"))) { ignoreSub = true; } else { fSubstitutionGroupRecursionRegistry.addElement(substitutionGroupElementDecl.getAttribute("name")); traverseElementDecl(substitutionGroupElementDecl); substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); fSubstitutionGroupRecursionRegistry.remove(substitutionGroupElementDecl.getAttribute("name")); } } } if (!ignoreSub && substitutionGroupElementDeclIndex != -1) { substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex ); if (substitutionGroupEltTypeInfo == null) { fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl); substitutionGroupEltDV = fTempElementDecl.datatypeValidator; if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } if(!ignoreSub) checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, subGrammar, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV); } // this element is ur-type, check its substitutionGroup affiliation. // if there is substitutionGroup affiliation and not type definition found for this element, // then grab substitutionGroup affiliation's type and give it to this element if ( noErrorSoFar && typeInfo == null && dv == null ) { typeInfo = substitutionGroupEltTypeInfo; dv = substitutionGroupEltDV; } if (typeInfo == null && dv==null) { if (noErrorSoFar) { // Actually this Element's type definition is ur-type; contentSpecType = XMLElementDecl.TYPE_ANY; // REVISIT, need to wait till we have wildcards implementation. // ADD attribute wildcards here } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError ("untyped element : " + nameStr ); } } // if element belongs to a compelx type if (typeInfo!=null) { contentSpecNodeIndex = typeInfo.contentSpecHandle; contentSpecType = typeInfo.contentType; scopeDefined = typeInfo.scopeDefined; dv = typeInfo.datatypeValidator; } // if element belongs to a simple type if (dv!=null) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; if (typeInfo == null) { fromAnotherSchema = null; // not to switch schema in this case } } // Now we can handle validation etc. of default and fixed attributes, // since we finally have all the type information. if(fixedAtt != null) defaultStr = fixedStr; if(!defaultStr.equals("")) { if(typeInfo != null && (typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE && typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX && typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) { // REVISIT: Localize reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model"); } if(typeInfo != null && (typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE || typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) { if (!particleEmptiable(typeInfo.contentSpecHandle)) reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable"); } try { if(dv != null) { dv.validate(defaultStr, null); } } catch (InvalidDatatypeValueException ide) { reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr); } } if (!defaultStr.equals("") && dv != null && dv instanceof IDDatatypeValidator) { reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr); } // // Create element decl // int elementNameIndex = fStringPool.addSymbol(nameStr); int localpartIndex = elementNameIndex; int uriIndex = StringPool.EMPTY_STRING; int enclosingScope = fCurrentScope; //refer to 4.3.2 in "XML Schema Part 1: Structures" if ( isTopLevel(elementDecl)) { uriIndex = fTargetNSURI; enclosingScope = TOP_LEVEL_SCOPE; } else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) && (( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified ))) { uriIndex = fTargetNSURI; } //There can never be two elements with the same name and different type in the same scope. int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope); if ( existSuchElementIndex > -1) { fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl); DatatypeValidator edv = fTempElementDecl.datatypeValidator; ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex); if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo)) || ((edv != null)&&(edv != dv)) ) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("duplicate element decl in the same scope : " + fStringPool.toString(localpartIndex)); } } QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex); // add element decl to pool int attrListHead = -1 ; // copy up attribute decls from type object if (typeInfo != null) { attrListHead = typeInfo.attlistHead; } int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined, contentSpecType, contentSpecNodeIndex, attrListHead, dv); if ( DEBUGGING ) { /***/ System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+"," + fStringPool.toString(eltQName.localpart) + ")"+ " eltType:"+typeStr+" contentSpecType:"+contentSpecType+ " SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope + " scopeDefined: " +scopeDefined+"\n"); /***/ } fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); // REVISIT: should we report error if typeInfo was null? // mark element if its type belongs to different Schema. fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema); // set BlockSet, FinalSet, Nillable and Abstract for this element decl fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet); fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet); fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags); fSchemaGrammar.setElementDefault(elementIndex, defaultStr); // setSubstitutionGroupElementFullName fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName); // // key/keyref/unique processing // Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS); if (ic != null) { Integer elementIndexObj = new Integer(elementIndex); Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj); if (identityConstraints == null) { identityConstraints = new Vector(); fIdentityConstraints.put(elementIndexObj, identityConstraints); } while (ic != null) { if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: adding ic for later traversal: "+ic); } identityConstraints.addElement(ic); ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS); } } return eltQName; }// end of method traverseElementDecl(Element)
private QName traverseElementDecl(Element elementDecl) throws Exception { // General Attribute Checking int scope = isTopLevel(elementDecl)? GeneralAttrCheck.ELE_CONTEXT_GLOBAL: GeneralAttrCheck.ELE_CONTEXT_LOCAL; Hashtable attrValues = fGeneralAttrCheck.checkAttributes(elementDecl, scope); int contentSpecType = -1; int contentSpecNodeIndex = -1; int typeNameIndex = -1; int scopeDefined = -2; //signal a error if -2 gets gets through //cause scope can never be -2. DatatypeValidator dv = null; String abstractStr = elementDecl.getAttribute(SchemaSymbols.ATT_ABSTRACT); String blockStr = elementDecl.getAttribute(SchemaSymbols.ATT_BLOCK); String defaultStr = elementDecl.getAttribute(SchemaSymbols.ATT_DEFAULT); String finalStr = elementDecl.getAttribute(SchemaSymbols.ATT_FINAL); String fixedStr = elementDecl.getAttribute(SchemaSymbols.ATT_FIXED); String formStr = elementDecl.getAttribute(SchemaSymbols.ATT_FORM); String maxOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MAXOCCURS); String minOccursStr = elementDecl.getAttribute(SchemaSymbols.ATT_MINOCCURS); String nameStr = elementDecl.getAttribute(SchemaSymbols.ATT_NAME); String nillableStr = elementDecl.getAttribute(SchemaSymbols.ATT_NILLABLE); String refStr = elementDecl.getAttribute(SchemaSymbols.ATT_REF); String substitutionGroupStr = elementDecl.getAttribute(SchemaSymbols.ATT_SUBSTITUTIONGROUP); String typeStr = elementDecl.getAttribute(SchemaSymbols.ATT_TYPE); checkEnumerationRequiredNotation(nameStr, typeStr); if ( DEBUGGING ) System.out.println("traversing element decl : " + nameStr ); Attr abstractAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_ABSTRACT); Attr blockAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_BLOCK); Attr defaultAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_DEFAULT); Attr finalAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FINAL); Attr fixedAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FIXED); Attr formAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_FORM); Attr maxOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MAXOCCURS); Attr minOccursAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS); Attr nameAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NAME); Attr nillableAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_NILLABLE); Attr refAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_REF); Attr substitutionGroupAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_SUBSTITUTIONGROUP); Attr typeAtt = elementDecl.getAttributeNode(SchemaSymbols.ATT_TYPE); if(defaultAtt != null && fixedAtt != null) // REVISIT: localize reportGenericSchemaError("src-element.1: an element cannot have both \"fixed\" and \"default\" present at the same time"); String fromAnotherSchema = null; if (isTopLevel(elementDecl)) { if(nameAtt == null) // REVISIT: localize reportGenericSchemaError("globally-declared element must have a name"); else if (refAtt != null) // REVISIT: localize reportGenericSchemaError("globally-declared element " + nameStr + " cannot have a ref attribute"); int nameIndex = fStringPool.addSymbol(nameStr); int eltKey = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, nameIndex,TOP_LEVEL_SCOPE); if (eltKey > -1 ) { return new QName(-1,nameIndex,nameIndex,fTargetNSURI); } } // parse out 'block', 'final', 'nillable', 'abstract' if (blockAtt == null) blockStr = null; int blockSet = parseBlockSet(blockStr); if( (blockStr != null) && !blockStr.equals("") && (!blockStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((blockSet & SchemaSymbols.RESTRICTION) == 0) && (((blockSet & SchemaSymbols.EXTENSION) == 0) && ((blockSet & SchemaSymbols.SUBSTITUTION) == 0))))) reportGenericSchemaError("The values of the 'block' attribute of an element must be either #all or a list of 'substitution', 'restriction' and 'extension'; " + blockStr + " was found"); if (finalAtt == null) finalStr = null; int finalSet = parseFinalSet(finalStr); if( (finalStr != null) && !finalStr.equals("") && (!finalStr.equals(SchemaSymbols.ATTVAL_POUNDALL) && (((finalSet & SchemaSymbols.RESTRICTION) == 0) && ((finalSet & SchemaSymbols.EXTENSION) == 0)))) reportGenericSchemaError("The values of the 'final' attribute of an element must be either #all or a list of 'restriction' and 'extension'; " + finalStr + " was found"); boolean isNillable = nillableStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; boolean isAbstract = abstractStr.equals(SchemaSymbols.ATTVAL_TRUE)? true:false; int elementMiscFlags = 0; if (isNillable) { elementMiscFlags += SchemaSymbols.NILLABLE; } if (isAbstract) { elementMiscFlags += SchemaSymbols.ABSTRACT; } // make the property of the element's value being fixed also appear in elementMiscFlags if(fixedAtt != null) elementMiscFlags += SchemaSymbols.FIXED; //if this is a reference to a global element if (refAtt != null) { //REVISIT top level check for ref if (abstractAtt != null || blockAtt != null || defaultAtt != null || finalAtt != null || fixedAtt != null || formAtt != null || nillableAtt != null || substitutionGroupAtt != null || typeAtt != null) reportSchemaError(SchemaMessageProvider.BadAttWithRef, null); //src-element.2.2 if (nameAtt != null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: element " + nameStr + " cannot also have a ref attribute"); Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { if (XUtil.getNextSiblingElement(child) != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); else traverseAnnotationDecl(child); } else if (child != null) reportSchemaError(SchemaMessageProvider.NoContentForRef, null); String prefix = ""; String localpart = refStr; int colonptr = refStr.indexOf(":"); if ( colonptr > 0) { prefix = refStr.substring(0,colonptr); localpart = refStr.substring(colonptr+1); } int localpartIndex = fStringPool.addSymbol(localpart); String uriString = resolvePrefixToURI(prefix); QName eltName = new QName(prefix != null ? fStringPool.addSymbol(prefix) : -1, localpartIndex, fStringPool.addSymbol(refStr), uriString != null ? fStringPool.addSymbol(uriString) : StringPool.EMPTY_STRING); //if from another schema, just return the element QName if (! uriString.equals(fTargetNSURIString) ) { return eltName; } int elementIndex = fSchemaGrammar.getElementDeclIndex(eltName, TOP_LEVEL_SCOPE); //if not found, traverse the top level element that if referenced if (elementIndex == -1 ) { Element targetElement = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT,localpart); if (targetElement == null ) { // REVISIT: Localize reportGenericSchemaError("Element " + localpart + " not found in the Schema"); //REVISIT, for now, the QName anyway return eltName; //return new QName(-1,fStringPool.addSymbol(localpart), -1, fStringPool.addSymbol(uriString)); } else { // do nothing here, other wise would cause infinite loop for // <element name="recur"><complexType><element ref="recur"> ... //eltName= traverseElementDecl(targetElement); } } return eltName; } else if (nameAtt == null) // REVISIT: Localize reportGenericSchemaError("src-element.2.1: a local element must have a name or a ref attribute present"); // Handle the substitutionGroup Element substitutionGroupElementDecl = null; int substitutionGroupElementDeclIndex = -1; boolean noErrorSoFar = true; // // resolving the type for this element right here // ComplexTypeInfo typeInfo = null; // element has a single child element, either a datatype or a type, null if primitive Element child = XUtil.getFirstChildElement(elementDecl); if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child); child = XUtil.getNextSiblingElement(child); } if(child != null && child.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) // REVISIT: Localize reportGenericSchemaError("element declarations can contain at most one annotation Element Information Item"); boolean haveAnonType = false; // Handle Anonymous type if there is one if (child != null) { String childName = child.getLocalName(); if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous complexType in element '" + nameStr +"' has a name attribute"); } else { // Determine what the type name will be String anonTypeName = genAnonTypeName(child); if (fCurrentTypeNameStack.search((Object)anonTypeName) > - 1) { // A recursing element using an anonymous type int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,anonTypeName)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl(child); if (typeNameIndex != -1 ) { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse complexType error in element '" + nameStr +"'"); } } } haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { if (child.getAttribute(SchemaSymbols.ATT_NAME).length() > 0) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("anonymous simpleType in element '" + nameStr +"' has a name attribute"); } else typeNameIndex = traverseSimpleTypeDecl(child); if (typeNameIndex != -1) { dv = fDatatypeRegistry.getDatatypeValidator(fStringPool.toString(typeNameIndex)); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("traverse simpleType error in element '" + nameStr +"'"); } contentSpecType = XMLElementDecl.TYPE_SIMPLE; haveAnonType = true; child = XUtil.getNextSiblingElement(child); } else if (typeAtt == null) { // "ur-typed" leaf contentSpecType = XMLElementDecl.TYPE_ANY; //REVISIT: is this right? //contentSpecType = fStringPool.addSymbol("UR_TYPE"); // set occurrence count contentSpecNodeIndex = -1; } // see if there's something here; it had better be key, keyref or unique. if (child != null) childName = child.getLocalName(); while ((child != null) && ((childName.equals(SchemaSymbols.ELT_KEY)) || (childName.equals(SchemaSymbols.ELT_KEYREF)) || (childName.equals(SchemaSymbols.ELT_UNIQUE)))) { child = XUtil.getNextSiblingElement(child); if (child != null) { childName = child.getLocalName(); } } if (child != null) { // REVISIT: Localize noErrorSoFar = false; reportGenericSchemaError("src-element.0: the content of an element information item must match (annotation?, (simpleType | complexType)?, (unique | key | keyref)*)"); } } // handle type="" here if (haveAnonType && (typeAtt != null)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError( "src-element.3: Element '"+ nameStr + "' have both a type attribute and a annoymous type child" ); } // type specified as an attribute and no child is type decl. else if (typeAtt != null) { String prefix = ""; String localpart = typeStr; int colonptr = typeStr.indexOf(":"); if ( colonptr > 0) { prefix = typeStr.substring(0,colonptr); localpart = typeStr.substring(colonptr+1); } String typeURI = resolvePrefixToURI(prefix); // check if the type is from the same Schema if ( !typeURI.equals(fTargetNSURIString) && !typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && typeURI.length() != 0) { // REVISIT, only needed because of resolvePrifixToURI. fromAnotherSchema = typeURI; typeInfo = getTypeInfoFromNS(typeURI, localpart); if (typeInfo == null) { dv = getTypeValidatorFromNS(typeURI, localpart); if (dv == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type " +localpart + " in schema " + typeURI); } } } else { typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(typeURI+","+localpart); if (typeInfo == null) { dv = getDatatypeValidator(typeURI, localpart); if (dv == null ) if (typeURI.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) && !fTargetNSURIString.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA)) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } else { Element topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_COMPLEXTYPE,localpart); if (topleveltype != null) { if (fCurrentTypeNameStack.search((Object)localpart) > - 1) { //then we found a recursive element using complexType. // REVISIT: this will be broken when recursing happens between 2 schemas int uriInd = StringPool.EMPTY_STRING; if ( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified) { uriInd = fTargetNSURI; } int nameIndex = fStringPool.addSymbol(nameStr); QName tempQName = new QName(-1, nameIndex, nameIndex, uriInd); int eltIndex = fSchemaGrammar.addElementDecl(tempQName, fCurrentScope, fCurrentScope, -1, -1, -1, null); fElementRecurseComplex.addElement(new ElementInfo(eltIndex,localpart)); return tempQName; } else { typeNameIndex = traverseComplexTypeDecl( topleveltype, true ); typeInfo = (ComplexTypeInfo) fComplexTypeRegistry.get(fStringPool.toString(typeNameIndex)); } } else { topleveltype = getTopLevelComponentByName(SchemaSymbols.ELT_SIMPLETYPE, localpart); if (topleveltype != null) { typeNameIndex = traverseSimpleTypeDecl( topleveltype ); dv = getDatatypeValidator(typeURI, localpart); } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("type not found : " + typeURI+":"+localpart); } } } } } } // now we need to make sure that our substitution (if any) // is valid, now that we have all the requisite type-related info. String substitutionGroupUri = null; String substitutionGroupLocalpart = null; String substitutionGroupFullName = null; ComplexTypeInfo substitutionGroupEltTypeInfo = null; DatatypeValidator substitutionGroupEltDV = null; SchemaGrammar subGrammar = fSchemaGrammar; boolean ignoreSub = false; if ( substitutionGroupStr.length() > 0 ) { if(refAtt != null) // REVISIT: Localize reportGenericSchemaError("a local element cannot have a substitutionGroup"); substitutionGroupUri = resolvePrefixToURI(getPrefix(substitutionGroupStr)); substitutionGroupLocalpart = getLocalPart(substitutionGroupStr); substitutionGroupFullName = substitutionGroupUri+","+substitutionGroupLocalpart; if ( !substitutionGroupUri.equals(fTargetNSURIString) ) { Grammar grammar = fGrammarResolver.getGrammar(substitutionGroupUri); if (grammar != null && grammar instanceof SchemaGrammar) { subGrammar = (SchemaGrammar) grammar; substitutionGroupElementDeclIndex = subGrammar.getElementDeclIndex(fStringPool.addSymbol(substitutionGroupUri), fStringPool.addSymbol(substitutionGroupLocalpart), TOP_LEVEL_SCOPE); if (substitutionGroupElementDeclIndex<=-1) { // REVISIT: localize noErrorSoFar = false; reportGenericSchemaError("couldn't find substitutionGroup " + substitutionGroupLocalpart + " referenced by element " + nameStr + " in the SchemaGrammar "+substitutionGroupUri); } else { substitutionGroupEltTypeInfo = getElementDeclTypeInfoFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltTypeInfo == null) { substitutionGroupEltDV = getElementDeclTypeValidatorFromNS(substitutionGroupUri, substitutionGroupLocalpart); if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } else { // REVISIT: locallize noErrorSoFar = false; reportGenericSchemaError("couldn't find a schema grammar with target namespace " + substitutionGroupUri); } } else { substitutionGroupElementDecl = getTopLevelComponentByName(SchemaSymbols.ELT_ELEMENT, substitutionGroupLocalpart); if (substitutionGroupElementDecl == null) { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("unable to locate substitutionGroup affiliation element " +substitutionGroupStr +" in element declaration " +nameStr); } } else { substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); if ( substitutionGroupElementDeclIndex == -1) { // check for mutual recursion! if(fSubstitutionGroupRecursionRegistry.contains(substitutionGroupElementDecl.getAttribute("name"))) { ignoreSub = true; } else { fSubstitutionGroupRecursionRegistry.addElement(substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); traverseElementDecl(substitutionGroupElementDecl); substitutionGroupElementDeclIndex = fSchemaGrammar.getElementDeclIndex(fTargetNSURI, getLocalPartIndex(substitutionGroupStr),TOP_LEVEL_SCOPE); fSubstitutionGroupRecursionRegistry.removeElement((Object)substitutionGroupElementDecl.getAttribute(SchemaSymbols.ATT_NAME)); } } } if (!ignoreSub && substitutionGroupElementDeclIndex != -1) { substitutionGroupEltTypeInfo = fSchemaGrammar.getElementComplexTypeInfo( substitutionGroupElementDeclIndex ); if (substitutionGroupEltTypeInfo == null) { fSchemaGrammar.getElementDecl(substitutionGroupElementDeclIndex, fTempElementDecl); substitutionGroupEltDV = fTempElementDecl.datatypeValidator; if (substitutionGroupEltDV == null) { //TO DO: report error here; noErrorSoFar = false; reportGenericSchemaError("Could not find type for element '" +substitutionGroupLocalpart + "' in schema '" + substitutionGroupUri+"'"); } } } } if(!ignoreSub) checkSubstitutionGroupOK(elementDecl, substitutionGroupElementDecl, noErrorSoFar, substitutionGroupElementDeclIndex, subGrammar, typeInfo, substitutionGroupEltTypeInfo, dv, substitutionGroupEltDV); } // this element is ur-type, check its substitutionGroup affiliation. // if there is substitutionGroup affiliation and not type definition found for this element, // then grab substitutionGroup affiliation's type and give it to this element if ( noErrorSoFar && typeInfo == null && dv == null ) { typeInfo = substitutionGroupEltTypeInfo; dv = substitutionGroupEltDV; } if (typeInfo == null && dv==null) { if (noErrorSoFar) { // Actually this Element's type definition is ur-type; contentSpecType = XMLElementDecl.TYPE_ANY; // REVISIT, need to wait till we have wildcards implementation. // ADD attribute wildcards here } else { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError ("untyped element : " + nameStr ); } } // if element belongs to a compelx type if (typeInfo!=null) { contentSpecNodeIndex = typeInfo.contentSpecHandle; contentSpecType = typeInfo.contentType; scopeDefined = typeInfo.scopeDefined; dv = typeInfo.datatypeValidator; } // if element belongs to a simple type if (dv!=null) { contentSpecType = XMLElementDecl.TYPE_SIMPLE; if (typeInfo == null) { fromAnotherSchema = null; // not to switch schema in this case } } // Now we can handle validation etc. of default and fixed attributes, // since we finally have all the type information. if(fixedAtt != null) defaultStr = fixedStr; if(!defaultStr.equals("")) { if(typeInfo != null && (typeInfo.contentType != XMLElementDecl.TYPE_MIXED_SIMPLE && typeInfo.contentType != XMLElementDecl.TYPE_MIXED_COMPLEX && typeInfo.contentType != XMLElementDecl.TYPE_SIMPLE)) { // REVISIT: Localize reportGenericSchemaError ("e-props-correct.2.1: element " + nameStr + " has a fixed or default value and must have a mixed or simple content model"); } if(typeInfo != null && (typeInfo.contentType == XMLElementDecl.TYPE_MIXED_SIMPLE || typeInfo.contentType == XMLElementDecl.TYPE_MIXED_COMPLEX)) { if (!particleEmptiable(typeInfo.contentSpecHandle)) reportGenericSchemaError ("e-props-correct.2.2.2: for element " + nameStr + ", the {content type} is mixed, then the {content type}'s particle must be emptiable"); } try { if(dv != null) { dv.validate(defaultStr, null); } } catch (InvalidDatatypeValueException ide) { reportGenericSchemaError ("e-props-correct.2: invalid fixed or default value '" + defaultStr + "' in element " + nameStr); } } if (!defaultStr.equals("") && dv != null && dv instanceof IDDatatypeValidator) { reportGenericSchemaError ("e-props-correct.4: If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint} -- element " + nameStr); } // // Create element decl // int elementNameIndex = fStringPool.addSymbol(nameStr); int localpartIndex = elementNameIndex; int uriIndex = StringPool.EMPTY_STRING; int enclosingScope = fCurrentScope; //refer to 4.3.2 in "XML Schema Part 1: Structures" if ( isTopLevel(elementDecl)) { uriIndex = fTargetNSURI; enclosingScope = TOP_LEVEL_SCOPE; } else if ( !formStr.equals(SchemaSymbols.ATTVAL_UNQUALIFIED) && (( formStr.equals(SchemaSymbols.ATTVAL_QUALIFIED)|| fElementDefaultQualified ))) { uriIndex = fTargetNSURI; } //There can never be two elements with the same name and different type in the same scope. int existSuchElementIndex = fSchemaGrammar.getElementDeclIndex(uriIndex, localpartIndex, enclosingScope); if ( existSuchElementIndex > -1) { fSchemaGrammar.getElementDecl(existSuchElementIndex, fTempElementDecl); DatatypeValidator edv = fTempElementDecl.datatypeValidator; ComplexTypeInfo eTypeInfo = fSchemaGrammar.getElementComplexTypeInfo(existSuchElementIndex); if ( ((eTypeInfo != null)&&(eTypeInfo!=typeInfo)) || ((edv != null)&&(edv != dv)) ) { noErrorSoFar = false; // REVISIT: Localize reportGenericSchemaError("duplicate element decl in the same scope : " + fStringPool.toString(localpartIndex)); } } QName eltQName = new QName(-1,localpartIndex,elementNameIndex,uriIndex); // add element decl to pool int attrListHead = -1 ; // copy up attribute decls from type object if (typeInfo != null) { attrListHead = typeInfo.attlistHead; } int elementIndex = fSchemaGrammar.addElementDecl(eltQName, enclosingScope, scopeDefined, contentSpecType, contentSpecNodeIndex, attrListHead, dv); if ( DEBUGGING ) { /***/ System.out.println("########elementIndex:"+elementIndex+" ("+fStringPool.toString(eltQName.uri)+"," + fStringPool.toString(eltQName.localpart) + ")"+ " eltType:"+typeStr+" contentSpecType:"+contentSpecType+ " SpecNodeIndex:"+ contentSpecNodeIndex +" enclosingScope: " +enclosingScope + " scopeDefined: " +scopeDefined+"\n"); /***/ } fSchemaGrammar.setElementComplexTypeInfo(elementIndex, typeInfo); // REVISIT: should we report error if typeInfo was null? // mark element if its type belongs to different Schema. fSchemaGrammar.setElementFromAnotherSchemaURI(elementIndex, fromAnotherSchema); // set BlockSet, FinalSet, Nillable and Abstract for this element decl fSchemaGrammar.setElementDeclBlockSet(elementIndex, blockSet); fSchemaGrammar.setElementDeclFinalSet(elementIndex, finalSet); fSchemaGrammar.setElementDeclMiscFlags(elementIndex, elementMiscFlags); fSchemaGrammar.setElementDefault(elementIndex, defaultStr); // setSubstitutionGroupElementFullName fSchemaGrammar.setElementDeclSubstitutionGroupElementFullName(elementIndex, substitutionGroupFullName); // // key/keyref/unique processing // Element ic = XUtil.getFirstChildElementNS(elementDecl, IDENTITY_CONSTRAINTS); if (ic != null) { Integer elementIndexObj = new Integer(elementIndex); Vector identityConstraints = (Vector)fIdentityConstraints.get(elementIndexObj); if (identityConstraints == null) { identityConstraints = new Vector(); fIdentityConstraints.put(elementIndexObj, identityConstraints); } while (ic != null) { if (DEBUG_IC_DATATYPES) { System.out.println("<ICD>: adding ic for later traversal: "+ic); } identityConstraints.addElement(ic); ic = XUtil.getNextSiblingElementNS(ic, IDENTITY_CONSTRAINTS); } } return eltQName; }// end of method traverseElementDecl(Element)
diff --git a/sslr-impl/src/main/java/com/sonar/sslr/impl/channel/RegexpChannel.java b/sslr-impl/src/main/java/com/sonar/sslr/impl/channel/RegexpChannel.java index 86da0244..18bf8745 100644 --- a/sslr-impl/src/main/java/com/sonar/sslr/impl/channel/RegexpChannel.java +++ b/sslr-impl/src/main/java/com/sonar/sslr/impl/channel/RegexpChannel.java @@ -1,52 +1,57 @@ /* * Copyright (C) 2010 SonarSource SA * All rights reserved * mailto:contact AT sonarsource DOT com */ package com.sonar.sslr.impl.channel; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sonar.channel.Channel; import org.sonar.channel.CodeReader; import com.sonar.sslr.api.GenericTokenType; import com.sonar.sslr.api.LexerOutput; import com.sonar.sslr.api.Token; import com.sonar.sslr.api.TokenType; import com.sonar.sslr.impl.LexerException; public class RegexpChannel extends Channel<LexerOutput> { private final StringBuilder tmpBuilder = new StringBuilder(); private final TokenType type; private final Matcher matcher; private final String regexp; public RegexpChannel(TokenType type, String regexp) { matcher = Pattern.compile(regexp).matcher(""); this.type = type; this.regexp = regexp; } @Override public boolean consume(CodeReader code, LexerOutput output) { try { if (code.popTo(matcher, tmpBuilder) > 0) { String value = tmpBuilder.toString(); if (type == GenericTokenType.COMMENT) { output.addCommentToken(new Token(GenericTokenType.COMMENT, value, code.getPreviousCursor().getLine(), code.getPreviousCursor() .getColumn())); } else { output.addTokenAndProcess(type, value, code.getPreviousCursor().getLine(), code.getPreviousCursor().getColumn()); } tmpBuilder.delete(0, tmpBuilder.length()); return true; } return false; } catch (StackOverflowError e) { - throw new LexerException("The regular expression " + regexp + " has led to a stack overflow error.", e); + throw new LexerException( + "The regular expression " + + regexp + + " has led to a stack overflow error. " + + "This error is certainly due to an inefficient use of alternations. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5050507", + e); } } }
true
true
public boolean consume(CodeReader code, LexerOutput output) { try { if (code.popTo(matcher, tmpBuilder) > 0) { String value = tmpBuilder.toString(); if (type == GenericTokenType.COMMENT) { output.addCommentToken(new Token(GenericTokenType.COMMENT, value, code.getPreviousCursor().getLine(), code.getPreviousCursor() .getColumn())); } else { output.addTokenAndProcess(type, value, code.getPreviousCursor().getLine(), code.getPreviousCursor().getColumn()); } tmpBuilder.delete(0, tmpBuilder.length()); return true; } return false; } catch (StackOverflowError e) { throw new LexerException("The regular expression " + regexp + " has led to a stack overflow error.", e); } }
public boolean consume(CodeReader code, LexerOutput output) { try { if (code.popTo(matcher, tmpBuilder) > 0) { String value = tmpBuilder.toString(); if (type == GenericTokenType.COMMENT) { output.addCommentToken(new Token(GenericTokenType.COMMENT, value, code.getPreviousCursor().getLine(), code.getPreviousCursor() .getColumn())); } else { output.addTokenAndProcess(type, value, code.getPreviousCursor().getLine(), code.getPreviousCursor().getColumn()); } tmpBuilder.delete(0, tmpBuilder.length()); return true; } return false; } catch (StackOverflowError e) { throw new LexerException( "The regular expression " + regexp + " has led to a stack overflow error. " + "This error is certainly due to an inefficient use of alternations. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5050507", e); } }
diff --git a/core/src/test/java/org/tautua/markdownpapers/MarkdownPapersTest.java b/core/src/test/java/org/tautua/markdownpapers/MarkdownPapersTest.java index 93ff71d..8aa398c 100644 --- a/core/src/test/java/org/tautua/markdownpapers/MarkdownPapersTest.java +++ b/core/src/test/java/org/tautua/markdownpapers/MarkdownPapersTest.java @@ -1,55 +1,56 @@ /* * Copyright 2011, TAUTUA * * 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.tautua.markdownpapers; import java.io.*; import java.util.Arrays; import java.util.List; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; @RunWith(LabelledParameterized.class) public class MarkdownPapersTest extends BaseTest { public MarkdownPapersTest(String fileName) { super(fileName, new File("target/test-classes/others"), new File("target/generated-test-sources/others")); } @Parameters public static List<Object[]> data() throws FileNotFoundException { return Arrays.asList(new Object[][]{ {"code"}, {"comments"}, + {"codespan"}, {"emphasis"}, {"headers"}, {"images"}, {"inline"}, {"linebreak"}, {"links"}, {"list"}, {"paragraphs"}, {"quoteAndList"}, {"quotes"}, {"rulers"}, {"snippets"}, {"tags"}, {"underscore"}, {"inlineUrls"} }); } }
true
true
public static List<Object[]> data() throws FileNotFoundException { return Arrays.asList(new Object[][]{ {"code"}, {"comments"}, {"emphasis"}, {"headers"}, {"images"}, {"inline"}, {"linebreak"}, {"links"}, {"list"}, {"paragraphs"}, {"quoteAndList"}, {"quotes"}, {"rulers"}, {"snippets"}, {"tags"}, {"underscore"}, {"inlineUrls"} }); }
public static List<Object[]> data() throws FileNotFoundException { return Arrays.asList(new Object[][]{ {"code"}, {"comments"}, {"codespan"}, {"emphasis"}, {"headers"}, {"images"}, {"inline"}, {"linebreak"}, {"links"}, {"list"}, {"paragraphs"}, {"quoteAndList"}, {"quotes"}, {"rulers"}, {"snippets"}, {"tags"}, {"underscore"}, {"inlineUrls"} }); }
diff --git a/src/org/jacorb/naming/NameServer.java b/src/org/jacorb/naming/NameServer.java index 25df66c9b..c5ac24980 100644 --- a/src/org/jacorb/naming/NameServer.java +++ b/src/org/jacorb/naming/NameServer.java @@ -1,356 +1,356 @@ package org.jacorb.naming; /* * JacORB - a free Java ORB * * Copyright (C) 1997-2002 Gerald Brose. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import java.net.*; import java.io.*; import org.omg.PortableServer.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.jacorb.orb.*; import org.jacorb.imr.util.ImRManager; import org.jacorb.util.*; /** * The name server application * * @author Gerald Brose, FU Berlin * @version $Id$ */ public class NameServer { private static org.omg.CORBA.ORB orb = null; public static String name_delimiter = "/"; private static String filePrefix = "_nsdb"; /** * The servant manager (servant activator) for the name server POA */ static class NameServantActivatorImpl extends _ServantActivatorLocalBase { private org.omg.CORBA.ORB orb = null; public NameServantActivatorImpl(org.omg.CORBA.ORB orb) { this.orb = orb; } /** * @returns - a servant initialized from a file */ public Servant incarnate( byte[] oid, POA adapter ) throws ForwardRequest { String oidStr = new String(oid); NamingContextImpl n = null; try { File f = new File( filePrefix + oidStr ); if( f.exists() ) { org.jacorb.util.Debug.output( 2,"Reading in context state from file"); FileInputStream f_in = new FileInputStream(f); if( f_in.available() > 0 ) { ObjectInputStream in = new ObjectInputStream(f_in); n = (NamingContextImpl)in.readObject(); in.close(); } f_in.close(); } else org.jacorb.util.Debug.output(2,"No naming context state, starting empty"); } catch( IOException io ) { org.jacorb.util.Debug.output(2,"File seems corrupt, starting empty"); } catch( java.lang.ClassNotFoundException c ) { System.err.println("Could not read object from file, class not found!"); System.exit(1); } if( n == null ) { n = new NamingContextImpl(); } n.init( orb, adapter); return n; } /** * Saves the servant's state in a file */ public void etherealize(byte[] oid, POA adapter, Servant servant, boolean cleanup_in_progress, boolean remaining_activations) { String oidStr = new String(oid); try { File f = new File(filePrefix + oidStr); FileOutputStream fout = new FileOutputStream(f); ObjectOutputStream out = new ObjectOutputStream(fout); /* save state */ out.writeObject((NamingContextImpl)servant); org.jacorb.util.Debug.output(2,"Saved state for servant " + oidStr); } catch( IOException io ) { io.printStackTrace(); System.err.println("Error opening output file " + filePrefix + oidStr ); // System.exit(1); } } } private static void usage() { System.err.println("Usage: java org.jacorb.naming.NameServer [<ior_filename>] [-p <ns_port>] [-t <time_out> [imr_register] ]"); System.exit(1); } /** Main */ public static void main( String args[] ) { String port = null; boolean imr_register = false; String fileName = null; try { /* get time out value if any */ int time_out = 0; if( args.length > 6 ) { usage(); } int idx = 0; if( args.length > 0 ) { if( !args[0].startsWith("-p")) { fileName = args[0]; idx++; } if( idx < args.length && args[idx].startsWith("-p")) { if( idx+1 < args.length ) { port = args[ idx+1 ]; idx++; } else usage(); } if( idx < args.length && args[ idx ].startsWith("-t")) { if( idx+1 < args.length ) { try { time_out = Integer.parseInt( args[ idx+1] ); idx++; } catch( NumberFormatException nf ) { } if( idx +1 < args.length && args[idx +1].equals("imr_register") ) imr_register = true; } else usage(); } } java.util.Properties props = new java.util.Properties(); props.put("jacorb.implname","StandardNS"); /* * by setting the following property, the ORB will * accept client requests targeted at the object with * key "NameService", so more readablee corbaloc URLs * can be used */ props.put("jacorb.orb.objectKeyMap.NameService", - "%01StandardNS/NameServer%2DPOA/_root"); + "StandardNS/NameServer-POA/_root"); /* * set a connection time out : after 30 secs. idle time, * the adapter will close connections */ props.put( "jacorb.connection.server_timeout", "10000" ); // If port not set on command line see if configured if (port == null) { port = Environment.getProperty ("jacorb.naming.port"); if (port != null) { try { Integer.parseInt (port); } catch (NumberFormatException ex) { port = null; } } } if (port != null) { props.put ("OAPort", port); } /* which directory to store/load in? */ String directory = org.jacorb.util.Environment.getProperty("jacorb.naming.db_dir"); if( directory != null ) filePrefix = directory + File.separatorChar + filePrefix; /* intialize the ORB and Root POA */ orb = org.omg.CORBA.ORB.init(args, props); if ( org.jacorb.util.Environment.useImR() && imr_register) { // don't supply "imr_register", so a ns started by an imr_ssd // won't try to register himself again. String command = Environment.getProperty("jacorb.java_exec") + " org.jacorb.naming.NameServer " + args[0] + " " + args[1]; ImRManager.autoRegisterServer(orb, "StandardNS", command, ImRManager.getLocalHostName(), true); //edit existing } org.omg.PortableServer.POA rootPOA = org.omg.PortableServer.POAHelper.narrow(orb.resolve_initial_references("RootPOA")); /* create a user defined poa for the naming contexts */ org.omg.CORBA.Policy [] policies = new org.omg.CORBA.Policy[3]; policies[0] = rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID); policies[1] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); policies[2] = rootPOA.create_request_processing_policy( RequestProcessingPolicyValue.USE_SERVANT_MANAGER); POA nsPOA = rootPOA.create_POA("NameServer-POA", rootPOA.the_POAManager(), policies); NameServer.NameServantActivatorImpl servantActivator = new NameServer.NameServantActivatorImpl( orb ); nsPOA.set_servant_manager( servantActivator ); nsPOA.the_POAManager().activate(); for (int i = 0; i < policies.length; i++) policies[i].destroy(); /* export the root context's reference to a file */ byte[] oid = ( new String("_root").getBytes() ); try { org.omg.CORBA.Object obj = nsPOA.create_reference_with_id( oid, "IDL:omg.org/CosNaming/NamingContextExt:1.0"); if( fileName != null ) { PrintWriter out = new PrintWriter( new FileOutputStream( fileName ), true ); out.println( orb.object_to_string(obj) ); out.close(); } } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } org.jacorb.util.Debug.output(2,"NS up"); /* either block indefinitely or time out */ if( time_out == 0 ) orb.run(); else Thread.sleep(time_out); /* shutdown. This will etherealize all servants, thus saving their state */ orb.shutdown( true ); // System.exit(0); } catch( Exception e ) { e.printStackTrace(); System.exit(1); } } }
true
true
public static void main( String args[] ) { String port = null; boolean imr_register = false; String fileName = null; try { /* get time out value if any */ int time_out = 0; if( args.length > 6 ) { usage(); } int idx = 0; if( args.length > 0 ) { if( !args[0].startsWith("-p")) { fileName = args[0]; idx++; } if( idx < args.length && args[idx].startsWith("-p")) { if( idx+1 < args.length ) { port = args[ idx+1 ]; idx++; } else usage(); } if( idx < args.length && args[ idx ].startsWith("-t")) { if( idx+1 < args.length ) { try { time_out = Integer.parseInt( args[ idx+1] ); idx++; } catch( NumberFormatException nf ) { } if( idx +1 < args.length && args[idx +1].equals("imr_register") ) imr_register = true; } else usage(); } } java.util.Properties props = new java.util.Properties(); props.put("jacorb.implname","StandardNS"); /* * by setting the following property, the ORB will * accept client requests targeted at the object with * key "NameService", so more readablee corbaloc URLs * can be used */ props.put("jacorb.orb.objectKeyMap.NameService", "%01StandardNS/NameServer%2DPOA/_root"); /* * set a connection time out : after 30 secs. idle time, * the adapter will close connections */ props.put( "jacorb.connection.server_timeout", "10000" ); // If port not set on command line see if configured if (port == null) { port = Environment.getProperty ("jacorb.naming.port"); if (port != null) { try { Integer.parseInt (port); } catch (NumberFormatException ex) { port = null; } } } if (port != null) { props.put ("OAPort", port); } /* which directory to store/load in? */ String directory = org.jacorb.util.Environment.getProperty("jacorb.naming.db_dir"); if( directory != null ) filePrefix = directory + File.separatorChar + filePrefix; /* intialize the ORB and Root POA */ orb = org.omg.CORBA.ORB.init(args, props); if ( org.jacorb.util.Environment.useImR() && imr_register) { // don't supply "imr_register", so a ns started by an imr_ssd // won't try to register himself again. String command = Environment.getProperty("jacorb.java_exec") + " org.jacorb.naming.NameServer " + args[0] + " " + args[1]; ImRManager.autoRegisterServer(orb, "StandardNS", command, ImRManager.getLocalHostName(), true); //edit existing } org.omg.PortableServer.POA rootPOA = org.omg.PortableServer.POAHelper.narrow(orb.resolve_initial_references("RootPOA")); /* create a user defined poa for the naming contexts */ org.omg.CORBA.Policy [] policies = new org.omg.CORBA.Policy[3]; policies[0] = rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID); policies[1] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); policies[2] = rootPOA.create_request_processing_policy( RequestProcessingPolicyValue.USE_SERVANT_MANAGER); POA nsPOA = rootPOA.create_POA("NameServer-POA", rootPOA.the_POAManager(), policies); NameServer.NameServantActivatorImpl servantActivator = new NameServer.NameServantActivatorImpl( orb ); nsPOA.set_servant_manager( servantActivator ); nsPOA.the_POAManager().activate(); for (int i = 0; i < policies.length; i++) policies[i].destroy(); /* export the root context's reference to a file */ byte[] oid = ( new String("_root").getBytes() ); try { org.omg.CORBA.Object obj = nsPOA.create_reference_with_id( oid, "IDL:omg.org/CosNaming/NamingContextExt:1.0"); if( fileName != null ) { PrintWriter out = new PrintWriter( new FileOutputStream( fileName ), true ); out.println( orb.object_to_string(obj) ); out.close(); } } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } org.jacorb.util.Debug.output(2,"NS up"); /* either block indefinitely or time out */ if( time_out == 0 ) orb.run(); else Thread.sleep(time_out); /* shutdown. This will etherealize all servants, thus saving their state */ orb.shutdown( true ); // System.exit(0); } catch( Exception e ) { e.printStackTrace(); System.exit(1); } }
public static void main( String args[] ) { String port = null; boolean imr_register = false; String fileName = null; try { /* get time out value if any */ int time_out = 0; if( args.length > 6 ) { usage(); } int idx = 0; if( args.length > 0 ) { if( !args[0].startsWith("-p")) { fileName = args[0]; idx++; } if( idx < args.length && args[idx].startsWith("-p")) { if( idx+1 < args.length ) { port = args[ idx+1 ]; idx++; } else usage(); } if( idx < args.length && args[ idx ].startsWith("-t")) { if( idx+1 < args.length ) { try { time_out = Integer.parseInt( args[ idx+1] ); idx++; } catch( NumberFormatException nf ) { } if( idx +1 < args.length && args[idx +1].equals("imr_register") ) imr_register = true; } else usage(); } } java.util.Properties props = new java.util.Properties(); props.put("jacorb.implname","StandardNS"); /* * by setting the following property, the ORB will * accept client requests targeted at the object with * key "NameService", so more readablee corbaloc URLs * can be used */ props.put("jacorb.orb.objectKeyMap.NameService", "StandardNS/NameServer-POA/_root"); /* * set a connection time out : after 30 secs. idle time, * the adapter will close connections */ props.put( "jacorb.connection.server_timeout", "10000" ); // If port not set on command line see if configured if (port == null) { port = Environment.getProperty ("jacorb.naming.port"); if (port != null) { try { Integer.parseInt (port); } catch (NumberFormatException ex) { port = null; } } } if (port != null) { props.put ("OAPort", port); } /* which directory to store/load in? */ String directory = org.jacorb.util.Environment.getProperty("jacorb.naming.db_dir"); if( directory != null ) filePrefix = directory + File.separatorChar + filePrefix; /* intialize the ORB and Root POA */ orb = org.omg.CORBA.ORB.init(args, props); if ( org.jacorb.util.Environment.useImR() && imr_register) { // don't supply "imr_register", so a ns started by an imr_ssd // won't try to register himself again. String command = Environment.getProperty("jacorb.java_exec") + " org.jacorb.naming.NameServer " + args[0] + " " + args[1]; ImRManager.autoRegisterServer(orb, "StandardNS", command, ImRManager.getLocalHostName(), true); //edit existing } org.omg.PortableServer.POA rootPOA = org.omg.PortableServer.POAHelper.narrow(orb.resolve_initial_references("RootPOA")); /* create a user defined poa for the naming contexts */ org.omg.CORBA.Policy [] policies = new org.omg.CORBA.Policy[3]; policies[0] = rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.USER_ID); policies[1] = rootPOA.create_lifespan_policy(LifespanPolicyValue.PERSISTENT); policies[2] = rootPOA.create_request_processing_policy( RequestProcessingPolicyValue.USE_SERVANT_MANAGER); POA nsPOA = rootPOA.create_POA("NameServer-POA", rootPOA.the_POAManager(), policies); NameServer.NameServantActivatorImpl servantActivator = new NameServer.NameServantActivatorImpl( orb ); nsPOA.set_servant_manager( servantActivator ); nsPOA.the_POAManager().activate(); for (int i = 0; i < policies.length; i++) policies[i].destroy(); /* export the root context's reference to a file */ byte[] oid = ( new String("_root").getBytes() ); try { org.omg.CORBA.Object obj = nsPOA.create_reference_with_id( oid, "IDL:omg.org/CosNaming/NamingContextExt:1.0"); if( fileName != null ) { PrintWriter out = new PrintWriter( new FileOutputStream( fileName ), true ); out.println( orb.object_to_string(obj) ); out.close(); } } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } org.jacorb.util.Debug.output(2,"NS up"); /* either block indefinitely or time out */ if( time_out == 0 ) orb.run(); else Thread.sleep(time_out); /* shutdown. This will etherealize all servants, thus saving their state */ orb.shutdown( true ); // System.exit(0); } catch( Exception e ) { e.printStackTrace(); System.exit(1); } }
diff --git a/src/com/ds/avare/utils/BitmapHolder.java b/src/com/ds/avare/utils/BitmapHolder.java index 0d82a922..ce1ff39d 100644 --- a/src/com/ds/avare/utils/BitmapHolder.java +++ b/src/com/ds/avare/utils/BitmapHolder.java @@ -1,283 +1,284 @@ /* Copyright (c) 2012, Apps4Av Inc. (apps4av.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ds.avare.utils; import java.io.File; import com.ds.avare.storage.Preferences; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; /** * @author zkhan * This class hides all details of handling a bitmap */ public class BitmapHolder { /** * */ private Bitmap mBitmap = null; /** * */ private Canvas mCanvas; /** * */ private int mWidth = 0; /** * */ private int mHeight = 0; /** * */ private String mName = null; /** * Transform for scale/translate */ private Matrix mTransform = new Matrix(); /** * */ public static final int WIDTH = 512; /** * */ public static final int HEIGHT = 512; /** * @param name * Get bitmap from renderer */ public BitmapHolder() { Bitmap.Config conf = Bitmap.Config.RGB_565; try { mBitmap = Bitmap.createBitmap(WIDTH, HEIGHT, conf); mBitmap.setDensity(Bitmap.DENSITY_NONE); mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mCanvas = new Canvas(mBitmap); mName = null; } catch(OutOfMemoryError e){ } } /** * @param name * Get bitmap from renderer */ public BitmapHolder(int width, int height) { Bitmap.Config conf = Bitmap.Config.ARGB_8888; try { mBitmap = Bitmap.createBitmap(width, height, conf); mBitmap.setDensity(Bitmap.DENSITY_NONE); mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mCanvas = new Canvas(mBitmap); mName = null; } catch(OutOfMemoryError e){ } } /** * * @param b is bitmap to draw * @param name is the name to store */ public void drawInBitmap(BitmapHolder b, String name, int x, int y) { /* * This should mark bitmap dirty */ mName = name; if(null == name) { return; } if((null == b) || (null == mCanvas)) { return; } if(null == b.getBitmap()) { return; } mTransform.setTranslate(x, y); mCanvas.drawBitmap(b.getBitmap(), mTransform, null); } /** * * @param pref * @param name * @param opts */ public static void getTileOptions(String name, Preferences pref, int opts[]) { if(!(new File(pref.mapsFolder() + "/" + name)).exists()) { opts[0] = WIDTH; opts[1] = HEIGHT; return; } /* * Bitmap dims without decoding */ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pref.mapsFolder() + "/" + name, options); opts[0] = options.outWidth; opts[1] = options.outHeight; if(opts[0] == 0) { opts[0] = WIDTH; } if(opts[1] == 0) { opts[1] = HEIGHT; } } /** * @param name * Get bitmap from a file */ public BitmapHolder(Context context, Preferences pref, String name, int sampleSize) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inSampleSize = sampleSize; if(!(new File(pref.mapsFolder() + "/" + name)).exists()) { mName = null; return; } try { mBitmap = BitmapFactory.decodeFile(pref.mapsFolder() + "/" + name, opt); } catch(OutOfMemoryError e) { } if(null != mBitmap) { mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mName = name; } else { mName = null; } } /** * @param name * Get bitmap from a diagram / plate file */ public BitmapHolder(String name) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inSampleSize = 1; if(!(new File(name).exists())) { mWidth = 0; mHeight = 0; - mName = null; + mName = null; + return; } try { mBitmap = BitmapFactory.decodeFile(name, opt); } catch(OutOfMemoryError e){ } if(null != mBitmap) { mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mName = name; } else { mWidth = 0; mHeight = 0; mName = null; } } /** * @param context * @param id * Get bitmap from resources */ public BitmapHolder(Context context, int id) { try { mBitmap = BitmapFactory.decodeResource(context.getResources(), id); } catch(OutOfMemoryError e){ } if(null != mBitmap) { mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); } } /** * Android does not free memory for a bitmap. Have to call this explicitly * especially for large bitmaps */ public void recycle() { if(null != mBitmap) { mBitmap.recycle(); } mBitmap = null; mName = null; mWidth = 0; mHeight = 0; } /** * @return */ public int getWidth() { return mWidth; } /** * @return */ public int getHeight() { return mHeight; } /** * @return */ public String getName() { return mName; } /** * @return */ public Bitmap getBitmap() { return mBitmap; } /** * * @return */ public Matrix getTransform() { return mTransform; } }
true
true
public BitmapHolder(String name) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inSampleSize = 1; if(!(new File(name).exists())) { mWidth = 0; mHeight = 0; mName = null; } try { mBitmap = BitmapFactory.decodeFile(name, opt); } catch(OutOfMemoryError e){ } if(null != mBitmap) { mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mName = name; } else { mWidth = 0; mHeight = 0; mName = null; } }
public BitmapHolder(String name) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inSampleSize = 1; if(!(new File(name).exists())) { mWidth = 0; mHeight = 0; mName = null; return; } try { mBitmap = BitmapFactory.decodeFile(name, opt); } catch(OutOfMemoryError e){ } if(null != mBitmap) { mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mName = name; } else { mWidth = 0; mHeight = 0; mName = null; } }
diff --git a/src/be/ibridge/kettle/job/entry/trans/JobEntryTrans.java b/src/be/ibridge/kettle/job/entry/trans/JobEntryTrans.java index 992f881d..1d7fbb2b 100644 --- a/src/be/ibridge/kettle/job/entry/trans/JobEntryTrans.java +++ b/src/be/ibridge/kettle/job/entry/trans/JobEntryTrans.java @@ -1,570 +1,570 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.job.entry.trans; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LocalVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleJobException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.logging.Log4jFileAppender; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.JobEntryBase; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; /** * This is the job entry that defines a transformation to be run. * * @author Matt * @since 1-10-2003, rewritten on 18-06-2004 * */ public class JobEntryTrans extends JobEntryBase implements Cloneable, JobEntryInterface { private String transname; private String filename; private RepositoryDirectory directory; public String arguments[]; public boolean argFromPrevious; public boolean execPerRow; public boolean setLogfile; public String logfile, logext; public boolean addDate, addTime; public int loglevel; private String directoryPath; public JobEntryTrans(String name) { super(name, ""); setType(JobEntryInterface.TYPE_JOBENTRY_TRANSFORMATION); } public JobEntryTrans() { this(""); clear(); } public JobEntryTrans(JobEntryBase jeb) { super(jeb); } public void setFileName(String n) { filename=n; } public String getFileName() { return filename; } public void setTransname(String transname) { this.transname=transname; } public String getTransname() { return transname; } public RepositoryDirectory getDirectory() { return directory; } public void setDirectory(RepositoryDirectory directory) { this.directory = directory; } public String getLogFilename() { String retval=""; if (setLogfile) { retval+=logfile; Calendar cal = Calendar.getInstance(); if (addDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); retval+="_"+sdf.format(cal.getTime()); } if (addTime) { SimpleDateFormat sdf = new SimpleDateFormat("HHmmss"); retval+="_"+sdf.format(cal.getTime()); } if (logext!=null && logext.length()>0) { retval+="."+logext; } } return retval; } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(super.getXML()); retval.append(" "+XMLHandler.addTagValue("filename", filename)); retval.append(" "+XMLHandler.addTagValue("transname", transname)); if (directory!=null) { retval.append(" "+XMLHandler.addTagValue("directory", directory.getPath())); } else if (directoryPath!=null) { retval.append(" "+XMLHandler.addTagValue("directory", directoryPath)); // don't loose this info (backup/recovery) } retval.append(" "+XMLHandler.addTagValue("arg_from_previous", argFromPrevious)); retval.append(" "+XMLHandler.addTagValue("exec_per_row", execPerRow)); retval.append(" "+XMLHandler.addTagValue("set_logfile", setLogfile)); retval.append(" "+XMLHandler.addTagValue("logfile", logfile)); retval.append(" "+XMLHandler.addTagValue("logext", logext)); retval.append(" "+XMLHandler.addTagValue("add_date", addDate)); retval.append(" "+XMLHandler.addTagValue("add_time", addTime)); retval.append(" "+XMLHandler.addTagValue("loglevel", LogWriter.getLogLevelDesc(loglevel))); if (arguments!=null) for (int i=0;i<arguments.length;i++) { retval.append(" "+XMLHandler.addTagValue("argument"+i, arguments[i])); } return retval.toString(); } public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases); filename = XMLHandler.getTagValue(entrynode, "filename") ; transname = XMLHandler.getTagValue(entrynode, "transname") ; directoryPath = XMLHandler.getTagValue(entrynode, "directory"); if (rep!=null) // import from XML into a repository for example... (or copy/paste) { directory = rep.getDirectoryTree().findDirectory(directoryPath); } argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "arg_from_previous") ); execPerRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "exec_per_row") ); setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_logfile") ); addDate = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_date") ); addTime = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_time") ); logfile = XMLHandler.getTagValue(entrynode, "logfile"); logext = XMLHandler.getTagValue(entrynode, "logext"); loglevel = LogWriter.getLogLevel( XMLHandler.getTagValue(entrynode, "loglevel")); // How many arguments? int argnr = 0; while ( XMLHandler.getTagValue(entrynode, "argument"+argnr)!=null) argnr++; arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) arguments[a]=XMLHandler.getTagValue(entrynode, "argument"+a); } catch(KettleException e) { throw new KettleXMLException("Unable to load transformation job entry from XML node", e); } } // Load the jobentry from repository public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException { try { super.loadRep(rep, id_jobentry, databases); transname = rep.getJobEntryAttributeString(id_jobentry, "name"); String dirPath = rep.getJobEntryAttributeString(id_jobentry, "dir_path"); directory = rep.getDirectoryTree().findDirectory(dirPath); filename = rep.getJobEntryAttributeString(id_jobentry, "filename"); argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous"); execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row"); setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile"); addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date"); addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time"); logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile"); logext = rep.getJobEntryAttributeString(id_jobentry, "logext"); loglevel = LogWriter.getLogLevel( rep.getJobEntryAttributeString(id_jobentry, "loglevel") ); // How many arguments? int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument"); arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) { arguments[a]= rep.getJobEntryAttributeString(id_jobentry, a, "argument"); } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type transMeta from the repository for id_jobentry="+id_jobentry, dbe); } } // Save the attributes of this job entry // public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); long id_transformation = rep.getTransformationID(transname, directory.getID()); rep.saveJobEntryAttribute(id_job, getID(), "id_transformation", id_transformation); rep.saveJobEntryAttribute(id_job, getID(), "name", getTransname()); rep.saveJobEntryAttribute(id_job, getID(), "dir_path", getDirectory()!=null?getDirectory().getPath():""); rep.saveJobEntryAttribute(id_job, getID(), "file_name", filename); rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious); rep.saveJobEntryAttribute(id_job, getID(), "exec_per_row", execPerRow); rep.saveJobEntryAttribute(id_job, getID(), "set_logfile", setLogfile); rep.saveJobEntryAttribute(id_job, getID(), "add_date", addDate); rep.saveJobEntryAttribute(id_job, getID(), "add_time", addTime); rep.saveJobEntryAttribute(id_job, getID(), "logfile", logfile); rep.saveJobEntryAttribute(id_job, getID(), "logext", logext); rep.saveJobEntryAttribute(id_job, getID(), "loglevel", LogWriter.getLogLevelDesc(loglevel)); // save the arguments... if (arguments!=null) { for (int i=0;i<arguments.length;i++) { rep.saveJobEntryAttribute(id_job, getID(), i, "argument", arguments[i]); } } } catch(KettleDatabaseException dbe) { throw new KettleException("unable to save job entry of type transMeta to the repository for id_job="+id_job, dbe); } } public void clear() { super.clear(); transname=null; filename=null; directory = new RepositoryDirectory(); arguments=null; argFromPrevious=false; execPerRow=false; addDate=false; addTime=false; logfile=null; logext=null; setLogfile=false; } /** * Execute this job entry and return the result. * In this case it means, just set the result boolean in the Result class. * @param prev_result The result of the previous execution * @return The Result of the execution. */ public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException { LogWriter log = LogWriter.getInstance(); result.setEntryNr( nr ); LogWriter logwriter = log; Log4jFileAppender appender = null; int backupLogLevel = log.getLogLevel(); if (setLogfile) { try { appender = LogWriter.createFileAppender(getLogFilename(), true); } catch(KettleException e) { log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); result.setResult(false); return result; } log.addAppender(appender); log.setLogLevel(loglevel); } // Open the transformation... // Default directory for now... log.logBasic(toString(), "Opening transformation: ["+getTransname()+"] in directory ["+directory.getPath()+"]"); int iteration = 0; String args[] = arguments; Row resultRow = null; boolean first = true; List rows = result.getRows(); while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) ) { first=false; if (rows!=null && execPerRow) { resultRow = (Row) rows.get(iteration); } else { resultRow = null; } try { log.logDetailed(toString(), "Starting transformation...(file="+getFileName()+", name="+getName()+"), repinfo="+getDescription()); TransMeta transMeta = getTransMeta(rep); if (parentJob.getJobMeta().isBatchIdPassed()) { transMeta.setJobBatchId(parentJob.getJobMeta().getBatchId()); } // Create the transformation from meta-data Trans trans = new Trans(logwriter, transMeta); // Set the result rows for the next one... trans.getTransMeta().setSourceRows(result.getRows()); // Set the result rows for the next one... trans.getTransMeta().setPreviousResult((Result)result.clone()); // set the parent job on the transformation, variables are taken from here... trans.setParentJob(parentJob); // Pass along the kettle variables... LocalVariables localVariables = LocalVariables.getInstance(); localVariables.createKettleVariables(Thread.currentThread(), parentJob, false); if (execPerRow) // Execute for each input row { if (argFromPrevious) // Copy the input row to the (command line) arguments { args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).getString(); } } } else { // Just pass a single row ArrayList newList = new ArrayList(); newList.add(resultRow); trans.setSourceRows(newList); } } else { if (argFromPrevious) { // Only put the first Row on the arguments args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).toString(); } } } else { // Keep it as it was... trans.setSourceRows(result.getRows()); } } // Execute! if (!trans.execute(args)) { log.logError(toString(), "Unable to prepare for execution of the transformation"); result.setNrErrors(1); } else { - while (!trans.isFinished() && !parentJob.isStopped()) + while (!trans.isFinished() && !parentJob.isStopped() && trans.getErrors() == 0) { try { Thread.sleep(100);} catch(InterruptedException e) { } } - if (parentJob.isStopped()) + if (parentJob.isStopped() || trans.getErrors() != 0) { trans.stopAll(); trans.waitUntilFinished(); trans.endProcessing("stop"); result.setNrErrors(1); } else { trans.endProcessing("end"); } Result newResult = trans.getResult(); result.clear(); result.add(newResult); // Set the result rows too... result.setRows(newResult.getRows()); if (setLogfile) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, new File(getLogFilename()), parentJob.getName(), toString()); result.getResultFiles().add(resultFile); } } } catch(KettleException e) { log.logError(toString(), "Unable to open transformation: "+e.getMessage()); result.setNrErrors(1); } iteration++; } if (setLogfile) { if (appender!=null) { log.removeAppender(appender); appender.close(); } log.setLogLevel(backupLogLevel); } if (result.getNrErrors()==0) { result.setResult( true ); } else { result.setResult( false ); } return result; } private TransMeta getTransMeta(Repository rep) throws KettleException { TransMeta transMeta = null; if (getTransname() != null && getTransname().length() > 0 && // Load from the repository getDirectory() != null) { transMeta = new TransMeta(rep, getTransname(), getDirectory()); } else if (getFileName() != null && getFileName().length() > 0) // Load from an XML file { transMeta = new TransMeta(getFileName()); } else { throw new KettleJobException("The transformation to execute is not specified!"); } // Set the arguments... transMeta.setArguments(arguments); return transMeta; } public boolean evaluates() { return true; } public boolean isUnconditional() { return true; } public ArrayList getSQLStatements(Repository repository) throws KettleException { TransMeta transMeta = getTransMeta(repository); return transMeta.getSQLStatements(); } /** * @return Returns the directoryPath. */ public String getDirectoryPath() { return directoryPath; } /** * @param directoryPath The directoryPath to set. */ public void setDirectoryPath(String directoryPath) { this.directoryPath = directoryPath; } public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) { return new JobEntryTransDialog(shell,this,rep); } }
false
true
public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException { LogWriter log = LogWriter.getInstance(); result.setEntryNr( nr ); LogWriter logwriter = log; Log4jFileAppender appender = null; int backupLogLevel = log.getLogLevel(); if (setLogfile) { try { appender = LogWriter.createFileAppender(getLogFilename(), true); } catch(KettleException e) { log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); result.setResult(false); return result; } log.addAppender(appender); log.setLogLevel(loglevel); } // Open the transformation... // Default directory for now... log.logBasic(toString(), "Opening transformation: ["+getTransname()+"] in directory ["+directory.getPath()+"]"); int iteration = 0; String args[] = arguments; Row resultRow = null; boolean first = true; List rows = result.getRows(); while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) ) { first=false; if (rows!=null && execPerRow) { resultRow = (Row) rows.get(iteration); } else { resultRow = null; } try { log.logDetailed(toString(), "Starting transformation...(file="+getFileName()+", name="+getName()+"), repinfo="+getDescription()); TransMeta transMeta = getTransMeta(rep); if (parentJob.getJobMeta().isBatchIdPassed()) { transMeta.setJobBatchId(parentJob.getJobMeta().getBatchId()); } // Create the transformation from meta-data Trans trans = new Trans(logwriter, transMeta); // Set the result rows for the next one... trans.getTransMeta().setSourceRows(result.getRows()); // Set the result rows for the next one... trans.getTransMeta().setPreviousResult((Result)result.clone()); // set the parent job on the transformation, variables are taken from here... trans.setParentJob(parentJob); // Pass along the kettle variables... LocalVariables localVariables = LocalVariables.getInstance(); localVariables.createKettleVariables(Thread.currentThread(), parentJob, false); if (execPerRow) // Execute for each input row { if (argFromPrevious) // Copy the input row to the (command line) arguments { args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).getString(); } } } else { // Just pass a single row ArrayList newList = new ArrayList(); newList.add(resultRow); trans.setSourceRows(newList); } } else { if (argFromPrevious) { // Only put the first Row on the arguments args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).toString(); } } } else { // Keep it as it was... trans.setSourceRows(result.getRows()); } } // Execute! if (!trans.execute(args)) { log.logError(toString(), "Unable to prepare for execution of the transformation"); result.setNrErrors(1); } else { while (!trans.isFinished() && !parentJob.isStopped()) { try { Thread.sleep(100);} catch(InterruptedException e) { } } if (parentJob.isStopped()) { trans.stopAll(); trans.waitUntilFinished(); trans.endProcessing("stop"); result.setNrErrors(1); } else { trans.endProcessing("end"); } Result newResult = trans.getResult(); result.clear(); result.add(newResult); // Set the result rows too... result.setRows(newResult.getRows()); if (setLogfile) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, new File(getLogFilename()), parentJob.getName(), toString()); result.getResultFiles().add(resultFile); } } } catch(KettleException e) { log.logError(toString(), "Unable to open transformation: "+e.getMessage()); result.setNrErrors(1); } iteration++; } if (setLogfile) { if (appender!=null) { log.removeAppender(appender); appender.close(); } log.setLogLevel(backupLogLevel); } if (result.getNrErrors()==0) { result.setResult( true ); } else { result.setResult( false ); } return result; }
public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException { LogWriter log = LogWriter.getInstance(); result.setEntryNr( nr ); LogWriter logwriter = log; Log4jFileAppender appender = null; int backupLogLevel = log.getLogLevel(); if (setLogfile) { try { appender = LogWriter.createFileAppender(getLogFilename(), true); } catch(KettleException e) { log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); result.setResult(false); return result; } log.addAppender(appender); log.setLogLevel(loglevel); } // Open the transformation... // Default directory for now... log.logBasic(toString(), "Opening transformation: ["+getTransname()+"] in directory ["+directory.getPath()+"]"); int iteration = 0; String args[] = arguments; Row resultRow = null; boolean first = true; List rows = result.getRows(); while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) ) { first=false; if (rows!=null && execPerRow) { resultRow = (Row) rows.get(iteration); } else { resultRow = null; } try { log.logDetailed(toString(), "Starting transformation...(file="+getFileName()+", name="+getName()+"), repinfo="+getDescription()); TransMeta transMeta = getTransMeta(rep); if (parentJob.getJobMeta().isBatchIdPassed()) { transMeta.setJobBatchId(parentJob.getJobMeta().getBatchId()); } // Create the transformation from meta-data Trans trans = new Trans(logwriter, transMeta); // Set the result rows for the next one... trans.getTransMeta().setSourceRows(result.getRows()); // Set the result rows for the next one... trans.getTransMeta().setPreviousResult((Result)result.clone()); // set the parent job on the transformation, variables are taken from here... trans.setParentJob(parentJob); // Pass along the kettle variables... LocalVariables localVariables = LocalVariables.getInstance(); localVariables.createKettleVariables(Thread.currentThread(), parentJob, false); if (execPerRow) // Execute for each input row { if (argFromPrevious) // Copy the input row to the (command line) arguments { args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).getString(); } } } else { // Just pass a single row ArrayList newList = new ArrayList(); newList.add(resultRow); trans.setSourceRows(newList); } } else { if (argFromPrevious) { // Only put the first Row on the arguments args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).toString(); } } } else { // Keep it as it was... trans.setSourceRows(result.getRows()); } } // Execute! if (!trans.execute(args)) { log.logError(toString(), "Unable to prepare for execution of the transformation"); result.setNrErrors(1); } else { while (!trans.isFinished() && !parentJob.isStopped() && trans.getErrors() == 0) { try { Thread.sleep(100);} catch(InterruptedException e) { } } if (parentJob.isStopped() || trans.getErrors() != 0) { trans.stopAll(); trans.waitUntilFinished(); trans.endProcessing("stop"); result.setNrErrors(1); } else { trans.endProcessing("end"); } Result newResult = trans.getResult(); result.clear(); result.add(newResult); // Set the result rows too... result.setRows(newResult.getRows()); if (setLogfile) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, new File(getLogFilename()), parentJob.getName(), toString()); result.getResultFiles().add(resultFile); } } } catch(KettleException e) { log.logError(toString(), "Unable to open transformation: "+e.getMessage()); result.setNrErrors(1); } iteration++; } if (setLogfile) { if (appender!=null) { log.removeAppender(appender); appender.close(); } log.setLogLevel(backupLogLevel); } if (result.getNrErrors()==0) { result.setResult( true ); } else { result.setResult( false ); } return result; }
diff --git a/src/org/geometerplus/android/fbreader/error/BookReadingErrorActivity.java b/src/org/geometerplus/android/fbreader/error/BookReadingErrorActivity.java index d741453f..2e4ccee0 100644 --- a/src/org/geometerplus/android/fbreader/error/BookReadingErrorActivity.java +++ b/src/org/geometerplus/android/fbreader/error/BookReadingErrorActivity.java @@ -1,72 +1,72 @@ /* * Copyright (C) 2007-2012 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.android.fbreader.error; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.geometerplus.zlibrary.core.resources.ZLResource; import org.geometerplus.zlibrary.ui.android.R; import org.geometerplus.zlibrary.ui.android.error.ErrorKeys; import org.geometerplus.zlibrary.ui.android.error.ErrorUtil; public class BookReadingErrorActivity extends Activity implements ErrorKeys { @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.error_book_reading); final ZLResource resource = ZLResource.resource("error").getResource("bookReading"); setTitle(resource.getResource("title").getValue()); final TextView textView = (TextView)findViewById(R.id.error_book_reading_text); textView.setText(getIntent().getStringExtra(MESSAGE)); final View buttonView = findViewById(R.id.error_book_reading_buttons); final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button"); final Button okButton = (Button)buttonView.findViewById(R.id.ok_button); okButton.setText(buttonResource.getResource("sendReport").getValue()); okButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { final Intent sendIntent = new Intent(Intent.ACTION_SEND); - sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); + sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, getIntent().getStringExtra(STACKTRACE)); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + new ErrorUtil(BookReadingErrorActivity.this).getVersionName() + " book reading issue report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } }); final Button cancelButton = (Button)buttonView.findViewById(R.id.cancel_button); cancelButton.setText(buttonResource.getResource("cancel").getValue()); cancelButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); } }
true
true
protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.error_book_reading); final ZLResource resource = ZLResource.resource("error").getResource("bookReading"); setTitle(resource.getResource("title").getValue()); final TextView textView = (TextView)findViewById(R.id.error_book_reading_text); textView.setText(getIntent().getStringExtra(MESSAGE)); final View buttonView = findViewById(R.id.error_book_reading_buttons); final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button"); final Button okButton = (Button)buttonView.findViewById(R.id.ok_button); okButton.setText(buttonResource.getResource("sendReport").getValue()); okButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { final Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, getIntent().getStringExtra(STACKTRACE)); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + new ErrorUtil(BookReadingErrorActivity.this).getVersionName() + " book reading issue report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } }); final Button cancelButton = (Button)buttonView.findViewById(R.id.cancel_button); cancelButton.setText(buttonResource.getResource("cancel").getValue()); cancelButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); }
protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.error_book_reading); final ZLResource resource = ZLResource.resource("error").getResource("bookReading"); setTitle(resource.getResource("title").getValue()); final TextView textView = (TextView)findViewById(R.id.error_book_reading_text); textView.setText(getIntent().getStringExtra(MESSAGE)); final View buttonView = findViewById(R.id.error_book_reading_buttons); final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button"); final Button okButton = (Button)buttonView.findViewById(R.id.ok_button); okButton.setText(buttonResource.getResource("sendReport").getValue()); okButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { final Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); sendIntent.putExtra(Intent.EXTRA_TEXT, getIntent().getStringExtra(STACKTRACE)); sendIntent.putExtra(Intent.EXTRA_SUBJECT, "FBReader " + new ErrorUtil(BookReadingErrorActivity.this).getVersionName() + " book reading issue report"); sendIntent.setType("message/rfc822"); startActivity(sendIntent); finish(); } }); final Button cancelButton = (Button)buttonView.findViewById(R.id.cancel_button); cancelButton.setText(buttonResource.getResource("cancel").getValue()); cancelButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); }
diff --git a/src/Main/WWJApplet.java b/src/Main/WWJApplet.java index 9ecb439..620aae7 100644 --- a/src/Main/WWJApplet.java +++ b/src/Main/WWJApplet.java @@ -1,1035 +1,1033 @@ package Main; /* Copyright (C) 2001, 2009 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. */ import Utilities.StateVector; import gov.nasa.worldwind.*; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.awt.WorldWindowGLCanvas; import gov.nasa.worldwind.examples.ClickAndGoSelectListener; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.layers.*; import gov.nasa.worldwind.render.GlobeAnnotation; import gov.nasa.worldwind.util.StatusBar; import gov.nasa.worldwind.view.orbit.*; import java.util.logging.Level; import java.util.logging.Logger; import netscape.javascript.JSObject; //Start of JSatTrak imports import Bodies.*; import Utilities.Time; import java.util.Hashtable; import java.text.SimpleDateFormat; import java.util.TimeZone; import Satellite.*; import java.util.Vector; import javax.swing.Timer; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import Layers.*; import gov.nasa.worldwind.examples.sunlight.*; import gov.nasa.worldwind.render.*; import java.util.ArrayList; import gov.nasa.worldwind.event.*; import gov.nasa.worldwind.awt.AWTInputHandler; import gov.nasa.worldwind.view.BasicView; import View.*; import gov.nasa.worldwind.view.orbit.BasicOrbitView; import java.util.GregorianCalendar; import Utilities.OnlineInput; import javax.swing.*; import java.awt.*; import gov.nasa.worldwind.layers.placename.*; import gov.nasa.worldwind.layers.Earth.*; /** * Provides a base application framework for simple WorldWind applets. * <p/> * A simple applet which runs World Wind with a StatusBar at the bottom and lets javascript set some view attributes. * * @author Patrick Murris * @version $Id: WWJApplet.java 15441 2011-05-14 08:50:57Z tgaskins $ */ public class WWJApplet extends JApplet { protected WorldWindowGLCanvas wwd; protected RenderableLayer labelsLayer; /* Variables being added for the JSatTrak addition to the WorldWind Applet. * Starting with: Sun and Moon bodies (update: Moon may not be used?) * Also adding: Time * Also adding: Hashtable for satellites */ // Sun object private Sun sun; private Moon moon; //Time! Time currentJulianDate = new Time(); // current sim or real time (Julian Date) // date formats for displaying and reading in private SimpleDateFormat dateformat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS z"); private SimpleDateFormat dateformatShort1 = new SimpleDateFormat("dd MMM y H:m:s.S z"); private SimpleDateFormat dateformatShort2 = new SimpleDateFormat("dd MMM y H:m:s z"); // no Milliseconds // scenario epoch time settings private boolean epochTimeEqualsCurrentTime = false; // uses current time for scenario epoch (reset button) private Time scenarioEpochDate = new Time(); // scenario epoch if epochTimeisCurrentTime = false // store local time zone for printing TimeZone localTZ = TimeZone.getDefault(); //Scenario Update variables int currentPlayDirection = 0; // 1= forward, -1=backward, =0-no animation step, but can update time (esentially a graphic ini or refresh) private double animationSimStepSeconds = 1.0; // dt in Days per animation step/time update //Animation variables private boolean stopHit = false; private long lastFPSms; private double fpsAnimation; private Timer playTimer; private int realTimeAnimationRefreshRateMs = 1000; // refresh rate for real time animation private int nonRealTimeAnimationRefreshRateMs = 50; // refresh rate for non-real time animation private int animationRefreshRateMs = nonRealTimeAnimationRefreshRateMs; // (current)Milliseconds //Satellites! // hashtable to store all the statelites currently being processed private Hashtable<String,AbstractSatellite> satHash = new Hashtable<String,AbstractSatellite>(); // time dependent objects that should be update when time is updated -- NEED TO BE SAVED? Vector<JSatTrakTimeDependent> timeDependentObjects = new Vector<JSatTrakTimeDependent>(); //Stuff from J3DEarthPanel ECIRenderableLayer eciLayer; // ECI layer for plotting in ECI coordinates ECEFRenderableLayer ecefLayer; // ECEF layer for plotting in ECEF coordinates EcefTimeDepRenderableLayer timeDepLayer; OrbitModelRenderable orbitModel; // renderable object for plotting ECEFModelRenderable ecefModel; private boolean viewModeECI = true; // view mode - ECI (true) or ECEF (false) StarsLayer starsLayer = new StarsLayer(); // view mode options private boolean modelViewMode = false; // default false private String modelViewString = ""; // to hold name of satellite to view when modelViewMode=true private double modelViewNearClip = 10000; // clipping pland for when in Model View mode private double modelViewFarClip = 5.0E7; private boolean smoothViewChanges = true; // for 3D view smoothing (only is set after model/earth view has been changed -needs to be fixed) // near/far clipping plane distances for 3d windows (can effect render speed and if full orbit is shown) private double farClippingPlaneDistOrbit = -1;//200000000d; // good out to geo, but slow for LEO, using AutoClipping plane view I made works better private double nearClippingPlaneDistOrbit = -1; // -1 value Means auto adjusting ViewControlsLayer viewControlsLayer; // sun shader private RectangularNormalTessellator tessellator; private LensFlareLayer lensFlareLayer; private AtmosphereLayer atmosphereLayer; private SunPositionProvider spp; private boolean sunShadingOn = false; // controls if sun shading is used // ECI grid private ECIRadialGrid eciRadialGrid = new ECIRadialGrid(); //Reading ephemeris data StkEphemerisReader Reader = new StkEphemerisReader(); public WWJApplet() { } public void init() { Vector<StateVector> vector; try { // Check for initial configuration values String value = getParameter("InitialLatitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LATITUDE, Double.parseDouble(value)); value = getParameter("InitialLongitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LONGITUDE, Double.parseDouble(value)); value = getParameter("InitialAltitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_ALTITUDE, Double.parseDouble(value)); value = getParameter("InitialHeading"); if (value != null) Configuration.setValue(AVKey.INITIAL_HEADING, Double.parseDouble(value)); value = getParameter("InitialPitch"); if (value != null) Configuration.setValue(AVKey.INITIAL_PITCH, Double.parseDouble(value)); Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Use normal/shading tessellator // sun shading needs this Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Create World Window GL Canvas this.wwd = new WorldWindowGLCanvas(); this.getContentPane().add(this.wwd, BorderLayout.CENTER); // Create the default model as described in the current worldwind properties. Model m = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME); this.wwd.setModel(m); //Remove original Stars Layer m.getLayers().remove(0); // // Add a renderable layer for application labels // this.labelsLayer = new RenderableLayer(); // this.labelsLayer.setName("Labels"); // insertBeforeLayerName(this.wwd, this.labelsLayer, "Compass"); // add EcefTimeDepRenderableLayer layer timeDepLayer = new EcefTimeDepRenderableLayer(currentJulianDate.getMJD(),sun); m.getLayers().add(timeDepLayer); //insertBeforeLayerName(this.wwd,timeDepLayer,"Labels");*/ // add ECI Layer -- FOR SOME REASON IF BEFORE EFEF and turned off ECEF Orbits don't show up!! Coverage effecting this too, strange eciLayer = new ECIRenderableLayer(currentJulianDate.getMJD()); // create ECI layer orbitModel = new OrbitModelRenderable(satHash, wwd.getModel().getGlobe()); eciLayer.addRenderable(orbitModel); // add renderable object eciLayer.setCurrentMJD(currentJulianDate.getMJD()); // update time again after adding renderable eciRadialGrid.setShowGrid(false); eciLayer.addRenderable(eciRadialGrid); // add grid (optional if it is on or not) m.getLayers().add(0, eciLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,eciLayer, "Labels"); CountryBoundariesLayer country = new CountryBoundariesLayer(); country.setEnabled(false); m.getLayers().add(country); Layer uhh = m.getLayers().getLayerByName("Political Boundaries"); m.getLayers().remove(uhh); // add ECEF Layer ecefLayer = new ECEFRenderableLayer(); // create ECEF layer ecefModel = new ECEFModelRenderable(satHash, wwd.getModel().getGlobe()); ecefLayer.addRenderable(ecefModel); // add renderable object ecefLayer.setEnabled(false); m.getLayers().add(ecefLayer); // add ECEF Layer //insertBeforeLayerName(this.wwd,ecefLayer,"Labels"); RenderableLayer latLongLinesLayer = createLatLongLinesLayer(); latLongLinesLayer.setName("Lat/Long Lines"); latLongLinesLayer.setEnabled(false); m.getLayers().add(latLongLinesLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,latLongLinesLayer,"Labels"); viewControlsLayer = new ViewControlsLayer(); viewControlsLayer.setLayout(AVKey.VERTICAL); // VOTD change from LAYOUT_VERTICAL (9/june/09) viewControlsLayer.setScale(6/10d); viewControlsLayer.setPosition(AVKey.SOUTHEAST); // put it on the right side viewControlsLayer.setLocationOffset( new Vec4(15,35,0,0)); viewControlsLayer.setEnabled(true); // turn off by default viewControlsLayer.setShowVeControls(false); m.getLayers().add(1,viewControlsLayer); //insertBeforeCompass(wwd, viewControlsLayer); //getLayerPanel().update(wwd); wwd.addSelectListener(new ViewControlsSelectListener(wwd, viewControlsLayer)); // first call to update time to current time: currentJulianDate.update2CurrentTime(); //update();// = getCurrentJulianDate(); // ini time // just a little touch up -- remove the milliseconds from the time int mil = currentJulianDate.get(Time.MILLISECOND); currentJulianDate.add(Time.MILLISECOND,1000-mil); // remove the milliseconds (so it shows an even second) // set time string format currentJulianDate.setDateFormat(dateformat); scenarioEpochDate.setDateFormat(dateformat); // create Sun object sun = new Sun(currentJulianDate.getMJD()); // // create Moon object // moon = new Moon(); // Moon.MoonPosition(currentJulianDate.getMJD()); OnlineInput input = new OnlineInput("http://localhost:8080/parameters.html"); int n = input.getSize(); for (int i = 0; i <n; i++) { addCustomSat(input.getSatelliteName(i)); } StkEphemerisReader reader = new StkEphemerisReader(); for (int i = 0; i <n; i++) { AbstractSatellite S = satHash.get(input.getSatelliteName(i)); S.setGroundTrackIni2False(); S.setPlot2DFootPrint(false); S.setShow3DFootprint(false); if (input.getColor(i).startsWith("b")) { S.setSatColor(Color.BLUE); } else if (input.getColor(i).startsWith("g")) { S.setSatColor(Color.GREEN); } else if (input.getColor(i).startsWith("r")) { S.setSatColor(Color.RED); } else if (input.getColor(i).startsWith("y")) { S.setSatColor(Color.YELLOW); } else if (input.getColor(i).startsWith("w")) { S.setSatColor(Color.WHITE); } else if (input.getColor(i).startsWith("p")) { S.setSatColor(Color.PINK); } else if (input.getColor(i).startsWith("o")) { S.setSatColor(Color.ORANGE); } vector = reader.readStkEphemeris(input.getEphemerisLocation(i)); S.setEphemeris(vector); // set default 3d model and turn on the use of 3d models // S.setThreeDModelPath("globalstar/Globalstar.3ds"); // S.setUse3dModel(true); if (input.getModelCentered(i)) { System.out.println("CANT DO THAT YET"); } else { //dont do anything! } double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); setTime(time); } //OLD SATELLITE READING METHOD // CustomSatellite satellite = new CustomSatellite("Test",currentJulianDate); // StkEphemerisReader reader = new StkEphemerisReader(); // //String filename = "file:///C:/Documents and Settings/MMascaro/Desktop/WorldWind_Applet/test_ephem.e"; // String filename = "http://localhost:8080/test_ephem.e"; // try // { // satellite.setEphemeris(reader.readStkEphemeris(filename)); // } // catch(Exception whocares) // {//It darn well better work without exceptions. // System.out.println("Problem Reading ephemeris file"); // } // //// satellite.setShow3D(true); //// satellite.setShowGroundTrack3d(false); //// satellite.setShow3DOrbitTrace(true); //// satellite.setShow3DOrbitTraceECI(true); //// satellite.setShow3DName(true); // satellite.setShow3DFootprint(false); //// satellite.setPlot2DFootPrint(false); // double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); // setTime(time); // satellite.propogate2JulDate(this.getCurrentJulTime()); // satHash.put("Test", satellite); //FIX FOR TRANSPARENT EARTH PROBLEM: Remove old star layer and add new star layer. starsLayer.setLongitudeOffset(Angle.fromDegrees(-eciLayer.getRotateECIdeg())); //insertBeforeLayerName(this.wwd,starsLayer,"View Controls"); m.getLayers().add(0,starsLayer); // set the sun provider to the shader spp = new CustomSunPositionProvider(sun); //ALREADY HAVE AN ATMOSPHERE LAYER (Its just not working) // Replace sky gradient with this atmosphere layer when using sun shading this.atmosphereLayer = new AtmosphereLayer(); m.getLayers().add(4,this.atmosphereLayer); //insertBeforeLayerName(this.wwd,this.atmosphereLayer,"Labels"); // Add lens flare layer this.lensFlareLayer = LensFlareLayer.getPresetInstance(LensFlareLayer.PRESET_BOLD); m.getLayers().add(this.lensFlareLayer); //insertBeforeLayerName(this.wwd,this.lensFlareLayer,"Labels"); // Get tessellator this.tessellator = (RectangularNormalTessellator)m.getGlobe().getTessellator(); // set default colors for shading this.tessellator.setAmbientColor(new Color(0.50f, 0.50f, 0.50f)); LayerList WWLayers = m.getLayers(); String TheLayers = WWLayers.toString(); System.out.println(TheLayers); for (Layer layer : m.getLayers()) { // if (layer instanceof TiledImageLayer) // { // ((TiledImageLayer) layer).setShowImageTileOutlines(false); // } if (layer instanceof LandsatI3) { ((TiledImageLayer) layer).setDrawBoundingVolumes(false); ((TiledImageLayer) layer).setEnabled(false); } if (layer instanceof CompassLayer) { ((CompassLayer) layer).setShowTilt(true); ((CompassLayer) layer).setEnabled(true); } if (layer instanceof PlaceNameLayer) { ((PlaceNameLayer) layer).setEnabled(false); // off } if (layer instanceof WorldMapLayer) { ((WorldMapLayer) layer).setEnabled(false); // off } if (layer instanceof USGSUrbanAreaOrtho) { ((USGSUrbanAreaOrtho) layer).setEnabled(false); // off } // save star layer if (layer instanceof StarsLayer) { starsLayer = (StarsLayer) layer; // for now just enlarge radius by a factor of 10 starsLayer.setRadius(starsLayer.getRadius()*10.0); } if(layer instanceof CountryBoundariesLayer) { ((CountryBoundariesLayer) layer).setEnabled(false); // off by default } if(layer instanceof AtmosphereLayer) { atmosphereLayer = (AtmosphereLayer) layer; atmosphereLayer.setEnabled(true); } - if(layer instanceof SkyGradientLayer) - ((SkyGradientLayer) layer).setEnabled(false); } // for layers //Visualization Tests // m.setShowWireframeExterior(true); // m.setShowWireframeInterior(true); // Add position listener to update light direction relative to the eye this.wwd.addPositionListener(new PositionListener() { Vec4 eyePoint; public void moved(PositionEvent event) { if(eyePoint == null || eyePoint.distanceTo3(wwd.getView().getEyePoint()) > 1000) { update(true); eyePoint = wwd.getView().getEyePoint(); } } }); setSunShadingOn(true); // enable sun shading by default // END Sun Shading ------------- setupView(); // setup needed viewing specs and use of AutoClipBasicOrbitView // Add the status bar StatusBar statusBar = new StatusBar(); this.getContentPane().add(statusBar, BorderLayout.PAGE_END); // Forward events to the status bar to provide the cursor position info. statusBar.setEventSource(this.wwd); // Setup a select listener for the worldmap click-and-go feature this.wwd.addSelectListener(new ClickAndGoSelectListener(this.wwd, WorldMapLayer.class)); updateTime(); // update plots System.out.print(this.getCurrentJulTime() + "\n"); // Call javascript appletInit() try { JSObject win = JSObject.getWindow(this); win.call("appletInit", null); } catch (Exception ignore) { } } catch (Throwable e) { e.printStackTrace(); } } public void start() { // Call javascript appletStart() try { JSObject win = JSObject.getWindow(this); win.call("appletStart", null); } catch (Exception ignore) { } } public void stop() { // Call javascript appletSop() try { JSObject win = JSObject.getWindow(this); win.call("appletStop", null); } catch (Exception ignore) { } // Shut down World Wind WorldWind.shutDown(); } /** * Adds a layer to WW current layerlist, before a named layer. Target name can be a part of the layer name * * @param wwd the <code>WorldWindow</code> reference. * @param layer the layer to be added. * @param targetName the partial layer name to be matched - case sensitive. */ public static void insertBeforeLayerName(WorldWindow wwd, Layer layer, String targetName) { // Insert the layer into the layer list just before the target layer. LayerList layers = wwd.getModel().getLayers(); int targetPosition = layers.size() - 1; for (Layer l : layers) { if (l.getName().indexOf(targetName) != -1) { targetPosition = layers.indexOf(l); break; } } layers.add(targetPosition, layer); } // ============== Public API - Javascript ======================= // /** * Move the current view position * * @param lat the target latitude in decimal degrees * @param lon the target longitude in decimal degrees */ public void gotoLatLon(double lat, double lon) { this.gotoLatLon(lat, lon, Double.NaN, 0, 0); } /** * Move the current view position, zoom, heading and pitch * * @param lat the target latitude in decimal degrees * @param lon the target longitude in decimal degrees * @param zoom the target eye distance in meters * @param heading the target heading in decimal degrees * @param pitch the target pitch in decimal degrees */ public void gotoLatLon(double lat, double lon, double zoom, double heading, double pitch) { BasicOrbitView view = (BasicOrbitView) this.wwd.getView(); if (!Double.isNaN(lat) || !Double.isNaN(lon) || !Double.isNaN(zoom)) { lat = Double.isNaN(lat) ? view.getCenterPosition().getLatitude().degrees : lat; lon = Double.isNaN(lon) ? view.getCenterPosition().getLongitude().degrees : lon; zoom = Double.isNaN(zoom) ? view.getZoom() : zoom; heading = Double.isNaN(heading) ? view.getHeading().degrees : heading; pitch = Double.isNaN(pitch) ? view.getPitch().degrees : pitch; view.addPanToAnimator(Position.fromDegrees(lat, lon, 0), Angle.fromDegrees(heading), Angle.fromDegrees(pitch), zoom, true); } } /** * Set the current view heading and pitch * * @param heading the traget heading in decimal degrees * @param pitch the target pitch in decimal degrees */ public void setHeadingAndPitch(double heading, double pitch) { BasicOrbitView view = (BasicOrbitView) this.wwd.getView(); if (!Double.isNaN(heading) || !Double.isNaN(pitch)) { heading = Double.isNaN(heading) ? view.getHeading().degrees : heading; pitch = Double.isNaN(pitch) ? view.getPitch().degrees : pitch; view.addHeadingPitchAnimator( view.getHeading(), Angle.fromDegrees(heading), view.getPitch(), Angle.fromDegrees(pitch)); } } /** * Set the current view zoom * * @param zoom the target eye distance in meters */ public void setZoom(double zoom) { BasicOrbitView view = (BasicOrbitView) this.wwd.getView(); if (!Double.isNaN(zoom)) { view.addZoomAnimator(view.getZoom(), zoom); } } /** * Get the WorldWindowGLCanvas * * @return the current WorldWindowGLCanvas */ public WorldWindowGLCanvas getWW() { return this.wwd; } /** * Get the current OrbitView * * @return the current OrbitView */ public OrbitView getOrbitView() { if (this.wwd.getView() instanceof OrbitView) return (OrbitView) this.wwd.getView(); return null; } /** * Get a reference to a layer with part of its name * * @param layerName part of the layer name to match. * * @return the corresponding layer or null if not found. */ public Layer getLayerByName(String layerName) { for (Layer layer : wwd.getModel().getLayers()) { if (layer.getName().indexOf(layerName) != -1) return layer; } return null; } /** * Add a text label at a position on the globe. * * @param text the text to be displayed. * @param lat the latitude in decimal degrees. * @param lon the longitude in decimal degrees. * @param font a string describing the font to be used. * @param color the color to be used as an hexadecimal coded string. */ public void addLabel(String text, double lat, double lon, String font, String color) { GlobeAnnotation ga = new GlobeAnnotation(text, Position.fromDegrees(lat, lon, 0), Font.decode(font), Color.decode(color)); ga.getAttributes().setBackgroundColor(Color.BLACK); ga.getAttributes().setDrawOffset(new Point(0, 0)); ga.getAttributes().setFrameShape(AVKey.SHAPE_NONE); ga.getAttributes().setEffect(AVKey.TEXT_EFFECT_OUTLINE); ga.getAttributes().setTextAlign(AVKey.CENTER); this.labelsLayer.addRenderable(ga); } //Added JSatTrak methods/classes public void updateTime() { // save old time double prevJulDate = currentJulianDate.getJulianDate(); // Get current simulation time! /*if(realTimeModeCheckBox.isSelected()) { // real time mode -- just use real time // Get current time in GMT // calculate current Juilian Date, update to current time currentJulianDate.update2CurrentTime(); //update();// = getCurrentJulianDate(); }*/ //else { // non-real time mode add fraction of time to current jul date //currentJulianDate += currentPlayDirection*animationSimStepDays; currentJulianDate.addSeconds( currentPlayDirection*animationSimStepSeconds ); } // update sun position // sun.setCurrentMJD(currentJulianDate.getMJD()); // if time jumps by more than 91 minutes check period of sat to see if // ground tracks need to be updated double timeDiffDays = Math.abs(currentJulianDate.getJulianDate()-prevJulDate); // in days checkTimeDiffResetGroundTracks(timeDiffDays); // update date box: //dateTextField.setText( currentJulianDate.getDateTimeStr() );//String.format("%tc",cal) ); // now propogate all satellites to the current time for (AbstractSatellite sat : satHash.values() ) { sat.propogate2JulDate( currentJulianDate.getJulianDate() ); } // propgate each sat // update any other time dependant objects for(JSatTrakTimeDependent tdo : timeDependentObjects) { if(tdo != null) { tdo.updateTime(currentJulianDate, satHash); } } forceRepainting(); // repaint 2d/3d earth } // update time public void checkTimeDiffResetGroundTracks(double timeDiffDays) { if( timeDiffDays > 91.0/1440.0) { // big time jump for (AbstractSatellite sat : satHash.values() ) { if(sat.getShowGroundTrack() && (sat.getPeriod() <= (timeDiffDays*24.0*60.0) ) ) { sat.setGroundTrackIni2False(); //System.out.println(sat.getName() +" - Groundtrack Initiated"); } } } } // checkTimeDiffResetGroundTracks public void forceRepainting() { wwd.redraw(); }// forceRepainting public void playScenario() { currentPlayDirection = 1; // forwards runAnimation(); // perform animation } // playScenario //NEEDS TO BE FIXED TO RUN WITHOUT ACTION LISTENER private void runAnimation() { lastFPSms = System.currentTimeMillis(); playTimer = new Timer(animationRefreshRateMs, new ActionListener() { public void actionPerformed(ActionEvent evt) { // take one time step in the aimation updateTime(); // animate long stopTime = System.currentTimeMillis(); fpsAnimation = 1.0 / ((stopTime-lastFPSms)/1000.0); // fps calculation lastFPSms = stopTime; // goal FPS: //fpsAnimation = 1.0 / (animationRefreshRateMs/1000.0); if (stopHit) { playTimer.stop(); } // SEG - if update took a long time reduce the timers repeat interval } }); } // runAnimation public void stopAnimation() { stopHit = true; // set flag for next animation step } public void addCustomSat(String name) { // if nothing given: if(name == null || name.equalsIgnoreCase("")) { System.out.println("returned"); return; } CustomSatellite prop = new CustomSatellite(name,this.getScenarioEpochDate()); satHash.put(name, prop); // set satellite time to current date prop.propogate2JulDate(this.getCurrentJulTime()); } public Time getScenarioEpochDate() { return scenarioEpochDate; } public double getCurrentJulTime() { return currentJulianDate.getJulianDate(); } private RenderableLayer createLatLongLinesLayer() { RenderableLayer shapeLayer = new RenderableLayer(); // Generate meridians ArrayList<Position> positions = new ArrayList<Position>(3); double height = 30e3; // 10e3 default for (double lon = -180; lon < 180; lon += 10) { Angle longitude = Angle.fromDegrees(lon); positions.clear(); positions.add(new Position(Angle.NEG90, longitude, height)); positions.add(new Position(Angle.ZERO, longitude, height)); positions.add(new Position(Angle.POS90, longitude, height)); Polyline polyline = new Polyline(positions); polyline.setFollowTerrain(false); polyline.setNumSubsegments(30); if(lon == -180 || lon == 0) { polyline.setColor(new Color(1f, 1f, 0f, 0.5f)); // yellow } else { polyline.setColor(new Color(1f, 1f, 1f, 0.5f)); } shapeLayer.addRenderable(polyline); } // Generate parallels for (double lat = -80; lat < 90; lat += 10) { Angle latitude = Angle.fromDegrees(lat); positions.clear(); positions.add(new Position(latitude, Angle.NEG180, height)); positions.add(new Position(latitude, Angle.ZERO, height)); positions.add(new Position(latitude, Angle.POS180, height)); Polyline polyline = new Polyline(positions); polyline.setPathType(Polyline.LINEAR); polyline.setFollowTerrain(false); polyline.setNumSubsegments(30); if(lat == 0) { polyline.setColor(new Color(1f, 1f, 0f, 0.5f)); } else { polyline.setColor(new Color(1f, 1f, 1f, 0.5f)); } shapeLayer.addRenderable(polyline); } return shapeLayer; } // Update worldwind wun shading private void update(boolean redraw) { if(sunShadingOn) //this.enableCheckBox.isSelected()) { // Compute Sun position according to current date and time LatLon sunPos = spp.getPosition(); Vec4 sun = wwd.getModel().getGlobe().computePointFromPosition(new Position(sunPos, 0)).normalize3(); Vec4 light = sun.getNegative3(); this.tessellator.setLightDirection(light); this.lensFlareLayer.setSunDirection(sun); //Already an atmosphere layer! atmosphereLayer.setSunDirection(sun); // Redraw if needed if(redraw) { wwd.redraw(); } } // if sun Shading } // update - for sun shading public void setSunShadingOn(boolean useSunShading) { if(useSunShading == sunShadingOn) { return; // nothing to do } sunShadingOn = useSunShading; if(sunShadingOn) { // enable shading - use special atmosphere for(int i = 0; i < wwd.getModel().getLayers().size(); i++) { Layer l = wwd.getModel().getLayers().get(i); if(l instanceof SkyGradientLayer) { wwd.getModel().getLayers().set(i, this.atmosphereLayer); } } } else { // disable shading // Turn off lighting this.tessellator.setLightDirection(null); this.lensFlareLayer.setSunDirection(null); this.atmosphereLayer.setSunDirection(null); // use standard atmosphere for(int i = 0; i < wwd.getModel().getLayers().size(); i++) { Layer l = wwd.getModel().getLayers().get(i); if(l instanceof AtmosphereLayer) { wwd.getModel().getLayers().set(i, new SkyGradientLayer()); } } } // if/else shading this.update(true); // redraw } // setSunShadingOn private void setupView() { if(modelViewMode == false) { // Earth View mode AutoClipBasicOrbitView bov = new AutoClipBasicOrbitView(); wwd.setView(bov); // remove the rest of the old input handler (does this need a remove of hover listener? - maybe it is now completely removed?) wwd.getInputHandler().setEventSource(null); AWTInputHandler awth = new AWTInputHandler(); awth.setEventSource(wwd); wwd.setInputHandler(awth); awth.setSmoothViewChanges(smoothViewChanges); // FALSE MAKES THE VIEW FAST!! -- MIGHT WANT TO MAKE IT GUI Chooseable // IF EARTH VIEW -- RESET CLIPPING PLANES BACK TO NORMAL SETTINGS!!! wwd.getView().setNearClipDistance(this.nearClippingPlaneDistOrbit); wwd.getView().setFarClipDistance(this.farClippingPlaneDistOrbit); // change class for inputHandler Configuration.setValue(AVKey.INPUT_HANDLER_CLASS_NAME, AWTInputHandler.class.getName()); // re-setup control layer handler wwd.addSelectListener(new ViewControlsSelectListener(wwd, viewControlsLayer)); } // Earth View mode else { // Model View mode // TEST NEW VIEW -- TO MAKE WORK MUST TURN OFF ECI! this.setViewModeECI(false); if(!satHash.containsKey(modelViewString)) { System.out.println("NO Current Satellite Selected, can't switch to Model Mode: " + modelViewString); return; } AbstractSatellite sat = satHash.get(modelViewString); BasicModelView3 bmv; if(wwd.getView() instanceof BasicOrbitView) { bmv = new BasicModelView3(((BasicOrbitView)wwd.getView()).getOrbitViewModel(), sat); //bmv = new BasicModelView3(sat); } else { bmv = new BasicModelView3(((BasicModelView3)wwd.getView()).getOrbitViewModel(), sat); } // remove the old hover listener -- depending on this instance of the input handler class type if( wwd.getInputHandler() instanceof AWTInputHandler) { ((AWTInputHandler) wwd.getInputHandler()).removeHoverSelectListener(); } else if( wwd.getInputHandler() instanceof BasicModelViewInputHandler3) { ((BasicModelViewInputHandler3) wwd.getInputHandler()).removeHoverSelectListener(); } // set view wwd.setView(bmv); // remove the rest of the old input handler wwd.getInputHandler().setEventSource(null); // add new input handler BasicModelViewInputHandler3 mih = new BasicModelViewInputHandler3(); mih.setEventSource(wwd); wwd.setInputHandler(mih); // view smooth? mih.setSmoothViewChanges(smoothViewChanges); // FALSE MAKES THE VIEW FAST!! // settings for great closeups! wwd.getView().setNearClipDistance(modelViewNearClip); wwd.getView().setFarClipDistance(modelViewFarClip); bmv.setZoom(900000); bmv.setPitch(Angle.fromDegrees(45)); // change class for inputHandler Configuration.setValue(AVKey.INPUT_HANDLER_CLASS_NAME, BasicModelViewInputHandler3.class.getName()); // re-setup control layer handler wwd.addSelectListener(new ViewControlsSelectListener(wwd, viewControlsLayer)); } // model view mode } // setupView public void setViewModeECI(boolean viewModeECI) { this.viewModeECI = viewModeECI; // take care of which view mode to use if(viewModeECI) { // update stars starsLayer.setLongitudeOffset(Angle.fromDegrees(-eciLayer.getRotateECIdeg())); } else { starsLayer.setLongitudeOffset(Angle.fromDegrees(0.0)); // reset to normal } } public void setTime(long millisecs) { currentJulianDate.set(millisecs); // update maps ---------------- // set animation direction = 0 currentPlayDirection = 0; // update graphics updateTime(); } /** * Set the current time of the app. * @param julianDate Julian Date */ public void setTime(double julianDate) { GregorianCalendar gc = Time.convertJD2Calendar(julianDate); setTime(gc.getTimeInMillis()); } }
true
true
public void init() { Vector<StateVector> vector; try { // Check for initial configuration values String value = getParameter("InitialLatitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LATITUDE, Double.parseDouble(value)); value = getParameter("InitialLongitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LONGITUDE, Double.parseDouble(value)); value = getParameter("InitialAltitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_ALTITUDE, Double.parseDouble(value)); value = getParameter("InitialHeading"); if (value != null) Configuration.setValue(AVKey.INITIAL_HEADING, Double.parseDouble(value)); value = getParameter("InitialPitch"); if (value != null) Configuration.setValue(AVKey.INITIAL_PITCH, Double.parseDouble(value)); Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Use normal/shading tessellator // sun shading needs this Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Create World Window GL Canvas this.wwd = new WorldWindowGLCanvas(); this.getContentPane().add(this.wwd, BorderLayout.CENTER); // Create the default model as described in the current worldwind properties. Model m = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME); this.wwd.setModel(m); //Remove original Stars Layer m.getLayers().remove(0); // // Add a renderable layer for application labels // this.labelsLayer = new RenderableLayer(); // this.labelsLayer.setName("Labels"); // insertBeforeLayerName(this.wwd, this.labelsLayer, "Compass"); // add EcefTimeDepRenderableLayer layer timeDepLayer = new EcefTimeDepRenderableLayer(currentJulianDate.getMJD(),sun); m.getLayers().add(timeDepLayer); //insertBeforeLayerName(this.wwd,timeDepLayer,"Labels");*/ // add ECI Layer -- FOR SOME REASON IF BEFORE EFEF and turned off ECEF Orbits don't show up!! Coverage effecting this too, strange eciLayer = new ECIRenderableLayer(currentJulianDate.getMJD()); // create ECI layer orbitModel = new OrbitModelRenderable(satHash, wwd.getModel().getGlobe()); eciLayer.addRenderable(orbitModel); // add renderable object eciLayer.setCurrentMJD(currentJulianDate.getMJD()); // update time again after adding renderable eciRadialGrid.setShowGrid(false); eciLayer.addRenderable(eciRadialGrid); // add grid (optional if it is on or not) m.getLayers().add(0, eciLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,eciLayer, "Labels"); CountryBoundariesLayer country = new CountryBoundariesLayer(); country.setEnabled(false); m.getLayers().add(country); Layer uhh = m.getLayers().getLayerByName("Political Boundaries"); m.getLayers().remove(uhh); // add ECEF Layer ecefLayer = new ECEFRenderableLayer(); // create ECEF layer ecefModel = new ECEFModelRenderable(satHash, wwd.getModel().getGlobe()); ecefLayer.addRenderable(ecefModel); // add renderable object ecefLayer.setEnabled(false); m.getLayers().add(ecefLayer); // add ECEF Layer //insertBeforeLayerName(this.wwd,ecefLayer,"Labels"); RenderableLayer latLongLinesLayer = createLatLongLinesLayer(); latLongLinesLayer.setName("Lat/Long Lines"); latLongLinesLayer.setEnabled(false); m.getLayers().add(latLongLinesLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,latLongLinesLayer,"Labels"); viewControlsLayer = new ViewControlsLayer(); viewControlsLayer.setLayout(AVKey.VERTICAL); // VOTD change from LAYOUT_VERTICAL (9/june/09) viewControlsLayer.setScale(6/10d); viewControlsLayer.setPosition(AVKey.SOUTHEAST); // put it on the right side viewControlsLayer.setLocationOffset( new Vec4(15,35,0,0)); viewControlsLayer.setEnabled(true); // turn off by default viewControlsLayer.setShowVeControls(false); m.getLayers().add(1,viewControlsLayer); //insertBeforeCompass(wwd, viewControlsLayer); //getLayerPanel().update(wwd); wwd.addSelectListener(new ViewControlsSelectListener(wwd, viewControlsLayer)); // first call to update time to current time: currentJulianDate.update2CurrentTime(); //update();// = getCurrentJulianDate(); // ini time // just a little touch up -- remove the milliseconds from the time int mil = currentJulianDate.get(Time.MILLISECOND); currentJulianDate.add(Time.MILLISECOND,1000-mil); // remove the milliseconds (so it shows an even second) // set time string format currentJulianDate.setDateFormat(dateformat); scenarioEpochDate.setDateFormat(dateformat); // create Sun object sun = new Sun(currentJulianDate.getMJD()); // // create Moon object // moon = new Moon(); // Moon.MoonPosition(currentJulianDate.getMJD()); OnlineInput input = new OnlineInput("http://localhost:8080/parameters.html"); int n = input.getSize(); for (int i = 0; i <n; i++) { addCustomSat(input.getSatelliteName(i)); } StkEphemerisReader reader = new StkEphemerisReader(); for (int i = 0; i <n; i++) { AbstractSatellite S = satHash.get(input.getSatelliteName(i)); S.setGroundTrackIni2False(); S.setPlot2DFootPrint(false); S.setShow3DFootprint(false); if (input.getColor(i).startsWith("b")) { S.setSatColor(Color.BLUE); } else if (input.getColor(i).startsWith("g")) { S.setSatColor(Color.GREEN); } else if (input.getColor(i).startsWith("r")) { S.setSatColor(Color.RED); } else if (input.getColor(i).startsWith("y")) { S.setSatColor(Color.YELLOW); } else if (input.getColor(i).startsWith("w")) { S.setSatColor(Color.WHITE); } else if (input.getColor(i).startsWith("p")) { S.setSatColor(Color.PINK); } else if (input.getColor(i).startsWith("o")) { S.setSatColor(Color.ORANGE); } vector = reader.readStkEphemeris(input.getEphemerisLocation(i)); S.setEphemeris(vector); // set default 3d model and turn on the use of 3d models // S.setThreeDModelPath("globalstar/Globalstar.3ds"); // S.setUse3dModel(true); if (input.getModelCentered(i)) { System.out.println("CANT DO THAT YET"); } else { //dont do anything! } double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); setTime(time); } //OLD SATELLITE READING METHOD // CustomSatellite satellite = new CustomSatellite("Test",currentJulianDate); // StkEphemerisReader reader = new StkEphemerisReader(); // //String filename = "file:///C:/Documents and Settings/MMascaro/Desktop/WorldWind_Applet/test_ephem.e"; // String filename = "http://localhost:8080/test_ephem.e"; // try // { // satellite.setEphemeris(reader.readStkEphemeris(filename)); // } // catch(Exception whocares) // {//It darn well better work without exceptions. // System.out.println("Problem Reading ephemeris file"); // } // //// satellite.setShow3D(true); //// satellite.setShowGroundTrack3d(false); //// satellite.setShow3DOrbitTrace(true); //// satellite.setShow3DOrbitTraceECI(true); //// satellite.setShow3DName(true); // satellite.setShow3DFootprint(false); //// satellite.setPlot2DFootPrint(false); // double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); // setTime(time); // satellite.propogate2JulDate(this.getCurrentJulTime()); // satHash.put("Test", satellite); //FIX FOR TRANSPARENT EARTH PROBLEM: Remove old star layer and add new star layer. starsLayer.setLongitudeOffset(Angle.fromDegrees(-eciLayer.getRotateECIdeg())); //insertBeforeLayerName(this.wwd,starsLayer,"View Controls"); m.getLayers().add(0,starsLayer); // set the sun provider to the shader spp = new CustomSunPositionProvider(sun); //ALREADY HAVE AN ATMOSPHERE LAYER (Its just not working) // Replace sky gradient with this atmosphere layer when using sun shading this.atmosphereLayer = new AtmosphereLayer(); m.getLayers().add(4,this.atmosphereLayer); //insertBeforeLayerName(this.wwd,this.atmosphereLayer,"Labels"); // Add lens flare layer this.lensFlareLayer = LensFlareLayer.getPresetInstance(LensFlareLayer.PRESET_BOLD); m.getLayers().add(this.lensFlareLayer); //insertBeforeLayerName(this.wwd,this.lensFlareLayer,"Labels"); // Get tessellator this.tessellator = (RectangularNormalTessellator)m.getGlobe().getTessellator(); // set default colors for shading this.tessellator.setAmbientColor(new Color(0.50f, 0.50f, 0.50f)); LayerList WWLayers = m.getLayers(); String TheLayers = WWLayers.toString(); System.out.println(TheLayers); for (Layer layer : m.getLayers()) { // if (layer instanceof TiledImageLayer) // { // ((TiledImageLayer) layer).setShowImageTileOutlines(false); // } if (layer instanceof LandsatI3) { ((TiledImageLayer) layer).setDrawBoundingVolumes(false); ((TiledImageLayer) layer).setEnabled(false); } if (layer instanceof CompassLayer) { ((CompassLayer) layer).setShowTilt(true); ((CompassLayer) layer).setEnabled(true); } if (layer instanceof PlaceNameLayer) { ((PlaceNameLayer) layer).setEnabled(false); // off } if (layer instanceof WorldMapLayer) { ((WorldMapLayer) layer).setEnabled(false); // off } if (layer instanceof USGSUrbanAreaOrtho) { ((USGSUrbanAreaOrtho) layer).setEnabled(false); // off } // save star layer if (layer instanceof StarsLayer) { starsLayer = (StarsLayer) layer; // for now just enlarge radius by a factor of 10 starsLayer.setRadius(starsLayer.getRadius()*10.0); } if(layer instanceof CountryBoundariesLayer) { ((CountryBoundariesLayer) layer).setEnabled(false); // off by default } if(layer instanceof AtmosphereLayer) { atmosphereLayer = (AtmosphereLayer) layer; atmosphereLayer.setEnabled(true); } if(layer instanceof SkyGradientLayer) ((SkyGradientLayer) layer).setEnabled(false); } // for layers //Visualization Tests // m.setShowWireframeExterior(true); // m.setShowWireframeInterior(true); // Add position listener to update light direction relative to the eye this.wwd.addPositionListener(new PositionListener() { Vec4 eyePoint; public void moved(PositionEvent event) { if(eyePoint == null || eyePoint.distanceTo3(wwd.getView().getEyePoint()) > 1000) { update(true); eyePoint = wwd.getView().getEyePoint(); } } }); setSunShadingOn(true); // enable sun shading by default // END Sun Shading ------------- setupView(); // setup needed viewing specs and use of AutoClipBasicOrbitView // Add the status bar StatusBar statusBar = new StatusBar(); this.getContentPane().add(statusBar, BorderLayout.PAGE_END); // Forward events to the status bar to provide the cursor position info. statusBar.setEventSource(this.wwd); // Setup a select listener for the worldmap click-and-go feature this.wwd.addSelectListener(new ClickAndGoSelectListener(this.wwd, WorldMapLayer.class)); updateTime(); // update plots System.out.print(this.getCurrentJulTime() + "\n"); // Call javascript appletInit() try { JSObject win = JSObject.getWindow(this); win.call("appletInit", null); } catch (Exception ignore) { } } catch (Throwable e) { e.printStackTrace(); } }
public void init() { Vector<StateVector> vector; try { // Check for initial configuration values String value = getParameter("InitialLatitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LATITUDE, Double.parseDouble(value)); value = getParameter("InitialLongitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_LONGITUDE, Double.parseDouble(value)); value = getParameter("InitialAltitude"); if (value != null) Configuration.setValue(AVKey.INITIAL_ALTITUDE, Double.parseDouble(value)); value = getParameter("InitialHeading"); if (value != null) Configuration.setValue(AVKey.INITIAL_HEADING, Double.parseDouble(value)); value = getParameter("InitialPitch"); if (value != null) Configuration.setValue(AVKey.INITIAL_PITCH, Double.parseDouble(value)); Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Use normal/shading tessellator // sun shading needs this Configuration.setValue(AVKey.TESSELLATOR_CLASS_NAME, RectangularNormalTessellator.class.getName()); // Create World Window GL Canvas this.wwd = new WorldWindowGLCanvas(); this.getContentPane().add(this.wwd, BorderLayout.CENTER); // Create the default model as described in the current worldwind properties. Model m = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME); this.wwd.setModel(m); //Remove original Stars Layer m.getLayers().remove(0); // // Add a renderable layer for application labels // this.labelsLayer = new RenderableLayer(); // this.labelsLayer.setName("Labels"); // insertBeforeLayerName(this.wwd, this.labelsLayer, "Compass"); // add EcefTimeDepRenderableLayer layer timeDepLayer = new EcefTimeDepRenderableLayer(currentJulianDate.getMJD(),sun); m.getLayers().add(timeDepLayer); //insertBeforeLayerName(this.wwd,timeDepLayer,"Labels");*/ // add ECI Layer -- FOR SOME REASON IF BEFORE EFEF and turned off ECEF Orbits don't show up!! Coverage effecting this too, strange eciLayer = new ECIRenderableLayer(currentJulianDate.getMJD()); // create ECI layer orbitModel = new OrbitModelRenderable(satHash, wwd.getModel().getGlobe()); eciLayer.addRenderable(orbitModel); // add renderable object eciLayer.setCurrentMJD(currentJulianDate.getMJD()); // update time again after adding renderable eciRadialGrid.setShowGrid(false); eciLayer.addRenderable(eciRadialGrid); // add grid (optional if it is on or not) m.getLayers().add(0, eciLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,eciLayer, "Labels"); CountryBoundariesLayer country = new CountryBoundariesLayer(); country.setEnabled(false); m.getLayers().add(country); Layer uhh = m.getLayers().getLayerByName("Political Boundaries"); m.getLayers().remove(uhh); // add ECEF Layer ecefLayer = new ECEFRenderableLayer(); // create ECEF layer ecefModel = new ECEFModelRenderable(satHash, wwd.getModel().getGlobe()); ecefLayer.addRenderable(ecefModel); // add renderable object ecefLayer.setEnabled(false); m.getLayers().add(ecefLayer); // add ECEF Layer //insertBeforeLayerName(this.wwd,ecefLayer,"Labels"); RenderableLayer latLongLinesLayer = createLatLongLinesLayer(); latLongLinesLayer.setName("Lat/Long Lines"); latLongLinesLayer.setEnabled(false); m.getLayers().add(latLongLinesLayer); // add ECI Layer //insertBeforeLayerName(this.wwd,latLongLinesLayer,"Labels"); viewControlsLayer = new ViewControlsLayer(); viewControlsLayer.setLayout(AVKey.VERTICAL); // VOTD change from LAYOUT_VERTICAL (9/june/09) viewControlsLayer.setScale(6/10d); viewControlsLayer.setPosition(AVKey.SOUTHEAST); // put it on the right side viewControlsLayer.setLocationOffset( new Vec4(15,35,0,0)); viewControlsLayer.setEnabled(true); // turn off by default viewControlsLayer.setShowVeControls(false); m.getLayers().add(1,viewControlsLayer); //insertBeforeCompass(wwd, viewControlsLayer); //getLayerPanel().update(wwd); wwd.addSelectListener(new ViewControlsSelectListener(wwd, viewControlsLayer)); // first call to update time to current time: currentJulianDate.update2CurrentTime(); //update();// = getCurrentJulianDate(); // ini time // just a little touch up -- remove the milliseconds from the time int mil = currentJulianDate.get(Time.MILLISECOND); currentJulianDate.add(Time.MILLISECOND,1000-mil); // remove the milliseconds (so it shows an even second) // set time string format currentJulianDate.setDateFormat(dateformat); scenarioEpochDate.setDateFormat(dateformat); // create Sun object sun = new Sun(currentJulianDate.getMJD()); // // create Moon object // moon = new Moon(); // Moon.MoonPosition(currentJulianDate.getMJD()); OnlineInput input = new OnlineInput("http://localhost:8080/parameters.html"); int n = input.getSize(); for (int i = 0; i <n; i++) { addCustomSat(input.getSatelliteName(i)); } StkEphemerisReader reader = new StkEphemerisReader(); for (int i = 0; i <n; i++) { AbstractSatellite S = satHash.get(input.getSatelliteName(i)); S.setGroundTrackIni2False(); S.setPlot2DFootPrint(false); S.setShow3DFootprint(false); if (input.getColor(i).startsWith("b")) { S.setSatColor(Color.BLUE); } else if (input.getColor(i).startsWith("g")) { S.setSatColor(Color.GREEN); } else if (input.getColor(i).startsWith("r")) { S.setSatColor(Color.RED); } else if (input.getColor(i).startsWith("y")) { S.setSatColor(Color.YELLOW); } else if (input.getColor(i).startsWith("w")) { S.setSatColor(Color.WHITE); } else if (input.getColor(i).startsWith("p")) { S.setSatColor(Color.PINK); } else if (input.getColor(i).startsWith("o")) { S.setSatColor(Color.ORANGE); } vector = reader.readStkEphemeris(input.getEphemerisLocation(i)); S.setEphemeris(vector); // set default 3d model and turn on the use of 3d models // S.setThreeDModelPath("globalstar/Globalstar.3ds"); // S.setUse3dModel(true); if (input.getModelCentered(i)) { System.out.println("CANT DO THAT YET"); } else { //dont do anything! } double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); setTime(time); } //OLD SATELLITE READING METHOD // CustomSatellite satellite = new CustomSatellite("Test",currentJulianDate); // StkEphemerisReader reader = new StkEphemerisReader(); // //String filename = "file:///C:/Documents and Settings/MMascaro/Desktop/WorldWind_Applet/test_ephem.e"; // String filename = "http://localhost:8080/test_ephem.e"; // try // { // satellite.setEphemeris(reader.readStkEphemeris(filename)); // } // catch(Exception whocares) // {//It darn well better work without exceptions. // System.out.println("Problem Reading ephemeris file"); // } // //// satellite.setShow3D(true); //// satellite.setShowGroundTrack3d(false); //// satellite.setShow3DOrbitTrace(true); //// satellite.setShow3DOrbitTraceECI(true); //// satellite.setShow3DName(true); // satellite.setShow3DFootprint(false); //// satellite.setPlot2DFootPrint(false); // double time = StkEphemerisReader.convertScenarioTimeString2JulianDate(reader.getScenarioEpoch() + " UTC"); // setTime(time); // satellite.propogate2JulDate(this.getCurrentJulTime()); // satHash.put("Test", satellite); //FIX FOR TRANSPARENT EARTH PROBLEM: Remove old star layer and add new star layer. starsLayer.setLongitudeOffset(Angle.fromDegrees(-eciLayer.getRotateECIdeg())); //insertBeforeLayerName(this.wwd,starsLayer,"View Controls"); m.getLayers().add(0,starsLayer); // set the sun provider to the shader spp = new CustomSunPositionProvider(sun); //ALREADY HAVE AN ATMOSPHERE LAYER (Its just not working) // Replace sky gradient with this atmosphere layer when using sun shading this.atmosphereLayer = new AtmosphereLayer(); m.getLayers().add(4,this.atmosphereLayer); //insertBeforeLayerName(this.wwd,this.atmosphereLayer,"Labels"); // Add lens flare layer this.lensFlareLayer = LensFlareLayer.getPresetInstance(LensFlareLayer.PRESET_BOLD); m.getLayers().add(this.lensFlareLayer); //insertBeforeLayerName(this.wwd,this.lensFlareLayer,"Labels"); // Get tessellator this.tessellator = (RectangularNormalTessellator)m.getGlobe().getTessellator(); // set default colors for shading this.tessellator.setAmbientColor(new Color(0.50f, 0.50f, 0.50f)); LayerList WWLayers = m.getLayers(); String TheLayers = WWLayers.toString(); System.out.println(TheLayers); for (Layer layer : m.getLayers()) { // if (layer instanceof TiledImageLayer) // { // ((TiledImageLayer) layer).setShowImageTileOutlines(false); // } if (layer instanceof LandsatI3) { ((TiledImageLayer) layer).setDrawBoundingVolumes(false); ((TiledImageLayer) layer).setEnabled(false); } if (layer instanceof CompassLayer) { ((CompassLayer) layer).setShowTilt(true); ((CompassLayer) layer).setEnabled(true); } if (layer instanceof PlaceNameLayer) { ((PlaceNameLayer) layer).setEnabled(false); // off } if (layer instanceof WorldMapLayer) { ((WorldMapLayer) layer).setEnabled(false); // off } if (layer instanceof USGSUrbanAreaOrtho) { ((USGSUrbanAreaOrtho) layer).setEnabled(false); // off } // save star layer if (layer instanceof StarsLayer) { starsLayer = (StarsLayer) layer; // for now just enlarge radius by a factor of 10 starsLayer.setRadius(starsLayer.getRadius()*10.0); } if(layer instanceof CountryBoundariesLayer) { ((CountryBoundariesLayer) layer).setEnabled(false); // off by default } if(layer instanceof AtmosphereLayer) { atmosphereLayer = (AtmosphereLayer) layer; atmosphereLayer.setEnabled(true); } } // for layers //Visualization Tests // m.setShowWireframeExterior(true); // m.setShowWireframeInterior(true); // Add position listener to update light direction relative to the eye this.wwd.addPositionListener(new PositionListener() { Vec4 eyePoint; public void moved(PositionEvent event) { if(eyePoint == null || eyePoint.distanceTo3(wwd.getView().getEyePoint()) > 1000) { update(true); eyePoint = wwd.getView().getEyePoint(); } } }); setSunShadingOn(true); // enable sun shading by default // END Sun Shading ------------- setupView(); // setup needed viewing specs and use of AutoClipBasicOrbitView // Add the status bar StatusBar statusBar = new StatusBar(); this.getContentPane().add(statusBar, BorderLayout.PAGE_END); // Forward events to the status bar to provide the cursor position info. statusBar.setEventSource(this.wwd); // Setup a select listener for the worldmap click-and-go feature this.wwd.addSelectListener(new ClickAndGoSelectListener(this.wwd, WorldMapLayer.class)); updateTime(); // update plots System.out.print(this.getCurrentJulTime() + "\n"); // Call javascript appletInit() try { JSObject win = JSObject.getWindow(this); win.call("appletInit", null); } catch (Exception ignore) { } } catch (Throwable e) { e.printStackTrace(); } }
diff --git a/src/main/java/com/dumptruckman/chunky/listeners/PlayerEvents.java b/src/main/java/com/dumptruckman/chunky/listeners/PlayerEvents.java index c5d9191..7a06413 100644 --- a/src/main/java/com/dumptruckman/chunky/listeners/PlayerEvents.java +++ b/src/main/java/com/dumptruckman/chunky/listeners/PlayerEvents.java @@ -1,52 +1,52 @@ package com.dumptruckman.chunky.listeners; import com.dumptruckman.chunky.Chunky; import com.dumptruckman.chunky.ChunkyManager; import com.dumptruckman.chunky.event.object.ChunkyPlayerChunkChangeEvent; import com.dumptruckman.chunky.exceptions.ChunkyPlayerOfflineException; import com.dumptruckman.chunky.exceptions.ChunkyUnregisteredException; import com.dumptruckman.chunky.locale.Language; import com.dumptruckman.chunky.locale.LanguagePath; import com.dumptruckman.chunky.object.ChunkyChunk; import com.dumptruckman.chunky.object.ChunkyPlayer; import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerMoveEvent; import sun.plugin2.message.Message; /** * @author dumptruckman, SwearWord */ public class PlayerEvents extends PlayerListener{ @Override public void onPlayerMove(PlayerMoveEvent event) { if(event.isCancelled()) return; ChunkyChunk toChunk = null; try { toChunk = ChunkyManager.getChunk(event.getTo()); } catch (ChunkyUnregisteredException ignored) { } ChunkyPlayer chunkyPlayer = ChunkyManager.getChunkyPlayer(event.getPlayer().getName()); ChunkyChunk fromChunk = chunkyPlayer.getLastChunk(); if(!fromChunk.equals(toChunk)) return; onPlayerChunkChange(chunkyPlayer,toChunk,fromChunk); } public void onPlayerChunkChange(ChunkyPlayer chunkyPlayer, ChunkyChunk toChunk, ChunkyChunk fromChunk) { String message = ""; if(toChunk==null && fromChunk != null) message += LanguagePath.UNREGISTERED_CHUNK_NAME; else if(toChunk != null) { if(fromChunk != null && !fromChunk.getName().equals(toChunk.getName())) message += toChunk.getName(); else message += toChunk.getName(); } ChunkyPlayerChunkChangeEvent event = new ChunkyPlayerChunkChangeEvent(chunkyPlayer,toChunk,fromChunk,message); Chunky.getModuleManager().callEvent(event); try { - chunkyPlayer.getPlayer().sendMessage(message); + chunkyPlayer.getPlayer().sendMessage(event.getMessage()); } catch (ChunkyPlayerOfflineException ignored) { } chunkyPlayer.setLastChunk(toChunk); } }
true
true
public void onPlayerChunkChange(ChunkyPlayer chunkyPlayer, ChunkyChunk toChunk, ChunkyChunk fromChunk) { String message = ""; if(toChunk==null && fromChunk != null) message += LanguagePath.UNREGISTERED_CHUNK_NAME; else if(toChunk != null) { if(fromChunk != null && !fromChunk.getName().equals(toChunk.getName())) message += toChunk.getName(); else message += toChunk.getName(); } ChunkyPlayerChunkChangeEvent event = new ChunkyPlayerChunkChangeEvent(chunkyPlayer,toChunk,fromChunk,message); Chunky.getModuleManager().callEvent(event); try { chunkyPlayer.getPlayer().sendMessage(message); } catch (ChunkyPlayerOfflineException ignored) { } chunkyPlayer.setLastChunk(toChunk); }
public void onPlayerChunkChange(ChunkyPlayer chunkyPlayer, ChunkyChunk toChunk, ChunkyChunk fromChunk) { String message = ""; if(toChunk==null && fromChunk != null) message += LanguagePath.UNREGISTERED_CHUNK_NAME; else if(toChunk != null) { if(fromChunk != null && !fromChunk.getName().equals(toChunk.getName())) message += toChunk.getName(); else message += toChunk.getName(); } ChunkyPlayerChunkChangeEvent event = new ChunkyPlayerChunkChangeEvent(chunkyPlayer,toChunk,fromChunk,message); Chunky.getModuleManager().callEvent(event); try { chunkyPlayer.getPlayer().sendMessage(event.getMessage()); } catch (ChunkyPlayerOfflineException ignored) { } chunkyPlayer.setLastChunk(toChunk); }
diff --git a/java/com/delcyon/capo/datastream/stream_attribute_filter/AbstractFilterInputStream.java b/java/com/delcyon/capo/datastream/stream_attribute_filter/AbstractFilterInputStream.java index 0d43fde..3f4711a 100644 --- a/java/com/delcyon/capo/datastream/stream_attribute_filter/AbstractFilterInputStream.java +++ b/java/com/delcyon/capo/datastream/stream_attribute_filter/AbstractFilterInputStream.java @@ -1,63 +1,65 @@ /** Copyright (C) 2012 Delcyon, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.delcyon.capo.datastream.stream_attribute_filter; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * @author jeremiah * */ public abstract class AbstractFilterInputStream extends FilterInputStream implements StreamAttributeFilter { private final byte[] smallBuffer = new byte[1]; @Override public String getName() { return getClass().getAnnotation(InputStreamAttributeFilterProvider.class).name(); } protected AbstractFilterInputStream(InputStream in) { super(in); } @Override public int read(byte[] b) throws IOException { return read(b,0,b.length); } @Override public int read() throws IOException { int bytesRead = read(smallBuffer, 0, 1); if (bytesRead > 0) //because we are always passing a buffer of length 1, this should never be zero { //the bytes come in as signed, so we need to mask them to unsigned so that code using the int read() method always gets a postive result as expected return (int)(smallBuffer[0] & 0xff); } else //if we're closed, then return -1 to indicate as much { + //clear the buffer when we haven't read anything, just in case we use the stream again, like in a zipstream + smallBuffer[0] = (byte)0; return -1; } } }
true
true
public int read() throws IOException { int bytesRead = read(smallBuffer, 0, 1); if (bytesRead > 0) //because we are always passing a buffer of length 1, this should never be zero { //the bytes come in as signed, so we need to mask them to unsigned so that code using the int read() method always gets a postive result as expected return (int)(smallBuffer[0] & 0xff); } else //if we're closed, then return -1 to indicate as much { return -1; } }
public int read() throws IOException { int bytesRead = read(smallBuffer, 0, 1); if (bytesRead > 0) //because we are always passing a buffer of length 1, this should never be zero { //the bytes come in as signed, so we need to mask them to unsigned so that code using the int read() method always gets a postive result as expected return (int)(smallBuffer[0] & 0xff); } else //if we're closed, then return -1 to indicate as much { //clear the buffer when we haven't read anything, just in case we use the stream again, like in a zipstream smallBuffer[0] = (byte)0; return -1; } }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java index 967b63a4b..7455d66cc 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java @@ -1,482 +1,484 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.executor; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.birt.core.data.DataType.AnyType; import org.eclipse.birt.core.util.IOUtil; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.executor.cache.ResultSetUtil; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.odi.IResultClass; /** * <code>ResultClass</code> contains the metadata about * the projected columns in the result set. */ public class ResultClass implements IResultClass { private ResultFieldMetadata[] projectedCols; private int m_fieldCount; private HashMap nameToIdMapping; private String[] fieldNames; private int[] fieldDriverPositions; private ResultClassHelper resultClassHelper; private boolean hasAny; private List originalAnyTypeField; public ResultClass( List projectedColumns ) throws DataException { assert( projectedColumns != null ); initColumnsInfo( projectedColumns ); } /** * * @param projectedColumns * @throws DataException */ private void validateProjectColumns( ResultFieldMetadata[] projectedColumns ) throws DataException { Set columnNameSet = new HashSet(); for( int i = 0; i < projectedColumns.length; i++ ) { ResultFieldMetadata column = projectedColumns[i]; if ( columnNameSet.contains( column.getName( ) ) ) { throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME, column.getName( ) ); } if ( columnNameSet.contains( column.getAlias( ) ) ) { throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME, column.getAlias( ) ); } columnNameSet.add( column.getName()); if( column.getAlias()!= null ) columnNameSet.add(column.getAlias()); } } /** * @param projectedColumns */ private void initColumnsInfo( List projectedColumns ) { m_fieldCount = projectedColumns.size( ); projectedCols = new ResultFieldMetadata[m_fieldCount]; nameToIdMapping = new HashMap( ); this.originalAnyTypeField = new ArrayList(); for ( int i = 0, n = projectedColumns.size( ); i < n; i++ ) { projectedCols[i] = (ResultFieldMetadata) projectedColumns.get( i ); ResultFieldMetadata column = projectedCols[i]; if( isOfAnyType( column )) { this.hasAny = true; this.originalAnyTypeField.add( new Integer( i + 1 ) ); } String upperCaseName = column.getName( ); //if ( upperCaseName != null ) // upperCaseName = upperCaseName.toUpperCase( ); // need to add 1 to the 0-based array index, so we can put the // 1-based index into the name-to-id mapping that will be used // for the rest of the interfaces in this class Integer index = new Integer( i + 1 ); // If the name is a duplicate of an existing column name or alias, // this entry is not put into the mapping table. This effectively // makes this entry inaccessible by name, which is the intended // behavior if ( !nameToIdMapping.containsKey( upperCaseName ) ) { nameToIdMapping.put( upperCaseName, index ); } String upperCaseAlias = column.getAlias( ); //if ( upperCaseAlias != null ) // upperCaseAlias = upperCaseAlias.toUpperCase( ); if ( upperCaseAlias != null && upperCaseAlias.length( ) > 0 && !nameToIdMapping.containsKey( upperCaseAlias ) ) { nameToIdMapping.put( upperCaseAlias, index ); } } } /** * * @param column * @return */ private boolean isOfAnyType( ResultFieldMetadata column ) { return column.getDataType( ).getName( ).equals( AnyType.class.getName( ) ); } /** * New an instance of ResultClass from input stream. * * @param inputStream * @throws DataException */ public ResultClass( InputStream inputStream ) throws DataException { assert inputStream != null; DataInputStream dis = new DataInputStream( inputStream ); try { List newProjectedColumns = new ArrayList( ); int size = IOUtil.readInt( dis ); for ( int i = 0; i < size; i++ ) { int driverPos = IOUtil.readInt( dis ); String name = IOUtil.readString( dis ); String lable = IOUtil.readString( dis ); String alias = IOUtil.readString( dis ); String dtName = IOUtil.readString( dis ); String ntName = IOUtil.readString( dis ); boolean bool = IOUtil.readBool( dis ); String dpdpName = IOUtil.readString( dis ); ResultFieldMetadata metaData = new ResultFieldMetadata( driverPos, name, lable, Class.forName( dtName ), ntName, bool ); metaData.setAlias( alias ); if ( dpdpName != null ) metaData.setDriverProvidedDataType( Class.forName( dpdpName ) ); newProjectedColumns.add( metaData ); } dis.close( ); initColumnsInfo( newProjectedColumns ); } catch ( ClassNotFoundException e ) { throw new DataException( ResourceConstants.RD_LOAD_ERROR, e, "Result Class" ); } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_LOAD_ERROR, e, "Result Class" ); } } /** * Serialize instance status into output stream. * * @param outputStream * @throws DataException */ public void doSave( OutputStream outputStream, Map requestColumnMap ) throws DataException { assert outputStream != null; DataOutputStream dos = new DataOutputStream( outputStream ); Set resultSetNameSet = ResultSetUtil.getRsColumnRequestMap( requestColumnMap ); // If there are refrences on columnName and columnAlias in // resultSetNameSet, size--; int size = resultSetNameSet.size( ); for ( int i = 0; i < projectedCols.length; i++ ) { String columnName = projectedCols[i].getName( ); String columnAlias = projectedCols[i].getAlias( ); - if ( resultSetNameSet.contains( columnName ) - && resultSetNameSet.contains( columnAlias ) ) + if ( columnName != null && + !columnName.equals( columnAlias ) && + resultSetNameSet.contains( columnName ) && + resultSetNameSet.contains( columnAlias ) ) size--; } try { IOUtil.writeInt( outputStream, size ); int writeCount = 0; for ( int i = 0; i < m_fieldCount; i++ ) { ResultFieldMetadata column = projectedCols[i]; // check if result set contains the column, if exists, remove it // from the result set for further invalid columns collecting if (resultSetNameSet.remove(column.getName()) || resultSetNameSet.remove(column.getAlias())) { IOUtil.writeInt( dos, column.getDriverPosition( ) ); IOUtil.writeString( dos, column.getName( ) ); IOUtil.writeString( dos, column.getLabel( ) ); IOUtil.writeString( dos, column.getAlias( ) ); IOUtil.writeString( dos, column.getDataType( ).getName( ) ); IOUtil.writeString( dos, column.getNativeTypeName( ) ); IOUtil.writeBool( dos, column.isCustom( ) ); if ( column.getDriverProvidedDataType( ) == null ) IOUtil.writeString( dos, null ); else IOUtil.writeString( dos, column.getDriverProvidedDataType( ).getName( ) ); writeCount++; } } if ( writeCount != size) { validateProjectColumns( projectedCols ); StringBuffer buf = new StringBuffer( ); for ( Iterator i = resultSetNameSet.iterator( ); i.hasNext( ); ) { String colName = (String) i.next( ); buf.append( colName ); buf.append( ',' ); } buf.deleteCharAt( buf.length( ) - 1 ); throw new DataException( ResourceConstants.RESULT_CLASS_SAVE_ERROR, buf.toString( ) ); } dos.close( ); } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_SAVE_ERROR, e, "Result Class" ); } } public int getFieldCount() { return m_fieldCount; } // returns the field names in the projected order // or an empty array if no fields were projected public String[] getFieldNames() { return doGetFieldNames(); } private String[] doGetFieldNames() { if( fieldNames == null ) { int size = m_fieldCount; fieldNames = new String[ size ]; for( int i = 0; i < size; i++ ) { fieldNames[i] = projectedCols[i].getName(); } } return fieldNames; } public int[] getFieldDriverPositions() { if( fieldDriverPositions == null ) { int size = m_fieldCount; fieldDriverPositions = new int[ size ]; for( int i = 0; i < size; i++ ) { ResultFieldMetadata column = projectedCols[i]; fieldDriverPositions[i] = column.getDriverPosition(); } } return fieldDriverPositions; } public String getFieldName( int index ) throws DataException { return projectedCols[index - 1].getName(); } public String getFieldAlias( int index ) throws DataException { return projectedCols[index - 1].getAlias(); } public int getFieldIndex( String fieldName ) { Integer i = (Integer) nameToIdMapping.get( fieldName );//.toUpperCase( ) ); return ( i == null ) ? -1 : i.intValue(); } private int doGetFieldIndex( String fieldName ) throws DataException { int index = getFieldIndex( fieldName ); if( index <= 0 ) throw new DataException( ResourceConstants.INVALID_FIELD_NAME, fieldName ); return index; } public Class getFieldValueClass( String fieldName ) throws DataException { int index = doGetFieldIndex( fieldName ); return getFieldValueClass( index ); } public Class getFieldValueClass( int index ) throws DataException { return projectedCols[index - 1].getDataType(); } public boolean isCustomField( String fieldName ) throws DataException { int index = doGetFieldIndex( fieldName ); return isCustomField( index ); } public boolean isCustomField( int index ) throws DataException { return projectedCols[index - 1].isCustom(); } public String getFieldLabel( int index ) throws DataException { return projectedCols[index - 1].getLabel(); } public String getFieldNativeTypeName( int index ) throws DataException { return projectedCols[index - 1].getNativeTypeName(); } public ResultFieldMetadata getFieldMetaData( int index ) throws DataException { return projectedCols[index - 1]; } /* * (non-Javadoc) * @see org.eclipse.birt.data.engine.odi.IResultClass#existCloborBlob() */ public boolean hasClobOrBlob( ) throws DataException { return getResultClasstHelper( ).hasClobOrBlob( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.odi.IResultClass#getClobIndexArray() */ public int[] getClobFieldIndexes( ) throws DataException { return getResultClasstHelper( ).getClobIndexArray( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.odi.IResultClass#getBlobIndexArray() */ public int[] getBlobFieldIndexes( ) throws DataException { return getResultClasstHelper( ).getBlobIndexArray( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.data.engine.odi.IResultClass#getResultObjectHelper() */ public ResultClassHelper getResultClasstHelper( ) throws DataException { if ( resultClassHelper == null ) resultClassHelper = new ResultClassHelper( this ); return resultClassHelper; } /* * (non-Javadoc) * @see org.eclipse.birt.data.engine.odi.IResultClass#hasAny() */ public boolean hasAnyTYpe( ) throws DataException { if( this.hasAny ) { for ( int i = 0; i < projectedCols.length; i++ ) { if( this.isOfAnyType( projectedCols[i] ) ) return this.hasAny; } this.hasAny = false; } return this.hasAny; } /** * * @param name * @return * @throws DataException */ public boolean wasAnyType( String name ) throws DataException { Iterator it = this.originalAnyTypeField.iterator( ); while ( it.hasNext( ) ) { int index = ((Integer)it.next( )).intValue( ); if ( this.getFieldName( index ).equals( name ) || this.getFieldAlias( index ).equals( name )) return true; } return false; } /** * * @param index * @return */ public boolean wasAnyType( int index ) { Iterator it = this.originalAnyTypeField.iterator( ); while ( it.hasNext( ) ) { if ( index == ((Integer)it.next( )).intValue( )) return true; } return false; } }
true
true
public void doSave( OutputStream outputStream, Map requestColumnMap ) throws DataException { assert outputStream != null; DataOutputStream dos = new DataOutputStream( outputStream ); Set resultSetNameSet = ResultSetUtil.getRsColumnRequestMap( requestColumnMap ); // If there are refrences on columnName and columnAlias in // resultSetNameSet, size--; int size = resultSetNameSet.size( ); for ( int i = 0; i < projectedCols.length; i++ ) { String columnName = projectedCols[i].getName( ); String columnAlias = projectedCols[i].getAlias( ); if ( resultSetNameSet.contains( columnName ) && resultSetNameSet.contains( columnAlias ) ) size--; } try { IOUtil.writeInt( outputStream, size ); int writeCount = 0; for ( int i = 0; i < m_fieldCount; i++ ) { ResultFieldMetadata column = projectedCols[i]; // check if result set contains the column, if exists, remove it // from the result set for further invalid columns collecting if (resultSetNameSet.remove(column.getName()) || resultSetNameSet.remove(column.getAlias())) { IOUtil.writeInt( dos, column.getDriverPosition( ) ); IOUtil.writeString( dos, column.getName( ) ); IOUtil.writeString( dos, column.getLabel( ) ); IOUtil.writeString( dos, column.getAlias( ) ); IOUtil.writeString( dos, column.getDataType( ).getName( ) ); IOUtil.writeString( dos, column.getNativeTypeName( ) ); IOUtil.writeBool( dos, column.isCustom( ) ); if ( column.getDriverProvidedDataType( ) == null ) IOUtil.writeString( dos, null ); else IOUtil.writeString( dos, column.getDriverProvidedDataType( ).getName( ) ); writeCount++; } } if ( writeCount != size) { validateProjectColumns( projectedCols ); StringBuffer buf = new StringBuffer( ); for ( Iterator i = resultSetNameSet.iterator( ); i.hasNext( ); ) { String colName = (String) i.next( ); buf.append( colName ); buf.append( ',' ); } buf.deleteCharAt( buf.length( ) - 1 ); throw new DataException( ResourceConstants.RESULT_CLASS_SAVE_ERROR, buf.toString( ) ); } dos.close( ); } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_SAVE_ERROR, e, "Result Class" ); } }
public void doSave( OutputStream outputStream, Map requestColumnMap ) throws DataException { assert outputStream != null; DataOutputStream dos = new DataOutputStream( outputStream ); Set resultSetNameSet = ResultSetUtil.getRsColumnRequestMap( requestColumnMap ); // If there are refrences on columnName and columnAlias in // resultSetNameSet, size--; int size = resultSetNameSet.size( ); for ( int i = 0; i < projectedCols.length; i++ ) { String columnName = projectedCols[i].getName( ); String columnAlias = projectedCols[i].getAlias( ); if ( columnName != null && !columnName.equals( columnAlias ) && resultSetNameSet.contains( columnName ) && resultSetNameSet.contains( columnAlias ) ) size--; } try { IOUtil.writeInt( outputStream, size ); int writeCount = 0; for ( int i = 0; i < m_fieldCount; i++ ) { ResultFieldMetadata column = projectedCols[i]; // check if result set contains the column, if exists, remove it // from the result set for further invalid columns collecting if (resultSetNameSet.remove(column.getName()) || resultSetNameSet.remove(column.getAlias())) { IOUtil.writeInt( dos, column.getDriverPosition( ) ); IOUtil.writeString( dos, column.getName( ) ); IOUtil.writeString( dos, column.getLabel( ) ); IOUtil.writeString( dos, column.getAlias( ) ); IOUtil.writeString( dos, column.getDataType( ).getName( ) ); IOUtil.writeString( dos, column.getNativeTypeName( ) ); IOUtil.writeBool( dos, column.isCustom( ) ); if ( column.getDriverProvidedDataType( ) == null ) IOUtil.writeString( dos, null ); else IOUtil.writeString( dos, column.getDriverProvidedDataType( ).getName( ) ); writeCount++; } } if ( writeCount != size) { validateProjectColumns( projectedCols ); StringBuffer buf = new StringBuffer( ); for ( Iterator i = resultSetNameSet.iterator( ); i.hasNext( ); ) { String colName = (String) i.next( ); buf.append( colName ); buf.append( ',' ); } buf.deleteCharAt( buf.length( ) - 1 ); throw new DataException( ResourceConstants.RESULT_CLASS_SAVE_ERROR, buf.toString( ) ); } dos.close( ); } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_SAVE_ERROR, e, "Result Class" ); } }
diff --git a/library/src/com/loopj/android/http/JsonHttpResponseHandler.java b/library/src/com/loopj/android/http/JsonHttpResponseHandler.java index 12516f8..6586eb4 100644 --- a/library/src/com/loopj/android/http/JsonHttpResponseHandler.java +++ b/library/src/com/loopj/android/http/JsonHttpResponseHandler.java @@ -1,204 +1,206 @@ /* Android Asynchronous Http Client Copyright (c) 2011 James Smith <[email protected]> http://loopj.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.loopj.android.http; import android.os.Message; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** * Used to intercept and handle the responses from requests made using * {@link AsyncHttpClient}, with automatic parsing into a {@link JSONObject} * or {@link JSONArray}. * <p/> * This class is designed to be passed to get, post, put and delete requests * with the {@link #onSuccess(JSONObject)} or {@link #onSuccess(JSONArray)} * methods anonymously overridden. * <p/> * Additionally, you can override the other event methods from the * parent class. */ public class JsonHttpResponseHandler extends AsyncHttpResponseHandler { protected static final int SUCCESS_JSON_MESSAGE = 100; // // Callbacks to be overridden, typically anonymously // /** * Fired when a request returns successfully and contains a json object * at the base of the response string. Override to handle in your * own code. * * @param response the parsed json object found in the server response (if any) */ public void onSuccess(JSONObject response) { } /** * Fired when a request returns successfully and contains a json array * at the base of the response string. Override to handle in your * own code. * * @param response the parsed json array found in the server response (if any) */ public void onSuccess(JSONArray response) { } /** * Fired when a request returns successfully and contains a json object * at the base of the response string. Override to handle in your * own code. * * @param statusCode the status code of the response * @param headers the headers of the HTTP response * @param response the parsed json object found in the server response (if any) */ public void onSuccess(int statusCode, Header[] headers, JSONObject response) { onSuccess(statusCode, response); } /** * Fired when a request returns successfully and contains a json object * at the base of the response string. Override to handle in your * own code. * * @param statusCode the status code of the response * @param response the parsed json object found in the server response (if any) */ public void onSuccess(int statusCode, JSONObject response) { onSuccess(response); } /** * Fired when a request returns successfully and contains a json array * at the base of the response string. Override to handle in your * own code. * * @param statusCode the status code of the response * @param headers the headers of the HTTP response * @param response the parsed json array found in the server response (if any) */ public void onSuccess(int statusCode, Header[] headers, JSONArray response) { onSuccess(statusCode, response); } /** * Fired when a request returns successfully and contains a json array * at the base of the response string. Override to handle in your * own code. * * @param statusCode the status code of the response * @param response the parsed json array found in the server response (if any) */ public void onSuccess(int statusCode, JSONArray response) { onSuccess(response); } public void onFailure(Throwable e, JSONObject errorResponse) { } public void onFailure(Throwable e, JSONArray errorResponse) { } // // Pre-processing of messages (executes in background threadpool thread) // @Override protected void sendSuccessMessage(int statusCode, Header[] headers, String responseBody) { if (statusCode != HttpStatus.SC_NO_CONTENT) { try { Object jsonResponse = parseResponse(responseBody); sendMessage(obtainMessage(SUCCESS_JSON_MESSAGE, new Object[]{statusCode, headers, jsonResponse})); } catch (JSONException e) { sendFailureMessage(e, responseBody); } } else { sendMessage(obtainMessage(SUCCESS_JSON_MESSAGE, new Object[]{statusCode, new JSONObject()})); } } // // Pre-processing of messages (in original calling thread, typically the UI thread) // @Override protected void handleMessage(Message msg) { switch (msg.what) { case SUCCESS_JSON_MESSAGE: Object[] response = (Object[]) msg.obj; handleSuccessJsonMessage(((Integer) response[0]).intValue(), (Header[]) response[1], response[2]); break; default: super.handleMessage(msg); } } protected void handleSuccessJsonMessage(int statusCode, Header[] headers, Object jsonResponse) { if (jsonResponse instanceof JSONObject) { onSuccess(statusCode, headers, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onSuccess(statusCode, headers, (JSONArray) jsonResponse); } else { onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()), (JSONObject) null); } } protected Object parseResponse(String responseBody) throws JSONException { Object result = null; //trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If Json is not valid this will return null responseBody = responseBody.trim(); if (responseBody.startsWith("{") || responseBody.startsWith("[")) { result = new JSONTokener(responseBody).nextValue(); } if (result == null) { result = responseBody; } return result; } @Override protected void handleFailureMessage(Throwable e, String responseBody) { try { if (responseBody != null) { Object jsonResponse = parseResponse(responseBody); if (jsonResponse instanceof JSONObject) { onFailure(e, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onFailure(e, (JSONArray) jsonResponse); + } else if (jsonResponse instanceof String) { + onFailure(e, (String) jsonResponse); } else { onFailure(e, responseBody); } } else { onFailure(e, ""); } } catch (JSONException ex) { onFailure(e, responseBody); } } }
true
true
protected void handleFailureMessage(Throwable e, String responseBody) { try { if (responseBody != null) { Object jsonResponse = parseResponse(responseBody); if (jsonResponse instanceof JSONObject) { onFailure(e, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onFailure(e, (JSONArray) jsonResponse); } else { onFailure(e, responseBody); } } else { onFailure(e, ""); } } catch (JSONException ex) { onFailure(e, responseBody); } }
protected void handleFailureMessage(Throwable e, String responseBody) { try { if (responseBody != null) { Object jsonResponse = parseResponse(responseBody); if (jsonResponse instanceof JSONObject) { onFailure(e, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onFailure(e, (JSONArray) jsonResponse); } else if (jsonResponse instanceof String) { onFailure(e, (String) jsonResponse); } else { onFailure(e, responseBody); } } else { onFailure(e, ""); } } catch (JSONException ex) { onFailure(e, responseBody); } }
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java index ed93065..c6c7e13 100644 --- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java +++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java @@ -1,169 +1,173 @@ /** * Pony's Handy Dandy Rape Generator * * INSERT BSD HERE */ package net.nexisonline.spade.chunkproviders; import java.util.logging.Logger; import libnoiseforjava.module.Multiply; import libnoiseforjava.module.Perlin; import libnoiseforjava.module.Turbulence; import org.bukkit.ChunkProvider; import org.bukkit.World; import org.bukkit.block.Biome; /** * @author PrettyPonyyy * */ public class ChunkProviderWat extends ChunkProvider { private Perlin m_perlinGenerator1; private Perlin m_perlinGenerator2; private Multiply m_multiplier; private Turbulence m_turbulence; /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#onLoad(org.bukkit.World, long) */ @Override public void onLoad(World world, long seed) { this.setHasCustomTerrain(true); try { m_perlinGenerator1 = new Perlin(); m_perlinGenerator2 = new Perlin(); m_multiplier = new Multiply(m_perlinGenerator1, m_perlinGenerator2); m_turbulence = new Turbulence(m_perlinGenerator1); m_perlinGenerator1.setSeed(1234); m_perlinGenerator1.setOctaveCount(8); m_perlinGenerator1.setFrequency(1.0f); m_perlinGenerator1.setLacunarity(0.25f); m_perlinGenerator2.setSeed(543); m_perlinGenerator2.setOctaveCount(1); m_turbulence.setSeed(135); m_turbulence.setPower(0.125); } catch (Exception e) { } } private static double lerp(double a, double b, double f) { return (a + (b - a) * f); } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[], * org.bukkit.block.Biome[], double[]) */ @Override public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { double density[][][] = new double[16][128][16]; for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { double posX = x + X; double posY = y - 64; double posZ = z + Z; - double warpMod = m_multiplier.getValue(posX * 0.004, posY * 0.004, posZ * 0.004) * 8; + double warpMod = m_perlinGenerator2.getValue(posX * 0.004, posY * 0.004, posZ * 0.004) * 8; double warpPosX = posX * warpMod; double warpPosY = posY * warpMod; double warpPosZ = posZ * warpMod; double mod = m_turbulence.getValue(warpPosX * 0.005, warpPosY * 0.005, warpPosZ * 0.005); density[x][y][z] = -(y - 64); density[x][y][z] += mod * 100; } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { if (y != 126) { density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2); density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8); } } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z += 3) { if (x == 0 && z > 0) { density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85); } else if (x > 0 && z > 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25); density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); } else if (x > 0 && z == 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); } } } } for (int x = 0; x < 16; x++) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z++) { if (density[x][y][z] > 0) { abyte[getBlockIndex(x,y,z)] = 1; } else { abyte[getBlockIndex(x,y,z)] = 0; } + // Origin point + sand to prevent 5000 years of loading. + if ((x == 0) && (z == 0) && (X == x) && (Z == z) && (y <= 63)) { + abyte[getBlockIndex(x,y,z)] = (byte) ((y == 125) ? 12 : 7); + } } } } Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z)); } }
false
true
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { double density[][][] = new double[16][128][16]; for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { double posX = x + X; double posY = y - 64; double posZ = z + Z; double warpMod = m_multiplier.getValue(posX * 0.004, posY * 0.004, posZ * 0.004) * 8; double warpPosX = posX * warpMod; double warpPosY = posY * warpMod; double warpPosZ = posZ * warpMod; double mod = m_turbulence.getValue(warpPosX * 0.005, warpPosY * 0.005, warpPosZ * 0.005); density[x][y][z] = -(y - 64); density[x][y][z] += mod * 100; } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { if (y != 126) { density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2); density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8); } } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z += 3) { if (x == 0 && z > 0) { density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85); } else if (x > 0 && z > 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25); density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); } else if (x > 0 && z == 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); } } } } for (int x = 0; x < 16; x++) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z++) { if (density[x][y][z] > 0) { abyte[getBlockIndex(x,y,z)] = 1; } else { abyte[getBlockIndex(x,y,z)] = 0; } } } } Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z)); }
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { double density[][][] = new double[16][128][16]; for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { double posX = x + X; double posY = y - 64; double posZ = z + Z; double warpMod = m_perlinGenerator2.getValue(posX * 0.004, posY * 0.004, posZ * 0.004) * 8; double warpPosX = posX * warpMod; double warpPosY = posY * warpMod; double warpPosZ = posZ * warpMod; double mod = m_turbulence.getValue(warpPosX * 0.005, warpPosY * 0.005, warpPosZ * 0.005); density[x][y][z] = -(y - 64); density[x][y][z] += mod * 100; } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y += 3) { for (int z = 0; z < 16; z += 3) { if (y != 126) { density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2); density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8); } } } } for (int x = 0; x < 16; x += 3) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z += 3) { if (x == 0 && z > 0) { density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85); } else if (x > 0 && z > 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25); density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25); density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85); } else if (x > 0 && z == 0) { density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25); density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85); } } } } for (int x = 0; x < 16; x++) { for (int y = 0; y < 128; y++) { for (int z = 0; z < 16; z++) { if (density[x][y][z] > 0) { abyte[getBlockIndex(x,y,z)] = 1; } else { abyte[getBlockIndex(x,y,z)] = 0; } // Origin point + sand to prevent 5000 years of loading. if ((x == 0) && (z == 0) && (X == x) && (Z == z) && (y <= 63)) { abyte[getBlockIndex(x,y,z)] = (byte) ((y == 125) ? 12 : 7); } } } } Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z)); }
diff --git a/src/main/java/com/authdb/AuthDB.java b/src/main/java/com/authdb/AuthDB.java index 8b88c67..5433c40 100644 --- a/src/main/java/com/authdb/AuthDB.java +++ b/src/main/java/com/authdb/AuthDB.java @@ -1,941 +1,943 @@ /** (C) Copyright 2011 CraftFire <[email protected]> Contex <[email protected]>, Wulfspider <[email protected]> This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. **/ package com.authdb; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.CodeSource; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.persistence.PersistenceException; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Event.Priority; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.authdb.listeners.AuthDBBlockListener; import com.authdb.listeners.AuthDBEntityListener; import com.authdb.listeners.AuthDBPlayerListener; import com.authdb.plugins.ZBukkitContrib; import com.authdb.plugins.ZCraftIRC; import com.authdb.plugins.ZPermissions; import com.authdb.plugins.ZPermissions.Permission; import com.authdb.util.Config; import com.authdb.util.Encryption; import com.authdb.util.Messages; import com.authdb.util.Util; import com.authdb.util.Messages.Message; import com.authdb.util.Processes; import com.authdb.util.databases.EBean; import com.authdb.util.databases.MySQL; import com.avaje.ebean.Ebean; import com.avaje.ebean.EbeanServer; import com.ensifera.animosity.craftirc.CraftIRC; public class AuthDB extends JavaPlugin { // public static org.bukkit.Server server; public static AuthDB plugin; public static EbeanServer database; public PluginDescriptionFile pluginFile = getDescription(); public static String pluginName, pluginVersion, pluginWebsite, pluginDescrption; public static CraftIRC craftircHandle; // private final AuthDBPlayerListener playerListener = new AuthDBPlayerListener(this); private final AuthDBBlockListener blockListener = new AuthDBBlockListener(this); private final AuthDBEntityListener entityListener = new AuthDBEntityListener(this); public static List<String> authorizedNames = new ArrayList<String>(); public static HashMap<String, Integer> AuthDB_Timeouts = new HashMap<String, Integer>(); public static HashMap<String, Long> AuthDB_Sessions = new HashMap<String, Long>(); public static HashMap<String, String> AuthDB_Authed = new HashMap<String, String>(); public static HashMap<String, Long> AuthDB_AuthTime = new HashMap<String, Long>(); public static HashMap<String, Long> AuthDB_RemindLogin = new HashMap<String, Long>(); public static HashMap<String, Integer> AuthDB_SpamMessage = new HashMap<String, Integer>(); public static HashMap<String, Long> AuthDB_SpamMessageTime = new HashMap<String, Long>(); public static HashMap<String, String> AuthDB_PasswordTries = new HashMap<String, String>(); public static HashMap<String, String> AuthDB_LinkedNames = new HashMap<String, String>(); public static HashMap<String, String> AuthDB_LinkedNameCheck = new HashMap<String, String>(); public static Logger log = Logger.getLogger("Minecraft"); public void onDisable() { for (Player p : getServer().getOnlinePlayers()) { EBean eBeanClass = EBean.checkPlayer(p, true); if (eBeanClass.getAuthorized() != null && eBeanClass.getAuthorized().equalsIgnoreCase("true")) { eBeanClass.setReloadtime(Util.timeStamp()); AuthDB.database.save(eBeanClass); } Processes.Logout(p); } Util.logging.Info(pluginName + " plugin " + pluginVersion + " has been disabled"); Plugin checkCraftIRC = getServer().getPluginManager().getPlugin("CraftIRC"); if ((checkCraftIRC != null) && (checkCraftIRC.isEnabled()) && (Config.CraftIRC_enabled == true)) { ZCraftIRC.sendMessage(Message.OnDisable, null); } authorizedNames.clear(); AuthDB_AuthTime.clear(); AuthDB_RemindLogin.clear(); AuthDB_SpamMessage.clear(); AuthDB_SpamMessageTime.clear(); AuthDB_LinkedNames.clear(); AuthDB_LinkedNameCheck.clear(); AuthDB_PasswordTries.clear(); AuthDB_Timeouts.clear(); AuthDB_Sessions.clear(); AuthDB_Authed.clear(); MySQL.close(); } public void onEnable() { plugin = this; setupPluginInformation(); server = getServer(); database = getDatabase(); Plugin[] plugins = server.getPluginManager().getPlugins(); //logging.Debug(System.getProperty("java.version")); /*logging.Debug(System.getProperty("java.io.tmpdir")); Util.logging.Debug(System.getProperty("java.library.path")); Util.logging.Debug(System.getProperty("java.class.path")); Util.logging.Debug(System.getProperty("user.home")); Util.logging.Debug(System.getProperty("user.dir")); Util.logging.Debug(System.getProperty("user.name")); Util.ErrorFile("HELLO"); */ int counter = 0; StringBuffer Plugins = new StringBuffer(); while (plugins.length > counter) { Plugins.append(plugins[counter].getDescription().getName() + "&_&" + plugins[counter].getDescription().getVersion()); if (plugins.length != (counter + 1)) { Plugins.append("*_*"); } counter++; } File f = new File("plugins/" + pluginName + "/config/config.yml"); if (!f.exists()) { Util.logging.Info("config.yml could not be found in plugins/AuthDB/config/! Creating config.yml!"); DefaultFile("config.yml", "config"); } new Config("config", "plugins/" + pluginName + "/config/", "config.yml"); f = new File(getDataFolder() + "/config/customdb.sql"); if (!f.exists()) { Util.logging.Info("customdb.sql could not be found in plugins/AuthDB/config/! Creating customdb.sql!"); DefaultFile("customdb.sql", "config"); } LoadYml("messages"); LoadYml("commands"); setupDatabase(); checkOldFiles(); final Plugin checkCraftIRC = getServer().getPluginManager().getPlugin("CraftIRC"); CheckPermissions(); if ((checkCraftIRC != null) && (Config.CraftIRC_enabled == true)) { craftircHandle = ((CraftIRC)checkCraftIRC); Util.logging.Info("Found supported plugin: " + checkCraftIRC.getDescription().getName()); this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { if (checkCraftIRC.isEnabled()) { ZCraftIRC.sendMessage(Message.OnEnable, null); } } }, 100); } final Plugin Backpack = getServer().getPluginManager().getPlugin("Backpack"); if (Backpack != null) { Config.hasBackpack = true; } final Plugin Check = getServer().getPluginManager().getPlugin("BukkitContrib"); if (Check != null) { Config.hasBukkitContrib = true; } PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.PLAYER_LOGIN, this.playerListener, Event.Priority.Low, this); pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Low, this); pm.registerEvent(Event.Type.PLAYER_QUIT, this.playerListener, Event.Priority.Low, this); pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, this.playerListener, Priority.Low, this); pm.registerEvent(Event.Type.PLAYER_MOVE, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_INTERACT, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Low, this); pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_RESPAWN, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_KICK, this.playerListener, Event.Priority.Lowest, this); pm.registerEvent(Event.Type.BLOCK_PLACE, this.blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_DAMAGE, this.blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_IGNITE, this.blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.ENTITY_DAMAGE, this.entityListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.ENTITY_TARGET, this.entityListener, Event.Priority.Normal, this); //PropertyManager TheSettings = new PropertyManager(new File("server.properties")); /* Properties prop = new Properties(); try { FileInputStream in = new FileInputStream(new File("server.properties")); prop.load(in); String work = prop.getProperty("online-mode"); if(work.equalsIgnoreCase("true")) { Config.onlineMode = true; } else { Config.onlineMode = false; } } catch(IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } */ Config.onlineMode = getServer().getOnlineMode(); Util.logging.Debug("Online mode: " + Config.onlineMode); updateLinkedNames(); MySQL.connect(); try { Util.checkScript("numusers",Config.script_name, null, null, null, null); } catch (SQLException e) { if (Config.custom_enabled && Config.custom_autocreate) { String enter = "\n"; Util.logging.Info("Creating default table schema for " + Config.custom_table); StringBuilder query = new StringBuilder(); String NL = System.getProperty("line.separator"); try { Scanner scanner = new Scanner(new FileInputStream(getDataFolder() + "/config/customdb.sql")); while (scanner != null && scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("CREATE TABLE") || line.contains("create table")) { query.append("CREATE TABLE IF NOT EXISTS `" + Config.custom_table + "` (" + NL); } else { query.append(line + NL); } } scanner.close(); } catch (FileNotFoundException e2) { Util.logging.StackTrace(e2.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } Util.logging.Debug(enter + query); try { MySQL.query("" + query); Util.logging.Info("Sucessfully created table " + Config.custom_table); PreparedStatement ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`"); ResultSet rs = ps.executeQuery(); if (rs.next()) { Util.logging.Info(rs.getInt("countit") + " user registrations in database"); } ps.close(); } catch (SQLException e1) { Util.logging.Info("Failed creating user table " + Config.custom_table); Util.logging.StackTrace(e1.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } } else { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } Util.logging.Info(pluginName + " plugin " + pluginVersion + " is enabled"); Util.logging.Debug("Debug is ENABLED, get ready for some heavy spam"); if (Config.custom_enabled) { if (Config.custom_encryption == null) { Util.logging.Info("**WARNING** SERVER IS RUNNING WITH NO ENCRYPTION: PASSWORDS ARE STORED IN PLAINTEXT"); } } Util.logging.Info(pluginName + " is developed by CraftFire <[email protected]>"); String thescript = "",theversion = ""; if (Config.custom_enabled) { thescript = "custom"; } else { thescript = Config.script_name; theversion = Config.script_version; } String online = "" + getServer().getOnlinePlayers().length; String max = "" + getServer().getMaxPlayers(); if (Config.usagestats_enabled) { try { Util.craftFire.postInfo(getServer().getServerName(),getServer().getVersion(),pluginVersion,System.getProperty("os.name"),System.getProperty("os.version"),System.getProperty("os.arch"),System.getProperty("java.version"),thescript,theversion,Plugins.toString(),online,max,server.getPort()); } catch (IOException e1) { Util.logging.Debug("Could not send usage stats to main server."); } } for (Player p : getServer().getOnlinePlayers()) { EBean eBeanClass = EBean.checkPlayer(p, true); if (eBeanClass.getReloadtime() + 30 > Util.timeStamp()) { Processes.Login(p); } } } public String commandString(String command) { if (command.contains(" ")) { String[] temp = command.split(" "); if (temp.length > 0) { command = temp[0].replaceAll("/", ""); } } else { command = command.replaceAll("/", ""); } return command; } public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { if (sender instanceof Player) { Player player = (Player)sender; if (cmd.getName().equalsIgnoreCase("authdb")) { if (args.length == 0) { player.sendMessage("§b Name: §f " + pluginName + " §4 " + pluginVersion); player.sendMessage("§b " + pluginName + " is developed by §4 CraftFire �e<[email protected]>"); player.sendMessage("§d " + pluginWebsite); return true; } } else if (cmd.getName().equalsIgnoreCase(commandString(Config.commands_reload)) || cmd.getName().equalsIgnoreCase(commandString(Config.aliases_reload))) { if (args.length == 1) { if (ZPermissions.isAllowed(player, Permission.command_admin_reload)) { new Config("config", "plugins/" + pluginName + "/config/", "config.yml"); LoadYml("commands"); LoadYml("messages"); player.sendMessage("§a AuthDB has been successfully reloaded!"); Messages.sendMessage(Message.reload_success, player, null); return true; } else { Messages.sendMessage(Message.protection_denied, player, null); } } } else if (cmd.getName().equalsIgnoreCase(commandString(Config.commands_logout)) || cmd.getName().equalsIgnoreCase(commandString(Config.aliases_logout))) { if (args.length == 0) { if (ZPermissions.isAllowed(player, Permission.command_logout)) { if (Processes.Logout(player)) { EBean eBeanClass = EBean.checkPlayer(player, true); eBeanClass.setSessiontime(0); getDatabase().save(eBeanClass); String check = Encryption.md5(player.getName() + Util.craftFirePlayer.getIP(player)); if (AuthDB.AuthDB_Sessions.containsKey(check)) { AuthDB_Sessions.remove(check); } Messages.sendMessage(Message.logout_success, player, null); return true; } else { Messages.sendMessage(Message.logout_failure, player, null); return true; } } else { Messages.sendMessage(Message.protection_denied, player, null); } } else if (args.length == 1) { if(ZPermissions.isAllowed(player, Permission.command_admin_logout)) { String PlayerName = args[0]; List<Player> players = sender.getServer().matchPlayer(PlayerName); if (!players.isEmpty()) { if (Processes.Logout(players.get(0))) { Messages.sendMessage(Message.logout_admin_success, player, null, players.get(0).getName()); Messages.sendMessage(Message.logout_admin, players.get(0), null); return true; } else { Messages.sendMessage(Message.logout_admin_failure, player, null, players.get(0).getName()); return true; } } Messages.sendMessage(Message.logout_admin_notfound, player, null, PlayerName); return true; } else { Messages.sendMessage(Message.protection_denied, player, null); } } } else if (isAuthorized(player) && (cmd.getName().equalsIgnoreCase(commandString(Config.commands_login)) || cmd.getName().equalsIgnoreCase(commandString(Config.aliases_login)))) { if (ZPermissions.isAllowed(player, Permission.command_admin_login)) { if (args.length == 1) { String PlayerName = args[0]; List<Player> players = sender.getServer().matchPlayer(PlayerName); if (!players.isEmpty()) { if (Processes.Logout(players.get(0))) { Messages.sendMessage(Message.login_admin_success, player, null, players.get(0).getName()); Messages.sendMessage(Message.login_admin, players.get(0), null); return true; } else { Messages.sendMessage(Message.login_admin_failure, player, null, players.get(0).getName()); return true; } } Messages.sendMessage(Message.login_admin_notfound, player, null, PlayerName); return true; } } else { Messages.sendMessage(Message.protection_denied, player, null); } } } return false; } private void setupDatabase() { try { getDatabase().find(EBean.class).findRowCount(); } catch (PersistenceException ex) { Util.logging.Info("Installing persistence database for " + pluginName + " due to first time usage"); installDDL(); } } @Override public List<Class<?>> getDatabaseClasses() { List<Class<?>> list = new ArrayList<Class<?>>(); list.add(EBean.class); return list; } void CheckPermissions() { Plugin Check1 = getServer().getPluginManager().getPlugin("Permissions"); if (Check1 != null) { ZPermissions.hasPlugin = true; } Plugin Check2 = getServer().getPluginManager().getPlugin("PermissionsBukkit"); if (Check2 != null) { if (ZPermissions.hasPlugin) { Util.logging.Info("Found 2 supported permissions plugins: " + Check1.getDescription().getName() + " " + Check1.getDescription().getVersion() + " and " + Check2.getDescription().getName() + " " + Check2.getDescription().getVersion()); Util.logging.Info("Defaulting permissions to: " + Check2.getDescription().getName() + " " + Check2.getDescription().getVersion()); } else { Util.logging.Info("Found supported plugin: " + Check2.getDescription().getName() + " " + Check2.getDescription().getVersion()); } ZPermissions.hasPermissionsBukkit = true; } else { if (ZPermissions.hasPlugin) { Util.logging.Info("Found supported plugin: " + Check1.getDescription().getName() + " " + Check1.getDescription().getVersion()); } else { Util.logging.Info("Could not load a permissions plugin, going over to OP!"); } } } void checkOldFiles() { File data = new File(getDataFolder() + "/data/", ""); if (!data.exists()) { if (data.mkdir()) { Util.logging.Debug("Created missing directory: " + getDataFolder() + "\\data\\"); } } data = new File(getDataFolder() + "/translations/", ""); if (!data.exists()) { if (data.mkdir()) { Util.logging.Debug("Created missing directory: " + getDataFolder() + "\\translations\\"); } } data = new File(getDataFolder() + "/config/", ""); if (!data.exists()) { if (data.mkdir()) { Util.logging.Debug("Created missing folder: " + getDataFolder() + "\\config\\"); } } data = new File(getDataFolder() + "/", "othernames.db"); if (data.exists()) { try { FileInputStream fstream = new FileInputStream(getDataFolder() + "/othernames.db"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; String[] split; int count = 0; EBean eBeanClass = null; while ((strLine = br.readLine()) != null) { split = strLine.split(":"); if(split.length == 2) { count++; Util.logging.Debug("Found linked name: " + split[0] + " linked with name: " + split[1]); eBeanClass = EBean.checkPlayer(split[0], false); eBeanClass.setLinkedname(split[1]); database.save(eBeanClass); } } in.close(); if(count > 0) { Util.logging.Debug("Successfully imported " + count + " linked names."); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (data.delete()) { Util.logging.Debug("Deleted file othernames.db from " + getDataFolder()); } } data = new File(getDataFolder() + "/", "idle.db"); if (data.exists()) { if (data.delete()) { Util.logging.Debug("Deleted file idle.db from " + getDataFolder()); } } data = new File(getDataFolder() + "/data/", "timeout.db"); if (data.exists()) { if (data.delete()) { Util.logging.Debug("Deleted file timeout.db from " + getDataFolder()); } } } public static boolean isAuthorized(Player player) { if (authorizedNames.contains(player.getName())) { return true; } EBean eBeanClass = EBean.find(player,EBean.Column.authorized,"true"); if (eBeanClass != null) { authorizedNames.add(player.getName()); return true; } return false; } public boolean checkPassword(String player, String password) { long start = Util.timeMS(); try { if (!Config.database_keepalive) { MySQL.connect(); } password = Matcher.quoteReplacement(password); if (!Util.checkOtherName(player).equals(player)) { player = Util.checkOtherName(player); } if (Util.checkScript("checkpassword",Config.script_name, player, password, null, null)) { long stop = Util.timeMS(); Util.logging.timeUsage(stop - start, "check the password"); return true; } if (!Config.database_keepalive) { MySQL.close(); } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); Stop("ERROR in checking password. Plugin will NOT work. Disabling it."); } long stop = Util.timeMS(); Util.logging.timeUsage(stop - start, "check the password"); return false; } public boolean isWithinRange(int number, int around, int range) { int difference = Math.abs(around - number); return difference <= range; } void Stop(String error) { Util.logging.advancedWarning(error); getServer().getPluginManager().disablePlugin(((org.bukkit.plugin.Plugin) (this))); } public boolean register(Player theplayer, String password, String email, String ipAddress) throws IOException, SQLException { if (password.length() < Integer.parseInt(Config.password_minimum)) { Messages.sendMessage(Message.password_minimum, theplayer, null); return false; } else if (password.length() > Integer.parseInt(Config.password_maximum)) { Messages.sendMessage(Message.password_maximum, theplayer, null); return false; } if (!Config.database_keepalive) { MySQL.connect(); } String player = theplayer.getName(); if (!Util.checkFilter("password",password)) { Messages.sendMessage(Message.filter_password, theplayer, null); } else { Util.checkScript("adduser",Config.script_name,player, password, email, ipAddress); } if (!Config.database_keepalive) { MySQL.close(); } return true; } List<String> getResourceListing(String path) { InputStream in = getClass().getResourceAsStream(path); ArrayList<String> temp = new ArrayList<String>(); BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); String line; try { while ((line = rdr.readLine()) != null) { temp.add(line); System.out.println("file: " + line); } rdr.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } return temp; } void LoadYml(String type) { String Language = "English"; //String[] LanguagesAll = new File(getDataFolder() + "/translations/" + type + "/").list(); File LanguagesAll = new File(getDataFolder() + "/translations"); boolean Set = false; File[] directories; FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; CodeSource src = getClass().getProtectionDomain().getCodeSource(); /* if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String directory = ze.getName(); if (directory.startsWith("files/translations/") && directory.endsWith(".yml") == false) { directory = directory.replace("files/translations/", ""); directory = directory.replace("/", ""); if(directory.equals("") == false) { Util.logging.Debug("Directory: "+directory); File f = new File(getDataFolder() + "/translations/" + directory + "/" + type + ".yml"); if (!f.exists()) { Util.logging.Info(type + ".yml" + " could not be found in plugins/AuthDB/translations/" + directory + "/! Creating " + type + ".yml"); DefaultFile(type + ".yml","translations/" + directory + ""); } if ((Config.language).equalsIgnoreCase(directory)) { Set = true; Language = directory; } } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } directories = LanguagesAll.listFiles(fileFilter); if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } /* for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (!Set) { for (int z=0; z<directories.length; z++) { if (Config.language.equalsIgnoreCase(directories[z].getName())) { Set = true; Language = directories[z].getName(); } } } if (!Set) { Util.logging.Info("Could not find translation files for " + Config.language + ", defaulting to " + Language); } else { Util.logging.Debug(type + " language set to " + Language); } new Config(type, getDataFolder() + "/translations/" + Language + "/", type + ".yml"); /*CodeSource src = getClass().getProtectionDomain().getCodeSource(); if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String fileName = ze.getName(); if (fileName.startsWith("files/translations/" + type + "/") && fileName.endsWith(".yml")) { fileName = fileName.replace("files/translations/" + type + "/", ""); File f = new File(getDataFolder() + "/translations/" + type + "/" + fileName); if (!f.exists()) { Util.logging.Info(fileName + " could not be found in plugins/AuthDB/translations/" + type + "/! Creating " + fileName); DefaultFile(fileName,"translations/" + type); } if ((Config.language + ".yml").equalsIgnoreCase(fileName)) { Set = true; Language = fileName; } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } */ } public boolean isRegistered(String when, String player) { boolean dupe = false; boolean checkneeded = true; //if (Config.debug_enable) //logging.Debug("Running function: isRegistered(String player)"); EBean eBeanClass = EBean.checkPlayer(player, true); if(eBeanClass.getRegistred().equalsIgnoreCase("true")) { if (when.equalsIgnoreCase("join")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player, null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else if (when.equalsIgnoreCase("command")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } else if (Util.checkOtherName(player) != player) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else { if (this.AuthDB_Authed.containsKey(Encryption.md5(player))) { String check = AuthDB_Authed.get(Encryption.md5(player)); if (check.equalsIgnoreCase("yes")) { checkneeded = false; return true; } else if (check.equalsIgnoreCase("no")) { return false; } } else if (checkneeded) { Util.logging.Debug("Check to see if user is registred is needed, performing check"); try { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; if (Util.checkScript("checkuser", Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); Stop("ERRORS in checking user. Plugin will NOT work. Disabling it."); } } } } return false; } public static boolean checkEmail(String email) { Util.logging.Debug("Validating email: " + email); Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(email); boolean Matches = m.matches(); if (Matches) { Util.logging.Debug("Email validation: passed!"); return true; } else { Util.logging.Debug("Email validation: failed!"); return false; } } public void storeInventory(Player player, ItemStack[] inventory, ItemStack[] armorinventory) throws IOException { StringBuffer inv = new StringBuffer(); StringBuffer armorinv = new StringBuffer(); for (short i = 0; i < inventory.length; i = (short)(i + 1)) { if (inventory[i] != null) { inv.append(inventory[i].getTypeId() + ":" + inventory[i].getAmount() + ":" + (inventory[i].getData() == null ? "" : Byte.valueOf(inventory[i].getData().getData())) + ":" + inventory[i].getDurability() + ", "); } else { inv.append("0:0:0:0,"); } } for (short i = 0; i < armorinventory.length; i = (short)(i + 1)) { if (armorinventory[i] != null) { armorinv.append(armorinventory[i].getTypeId() + ":" + armorinventory[i].getAmount() + ":" + (armorinventory[i].getData() == null ? "" : Byte.valueOf(armorinventory[i].getData().getData())) + ":" + armorinventory[i].getDurability() + ", "); } else { armorinv.append("0:0:0:0,"); } } EBean eBeanClass = EBean.find(player); eBeanClass.setInventory(inv.toString()); eBeanClass.setArmorinventory(armorinv.toString()); AuthDB.database.save(eBeanClass); } public void updateLinkedNames() { for (Player player : this.getServer().getOnlinePlayers()) { String name = Util.checkOtherName(player.getName()); if (!name.equals(player.getName())) { Util.craftFirePlayer.renamePlayer(player, name); } } } void setupPluginInformation() { pluginName = getDescription().getName(); pluginVersion = getDescription().getVersion(); pluginWebsite = getDescription().getWebsite(); pluginDescrption = getDescription().getDescription(); } public static ItemStack[] getInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getInventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); - ItemStack[] inventory = new ItemStack[36]; + ItemStack[] inventory; + if (Config.hasBackpack) { inventory = new ItemStack[252]; } + else { inventory = new ItemStack[36]; } for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setInventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } public static ItemStack[] getArmorInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getArmorinventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); ItemStack[] inventory = new ItemStack[4]; for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setArmorinventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } private void DefaultFile(String name, String folder) { File actual = new File(getDataFolder() + "/" + folder + "/", name); File direc = new File(getDataFolder() + "/" + folder + "/", ""); if (!direc.exists()) { if(direc.mkdir()) { Util.logging.Debug("Sucesfully created directory: "+direc); } } if (!actual.exists()) { java.io.InputStream input = getClass().getResourceAsStream("/files/" + folder + "/" + name); if (input != null) { java.io.FileOutputStream output = null; try { output = new java.io.FileOutputStream(actual); byte[] buf = new byte[8192]; int length = 0; while ((length = input.read(buf)) > 0) { output.write(buf, 0, length); } System.out.println("[" + pluginName + "] Written default setup for " + name); } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } finally { try { if (input != null) { input.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } try { if (output != null) { output.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } } } } }
true
true
void LoadYml(String type) { String Language = "English"; //String[] LanguagesAll = new File(getDataFolder() + "/translations/" + type + "/").list(); File LanguagesAll = new File(getDataFolder() + "/translations"); boolean Set = false; File[] directories; FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; CodeSource src = getClass().getProtectionDomain().getCodeSource(); /* if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String directory = ze.getName(); if (directory.startsWith("files/translations/") && directory.endsWith(".yml") == false) { directory = directory.replace("files/translations/", ""); directory = directory.replace("/", ""); if(directory.equals("") == false) { Util.logging.Debug("Directory: "+directory); File f = new File(getDataFolder() + "/translations/" + directory + "/" + type + ".yml"); if (!f.exists()) { Util.logging.Info(type + ".yml" + " could not be found in plugins/AuthDB/translations/" + directory + "/! Creating " + type + ".yml"); DefaultFile(type + ".yml","translations/" + directory + ""); } if ((Config.language).equalsIgnoreCase(directory)) { Set = true; Language = directory; } } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } directories = LanguagesAll.listFiles(fileFilter); if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } /* for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (!Set) { for (int z=0; z<directories.length; z++) { if (Config.language.equalsIgnoreCase(directories[z].getName())) { Set = true; Language = directories[z].getName(); } } } if (!Set) { Util.logging.Info("Could not find translation files for " + Config.language + ", defaulting to " + Language); } else { Util.logging.Debug(type + " language set to " + Language); } new Config(type, getDataFolder() + "/translations/" + Language + "/", type + ".yml"); /*CodeSource src = getClass().getProtectionDomain().getCodeSource(); if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String fileName = ze.getName(); if (fileName.startsWith("files/translations/" + type + "/") && fileName.endsWith(".yml")) { fileName = fileName.replace("files/translations/" + type + "/", ""); File f = new File(getDataFolder() + "/translations/" + type + "/" + fileName); if (!f.exists()) { Util.logging.Info(fileName + " could not be found in plugins/AuthDB/translations/" + type + "/! Creating " + fileName); DefaultFile(fileName,"translations/" + type); } if ((Config.language + ".yml").equalsIgnoreCase(fileName)) { Set = true; Language = fileName; } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } */ } public boolean isRegistered(String when, String player) { boolean dupe = false; boolean checkneeded = true; //if (Config.debug_enable) //logging.Debug("Running function: isRegistered(String player)"); EBean eBeanClass = EBean.checkPlayer(player, true); if(eBeanClass.getRegistred().equalsIgnoreCase("true")) { if (when.equalsIgnoreCase("join")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player, null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else if (when.equalsIgnoreCase("command")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } else if (Util.checkOtherName(player) != player) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else { if (this.AuthDB_Authed.containsKey(Encryption.md5(player))) { String check = AuthDB_Authed.get(Encryption.md5(player)); if (check.equalsIgnoreCase("yes")) { checkneeded = false; return true; } else if (check.equalsIgnoreCase("no")) { return false; } } else if (checkneeded) { Util.logging.Debug("Check to see if user is registred is needed, performing check"); try { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; if (Util.checkScript("checkuser", Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); Stop("ERRORS in checking user. Plugin will NOT work. Disabling it."); } } } } return false; } public static boolean checkEmail(String email) { Util.logging.Debug("Validating email: " + email); Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(email); boolean Matches = m.matches(); if (Matches) { Util.logging.Debug("Email validation: passed!"); return true; } else { Util.logging.Debug("Email validation: failed!"); return false; } } public void storeInventory(Player player, ItemStack[] inventory, ItemStack[] armorinventory) throws IOException { StringBuffer inv = new StringBuffer(); StringBuffer armorinv = new StringBuffer(); for (short i = 0; i < inventory.length; i = (short)(i + 1)) { if (inventory[i] != null) { inv.append(inventory[i].getTypeId() + ":" + inventory[i].getAmount() + ":" + (inventory[i].getData() == null ? "" : Byte.valueOf(inventory[i].getData().getData())) + ":" + inventory[i].getDurability() + ", "); } else { inv.append("0:0:0:0,"); } } for (short i = 0; i < armorinventory.length; i = (short)(i + 1)) { if (armorinventory[i] != null) { armorinv.append(armorinventory[i].getTypeId() + ":" + armorinventory[i].getAmount() + ":" + (armorinventory[i].getData() == null ? "" : Byte.valueOf(armorinventory[i].getData().getData())) + ":" + armorinventory[i].getDurability() + ", "); } else { armorinv.append("0:0:0:0,"); } } EBean eBeanClass = EBean.find(player); eBeanClass.setInventory(inv.toString()); eBeanClass.setArmorinventory(armorinv.toString()); AuthDB.database.save(eBeanClass); } public void updateLinkedNames() { for (Player player : this.getServer().getOnlinePlayers()) { String name = Util.checkOtherName(player.getName()); if (!name.equals(player.getName())) { Util.craftFirePlayer.renamePlayer(player, name); } } } void setupPluginInformation() { pluginName = getDescription().getName(); pluginVersion = getDescription().getVersion(); pluginWebsite = getDescription().getWebsite(); pluginDescrption = getDescription().getDescription(); } public static ItemStack[] getInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getInventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); ItemStack[] inventory = new ItemStack[36]; for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setInventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } public static ItemStack[] getArmorInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getArmorinventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); ItemStack[] inventory = new ItemStack[4]; for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setArmorinventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } private void DefaultFile(String name, String folder) { File actual = new File(getDataFolder() + "/" + folder + "/", name); File direc = new File(getDataFolder() + "/" + folder + "/", ""); if (!direc.exists()) { if(direc.mkdir()) { Util.logging.Debug("Sucesfully created directory: "+direc); } } if (!actual.exists()) { java.io.InputStream input = getClass().getResourceAsStream("/files/" + folder + "/" + name); if (input != null) { java.io.FileOutputStream output = null; try { output = new java.io.FileOutputStream(actual); byte[] buf = new byte[8192]; int length = 0; while ((length = input.read(buf)) > 0) { output.write(buf, 0, length); } System.out.println("[" + pluginName + "] Written default setup for " + name); } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } finally { try { if (input != null) { input.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } try { if (output != null) { output.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } } } } }
void LoadYml(String type) { String Language = "English"; //String[] LanguagesAll = new File(getDataFolder() + "/translations/" + type + "/").list(); File LanguagesAll = new File(getDataFolder() + "/translations"); boolean Set = false; File[] directories; FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; CodeSource src = getClass().getProtectionDomain().getCodeSource(); /* if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String directory = ze.getName(); if (directory.startsWith("files/translations/") && directory.endsWith(".yml") == false) { directory = directory.replace("files/translations/", ""); directory = directory.replace("/", ""); if(directory.equals("") == false) { Util.logging.Debug("Directory: "+directory); File f = new File(getDataFolder() + "/translations/" + directory + "/" + type + ".yml"); if (!f.exists()) { Util.logging.Info(type + ".yml" + " could not be found in plugins/AuthDB/translations/" + directory + "/! Creating " + type + ".yml"); DefaultFile(type + ".yml","translations/" + directory + ""); } if ((Config.language).equalsIgnoreCase(directory)) { Set = true; Language = directory; } } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } directories = LanguagesAll.listFiles(fileFilter); if(directories.length > 0) { Util.logging.Debug("Found " + directories.length + " directories for " + type); } else { Util.logging.error("Error! Could not find any directories for " + type); } /* for (int i=0; i<directories.length; i++) { Util.logging.Debug("Found translation directory '" + directories[i].getName() + "' for " + type); */ if (!Set) { for (int z=0; z<directories.length; z++) { if (Config.language.equalsIgnoreCase(directories[z].getName())) { Set = true; Language = directories[z].getName(); } } } if (!Set) { Util.logging.Info("Could not find translation files for " + Config.language + ", defaulting to " + Language); } else { Util.logging.Debug(type + " language set to " + Language); } new Config(type, getDataFolder() + "/translations/" + Language + "/", type + ".yml"); /*CodeSource src = getClass().getProtectionDomain().getCodeSource(); if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String fileName = ze.getName(); if (fileName.startsWith("files/translations/" + type + "/") && fileName.endsWith(".yml")) { fileName = fileName.replace("files/translations/" + type + "/", ""); File f = new File(getDataFolder() + "/translations/" + type + "/" + fileName); if (!f.exists()) { Util.logging.Info(fileName + " could not be found in plugins/AuthDB/translations/" + type + "/! Creating " + fileName); DefaultFile(fileName,"translations/" + type); } if ((Config.language + ".yml").equalsIgnoreCase(fileName)) { Set = true; Language = fileName; } } } zip.close(); } catch (IOException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } */ } public boolean isRegistered(String when, String player) { boolean dupe = false; boolean checkneeded = true; //if (Config.debug_enable) //logging.Debug("Running function: isRegistered(String player)"); EBean eBeanClass = EBean.checkPlayer(player, true); if(eBeanClass.getRegistred().equalsIgnoreCase("true")) { if (when.equalsIgnoreCase("join")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player, null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else if (when.equalsIgnoreCase("command")) { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; try { if (Util.checkScript("checkuser",Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } else if (Util.checkOtherName(player) != player) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } else { if (this.AuthDB_Authed.containsKey(Encryption.md5(player))) { String check = AuthDB_Authed.get(Encryption.md5(player)); if (check.equalsIgnoreCase("yes")) { checkneeded = false; return true; } else if (check.equalsIgnoreCase("no")) { return false; } } else if (checkneeded) { Util.logging.Debug("Check to see if user is registred is needed, performing check"); try { if (!Config.database_keepalive) { MySQL.connect(); } Config.hasForumBoard = false; if (Util.checkScript("checkuser", Config.script_name, player.toLowerCase(), null, null, null)) { AuthDB_Authed.put(Encryption.md5(player), "yes"); dupe = true; } if (!Config.database_keepalive) { MySQL.close(); } if (!dupe) { AuthDB_Authed.put(Encryption.md5(player), "no"); } return dupe; } catch (SQLException e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); Stop("ERRORS in checking user. Plugin will NOT work. Disabling it."); } } } } return false; } public static boolean checkEmail(String email) { Util.logging.Debug("Validating email: " + email); Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(email); boolean Matches = m.matches(); if (Matches) { Util.logging.Debug("Email validation: passed!"); return true; } else { Util.logging.Debug("Email validation: failed!"); return false; } } public void storeInventory(Player player, ItemStack[] inventory, ItemStack[] armorinventory) throws IOException { StringBuffer inv = new StringBuffer(); StringBuffer armorinv = new StringBuffer(); for (short i = 0; i < inventory.length; i = (short)(i + 1)) { if (inventory[i] != null) { inv.append(inventory[i].getTypeId() + ":" + inventory[i].getAmount() + ":" + (inventory[i].getData() == null ? "" : Byte.valueOf(inventory[i].getData().getData())) + ":" + inventory[i].getDurability() + ", "); } else { inv.append("0:0:0:0,"); } } for (short i = 0; i < armorinventory.length; i = (short)(i + 1)) { if (armorinventory[i] != null) { armorinv.append(armorinventory[i].getTypeId() + ":" + armorinventory[i].getAmount() + ":" + (armorinventory[i].getData() == null ? "" : Byte.valueOf(armorinventory[i].getData().getData())) + ":" + armorinventory[i].getDurability() + ", "); } else { armorinv.append("0:0:0:0,"); } } EBean eBeanClass = EBean.find(player); eBeanClass.setInventory(inv.toString()); eBeanClass.setArmorinventory(armorinv.toString()); AuthDB.database.save(eBeanClass); } public void updateLinkedNames() { for (Player player : this.getServer().getOnlinePlayers()) { String name = Util.checkOtherName(player.getName()); if (!name.equals(player.getName())) { Util.craftFirePlayer.renamePlayer(player, name); } } } void setupPluginInformation() { pluginName = getDescription().getName(); pluginVersion = getDescription().getVersion(); pluginWebsite = getDescription().getWebsite(); pluginDescrption = getDescription().getDescription(); } public static ItemStack[] getInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getInventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); ItemStack[] inventory; if (Config.hasBackpack) { inventory = new ItemStack[252]; } else { inventory = new ItemStack[36]; } for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setInventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } public static ItemStack[] getArmorInventory(Player player) { EBean eBeanClass = EBean.find(player); if (eBeanClass != null) { String data = eBeanClass.getArmorinventory(); if (data != "" && data != null) { String[] inv = Util.split(data, ", "); ItemStack[] inventory = new ItemStack[4]; for (int i=0; i<inv.length; i++) { String line = inv[i]; String[] split = line.split(":"); if (split.length == 4) { int type = Integer.valueOf(split[0]).intValue(); inventory[i] = new ItemStack(type, Integer.valueOf(split[1]).intValue()); short dur = Short.valueOf(split[3]).shortValue(); if (dur > 0) { inventory[i].setDurability(dur); } byte dd; if (split[2].length() == 0) { dd = 0; } else { dd = Byte.valueOf(split[2]).byteValue(); } Material mat = Material.getMaterial(type); if (mat == null) { inventory[i].setData(new MaterialData(type, dd)); } else { inventory[i].setData(mat.getNewData(dd)); } } } eBeanClass.setArmorinventory(null); AuthDB.database.save(eBeanClass); return inventory; } } return null; } private void DefaultFile(String name, String folder) { File actual = new File(getDataFolder() + "/" + folder + "/", name); File direc = new File(getDataFolder() + "/" + folder + "/", ""); if (!direc.exists()) { if(direc.mkdir()) { Util.logging.Debug("Sucesfully created directory: "+direc); } } if (!actual.exists()) { java.io.InputStream input = getClass().getResourceAsStream("/files/" + folder + "/" + name); if (input != null) { java.io.FileOutputStream output = null; try { output = new java.io.FileOutputStream(actual); byte[] buf = new byte[8192]; int length = 0; while ((length = input.read(buf)) > 0) { output.write(buf, 0, length); } System.out.println("[" + pluginName + "] Written default setup for " + name); } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } finally { try { if (input != null) { input.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } try { if (output != null) { output.close(); } } catch (Exception e) { Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName()); } } } } } }
diff --git a/src/main/java/tconstruct/smeltery/TinkerSmelteryEvents.java b/src/main/java/tconstruct/smeltery/TinkerSmelteryEvents.java index 8df83270d..60b1e8703 100644 --- a/src/main/java/tconstruct/smeltery/TinkerSmelteryEvents.java +++ b/src/main/java/tconstruct/smeltery/TinkerSmelteryEvents.java @@ -1,96 +1,96 @@ package tconstruct.smeltery; import mantle.world.WorldHelper; import net.minecraft.block.Block; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MovingObjectPosition.MovingObjectType; import net.minecraftforge.event.entity.player.FillBucketEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import tconstruct.armor.player.TPlayerStats; import tconstruct.library.tools.AbilityHelper; import tconstruct.smeltery.blocks.LiquidMetalFinite; import tconstruct.smeltery.blocks.TankAirBlock; import tconstruct.tools.TinkerTools; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.gameevent.PlayerEvent.ItemCraftedEvent; public class TinkerSmelteryEvents { @SubscribeEvent public void onCrafting (ItemCraftedEvent event) { Item item = event.crafting.getItem(); if (!event.player.worldObj.isRemote) { if (item == Item.getItemFromBlock(TinkerSmeltery.smeltery) || item == Item.getItemFromBlock(TinkerSmeltery.lavaTank)) { TPlayerStats stats = TPlayerStats.get(event.player); if (!stats.smelteryManual) { stats.smelteryManual = true; AbilityHelper.spawnItemAtPlayer(event.player, new ItemStack(TinkerTools.manualBook, 1, 2)); } } } } @SubscribeEvent public void bucketFill (FillBucketEvent evt) { - if (evt.current.getItem() == Items.bucket && evt.target.typeOfHit == MovingObjectType.ENTITY) + if (evt.current.getItem() == Items.bucket && evt.target.typeOfHit == MovingObjectType.BLOCK) { int hitX = evt.target.blockX; int hitY = evt.target.blockY; int hitZ = evt.target.blockZ; if (evt.entityPlayer != null && !evt.entityPlayer.canPlayerEdit(hitX, hitY, hitZ, evt.target.sideHit, evt.current)) { return; } Block bID = evt.world.getBlock(hitX, hitY, hitZ); for (int id = 0; id < TinkerSmeltery.fluidBlocks.length; id++) { if (bID == TinkerSmeltery.fluidBlocks[id]) { if (evt.entityPlayer.capabilities.isCreativeMode) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { if (TinkerSmeltery.fluidBlocks[id] instanceof LiquidMetalFinite) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } evt.setResult(Result.ALLOW); evt.result = new ItemStack(TinkerSmeltery.buckets, 1, id); } } } } } // Player interact event - prevent breaking of tank air blocks in creative @SubscribeEvent public void playerInteract (PlayerInteractEvent event) { if (event.action == Action.LEFT_CLICK_BLOCK) { Block block = event.entity.worldObj.getBlock(event.x, event.y, event.z); if (block instanceof TankAirBlock) { event.setCanceled(true); } } } }
true
true
public void bucketFill (FillBucketEvent evt) { if (evt.current.getItem() == Items.bucket && evt.target.typeOfHit == MovingObjectType.ENTITY) { int hitX = evt.target.blockX; int hitY = evt.target.blockY; int hitZ = evt.target.blockZ; if (evt.entityPlayer != null && !evt.entityPlayer.canPlayerEdit(hitX, hitY, hitZ, evt.target.sideHit, evt.current)) { return; } Block bID = evt.world.getBlock(hitX, hitY, hitZ); for (int id = 0; id < TinkerSmeltery.fluidBlocks.length; id++) { if (bID == TinkerSmeltery.fluidBlocks[id]) { if (evt.entityPlayer.capabilities.isCreativeMode) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { if (TinkerSmeltery.fluidBlocks[id] instanceof LiquidMetalFinite) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } evt.setResult(Result.ALLOW); evt.result = new ItemStack(TinkerSmeltery.buckets, 1, id); } } } } }
public void bucketFill (FillBucketEvent evt) { if (evt.current.getItem() == Items.bucket && evt.target.typeOfHit == MovingObjectType.BLOCK) { int hitX = evt.target.blockX; int hitY = evt.target.blockY; int hitZ = evt.target.blockZ; if (evt.entityPlayer != null && !evt.entityPlayer.canPlayerEdit(hitX, hitY, hitZ, evt.target.sideHit, evt.current)) { return; } Block bID = evt.world.getBlock(hitX, hitY, hitZ); for (int id = 0; id < TinkerSmeltery.fluidBlocks.length; id++) { if (bID == TinkerSmeltery.fluidBlocks[id]) { if (evt.entityPlayer.capabilities.isCreativeMode) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { if (TinkerSmeltery.fluidBlocks[id] instanceof LiquidMetalFinite) { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } else { WorldHelper.setBlockToAir(evt.world, hitX, hitY, hitZ); } evt.setResult(Result.ALLOW); evt.result = new ItemStack(TinkerSmeltery.buckets, 1, id); } } } } }
diff --git a/src/org/nutz/mvc/view/ServerRedirectView.java b/src/org/nutz/mvc/view/ServerRedirectView.java index 3e356dce8..879f07944 100644 --- a/src/org/nutz/mvc/view/ServerRedirectView.java +++ b/src/org/nutz/mvc/view/ServerRedirectView.java @@ -1,91 +1,91 @@ package org.nutz.mvc.view; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.segment.CharSegment; import org.nutz.lang.segment.Segment; import org.nutz.mvc.View; /** * 重定向视图 * <p> * 在入口函数上声明: * <p> * '@Ok("redirect:/pet/list.nut")' * <p> * 实际上相当于:<br> * new ServerRedirectView("/pet/list.nut"); * * @author zozoh([email protected]) */ public class ServerRedirectView implements View { private Segment dest; public ServerRedirectView(String dest) { this.dest = new CharSegment(Strings.trim(dest)); } // TODO 这个函数写的有点烂,有时间重构一下 public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception { Mirror<?> mirror = Mirror.me(obj); boolean isMap = null != obj && obj instanceof Map<?, ?>; - Map<?, ?> map = isMap ? null : (Map<?, ?>) obj; + Map<?, ?> map = isMap ? (Map<?, ?>) obj : null; // Fill path Set<String> keySet = dest.keys(); Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); Object value = null; int length = key.length(); if (key.startsWith("p.") && length > 2) { value = req.getParameter(key.substring(2)); } // Map else if (isMap && key.startsWith("obj.") && length > 4) { value = map.get(key); } // POJO else if (null != mirror && key.startsWith("obj.") && length > 4) { value = mirror.getValue(obj, key.substring(4)); } // Normal value else { value = obj; } if (null == value) value = obj; dest.set(key, value); } // Format the path ... String path = dest.toString(); // Another site if (path.startsWith("http://") || path.startsWith("https://")) {} // Absolute path, add the context path for it else if (path.startsWith("/")) { path = req.getContextPath() + path; } // Relative path, add current URL path for it else { String myPath = req.getPathInfo(); int pos = myPath.lastIndexOf('/'); if (pos > 0) path = myPath.substring(0, pos) + "/" + path; else path = "/" + path; } resp.sendRedirect(path); resp.flushBuffer(); } }
true
true
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception { Mirror<?> mirror = Mirror.me(obj); boolean isMap = null != obj && obj instanceof Map<?, ?>; Map<?, ?> map = isMap ? null : (Map<?, ?>) obj; // Fill path Set<String> keySet = dest.keys(); Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); Object value = null; int length = key.length(); if (key.startsWith("p.") && length > 2) { value = req.getParameter(key.substring(2)); } // Map else if (isMap && key.startsWith("obj.") && length > 4) { value = map.get(key); } // POJO else if (null != mirror && key.startsWith("obj.") && length > 4) { value = mirror.getValue(obj, key.substring(4)); } // Normal value else { value = obj; } if (null == value) value = obj; dest.set(key, value); } // Format the path ... String path = dest.toString(); // Another site if (path.startsWith("http://") || path.startsWith("https://")) {} // Absolute path, add the context path for it else if (path.startsWith("/")) { path = req.getContextPath() + path; } // Relative path, add current URL path for it else { String myPath = req.getPathInfo(); int pos = myPath.lastIndexOf('/'); if (pos > 0) path = myPath.substring(0, pos) + "/" + path; else path = "/" + path; } resp.sendRedirect(path); resp.flushBuffer(); }
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception { Mirror<?> mirror = Mirror.me(obj); boolean isMap = null != obj && obj instanceof Map<?, ?>; Map<?, ?> map = isMap ? (Map<?, ?>) obj : null; // Fill path Set<String> keySet = dest.keys(); Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); Object value = null; int length = key.length(); if (key.startsWith("p.") && length > 2) { value = req.getParameter(key.substring(2)); } // Map else if (isMap && key.startsWith("obj.") && length > 4) { value = map.get(key); } // POJO else if (null != mirror && key.startsWith("obj.") && length > 4) { value = mirror.getValue(obj, key.substring(4)); } // Normal value else { value = obj; } if (null == value) value = obj; dest.set(key, value); } // Format the path ... String path = dest.toString(); // Another site if (path.startsWith("http://") || path.startsWith("https://")) {} // Absolute path, add the context path for it else if (path.startsWith("/")) { path = req.getContextPath() + path; } // Relative path, add current URL path for it else { String myPath = req.getPathInfo(); int pos = myPath.lastIndexOf('/'); if (pos > 0) path = myPath.substring(0, pos) + "/" + path; else path = "/" + path; } resp.sendRedirect(path); resp.flushBuffer(); }
diff --git a/src/com/android/apps/tag/record/ImageRecord.java b/src/com/android/apps/tag/record/ImageRecord.java index 34af2ee..95eb329 100644 --- a/src/com/android/apps/tag/record/ImageRecord.java +++ b/src/com/android/apps/tag/record/ImageRecord.java @@ -1,81 +1,84 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.apps.tag.record; import com.android.apps.tag.R; import com.google.common.base.Preconditions; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.nfc.NdefRecord; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.ByteArrayOutputStream; /** * A NdefRecord corresponding to an image type. */ public class ImageRecord extends ParsedNdefRecord { public static final String RECORD_TYPE = "ImageRecord"; private final Bitmap mBitmap; private ImageRecord(Bitmap bitmap) { mBitmap = Preconditions.checkNotNull(bitmap); } @Override public View getView(Activity activity, LayoutInflater inflater, ViewGroup parent, int offset) { ImageView image = (ImageView) inflater.inflate(R.layout.tag_image, parent, false); image.setImageBitmap(mBitmap); return image; } public static ImageRecord parse(NdefRecord record) { String mimeType = record.toMimeType(); + if (mimeType == null) { + throw new IllegalArgumentException("not a valid image file"); + } Preconditions.checkArgument(mimeType.startsWith("image/")); // Try to ensure it's a legal, valid image byte[] content = record.getPayload(); Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length); if (bitmap == null) { throw new IllegalArgumentException("not a valid image file"); } return new ImageRecord(bitmap); } public static boolean isImage(NdefRecord record) { try { parse(record); return true; } catch (IllegalArgumentException e) { return false; } } public static NdefRecord newImageRecord(Bitmap bitmap) { ByteArrayOutputStream out = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); byte[] content = out.toByteArray(); return NdefRecord.createMime("image/jpeg", content); } }
true
true
public static ImageRecord parse(NdefRecord record) { String mimeType = record.toMimeType(); Preconditions.checkArgument(mimeType.startsWith("image/")); // Try to ensure it's a legal, valid image byte[] content = record.getPayload(); Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length); if (bitmap == null) { throw new IllegalArgumentException("not a valid image file"); } return new ImageRecord(bitmap); }
public static ImageRecord parse(NdefRecord record) { String mimeType = record.toMimeType(); if (mimeType == null) { throw new IllegalArgumentException("not a valid image file"); } Preconditions.checkArgument(mimeType.startsWith("image/")); // Try to ensure it's a legal, valid image byte[] content = record.getPayload(); Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length); if (bitmap == null) { throw new IllegalArgumentException("not a valid image file"); } return new ImageRecord(bitmap); }
diff --git a/src/main/java/fr/cedrik/inotes/fs/BaseFsExport.java b/src/main/java/fr/cedrik/inotes/fs/BaseFsExport.java index fe629f4..e7d9c89 100644 --- a/src/main/java/fr/cedrik/inotes/fs/BaseFsExport.java +++ b/src/main/java/fr/cedrik/inotes/fs/BaseFsExport.java @@ -1,203 +1,203 @@ /** * */ package fr.cedrik.inotes.fs; import java.io.IOException; import java.io.Writer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.cedrik.inotes.BaseINotesMessage; import fr.cedrik.inotes.Folder; import fr.cedrik.inotes.FoldersList; import fr.cedrik.inotes.INotesMessagesMetaData; import fr.cedrik.inotes.INotesProperties; import fr.cedrik.inotes.Session; import fr.cedrik.inotes.util.DateUtils; /** * @author C&eacute;drik LIME */ public abstract class BaseFsExport implements fr.cedrik.inotes.MainRunner.Main { protected static final String ISO8601_DATE_SEMITIME = "yyyy-MM-dd'T'HH:mm";//$NON-NLS-1$ protected static final String PREF_LAST_EXPORT_DATE = "lastExportDate";//$NON-NLS-1$ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected INotesProperties iNotes; protected Session session; protected Date oldestMessageToFetch, newestMessageToFetch; public BaseFsExport() throws IOException { } protected void run(String[] args, String extension) throws IOException { if (args.length == 0) { help(); System.exit(-1); } if (! validateDestinationName(args[0], extension)) { return; } iNotes = new INotesProperties(INotesProperties.FILE); // login session = new Session(iNotes); if (! session.login(iNotes.getUserName(), iNotes.getUserPassword())) { logger.error("Can not login user {}!", iNotes.getUserName()); return; } try { // export folders hierarchy FoldersList folders = session.getFolders(); Folder folder = folders.getFolderById(iNotes.getNotesFolderId()); if (folder == null) { throw new IllegalArgumentException("Can not find folder \"" + iNotes.getNotesFolderId() + "\". Did you input the folder name instead of its id?"); } export(folder, args); } finally { session.logout(); } } protected abstract void help(); protected void export(Folder folder, String[] args) throws IOException { boolean deleteExportedMessages = false; session.setCurrentFolder(folder); this.oldestMessageToFetch = null; // reset if (args.length > 1) { try { this.oldestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[1]); } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[1], ISO8601_DATE_SEMITIME); } if (args.length > 2) { try { this.newestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[2]); - if (newestMessageToFetch.after(oldestMessageToFetch)) { + if (oldestMessageToFetch.after(newestMessageToFetch)) { logger.error("End date must be _after_ start date! Exiting…"); return; } } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[2], ISO8601_DATE_SEMITIME); } } if (args.length > 3) { if (this.newestMessageToFetch != null && "--delete".equals(args[3])) { logger.warn("Flagging exported messages for deletion"); deleteExportedMessages = true; } } } else if (shouldLoadOldestMessageToFetchFromPreferences()) { // set oldestMessageToFetch if file exists, and there is a Preference try { Preferences prefs = getUserNode(false); if (prefs != null) { long lastExportDate = prefs.getLong(PREF_LAST_EXPORT_DATE, -1); if (lastExportDate != -1) { this.oldestMessageToFetch = new Date(lastExportDate); this.newestMessageToFetch = null; } } } catch (BackingStoreException ignore) { logger.warn("Can not load last export date:", ignore); } } if (this.oldestMessageToFetch != null) { String msg = folder.name + ": incremental export from " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.oldestMessageToFetch); if (newestMessageToFetch != null) { msg += " to " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.newestMessageToFetch); } if (deleteExportedMessages) { msg += " with source deletion"; } logger.info(msg); } else { logger.info(folder.name + ": full export"); } // messages and meeting notices meta-data INotesMessagesMetaData<? extends BaseINotesMessage> messages = session.getMessagesAndMeetingNoticesMetaData(oldestMessageToFetch, newestMessageToFetch); if (folder.isInbox() || folder.isAllMails()) { checkQuota(messages); } if (! messages.entries.isEmpty()) { Date lastExportedMessageDate = this.export(messages, deleteExportedMessages); if (lastExportedMessageDate != null) { if (oldestMessageToFetch != null) { assert lastExportedMessageDate.after(oldestMessageToFetch); } if (newestMessageToFetch != null) { assert lastExportedMessageDate.before(newestMessageToFetch); } if (newestMessageToFetch == null) { // incremental export: set Preference to oldestMessageToFetch setPreferenceToOldestMessageToFetch(lastExportedMessageDate); } } } } /** * @return last exported message date (can be {@code null}) */ protected abstract Date export(INotesMessagesMetaData<? extends BaseINotesMessage> messages, boolean deleteExportedMessages) throws IOException; /** * Create Java objects and store them in fields. Does not physically create files. */ protected abstract boolean validateDestinationName(String baseName, String extension); /** * Usually, check if outFile exists */ protected abstract boolean shouldLoadOldestMessageToFetchFromPreferences(); protected abstract void writeMIME(Writer mbox, BaseINotesMessage message, Iterator<String> mime) throws IOException; protected void checkQuota(INotesMessagesMetaData<?> messages) { if (messages.ignorequota == 0 && messages.sizelimit > 0) { String quotaDetails = "dbsize: " + messages.dbsize + " currentusage: " + messages.currentusage + " warning: " + messages.warning + " sizelimit: " + messages.sizelimit + " ignorequota: " + messages.ignorequota; if (messages.dbsize >= messages.sizelimit || messages.currentusage >= messages.sizelimit) { logger.warn("WARNING WARNING: you have exceeded your quota! " + quotaDetails); } else if (messages.dbsize > messages.warning || messages.currentusage > messages.warning) { logger.info("WARNING: you are nearing your quota! " + quotaDetails); } } } protected void setPreferenceToOldestMessageToFetch(Date lastExportDate) { try { Preferences prefs = getUserNode(true); logger.debug("Recording last export date: {} for: {}", lastExportDate, prefs); prefs.putLong(PREF_LAST_EXPORT_DATE, lastExportDate.getTime()+1);// +1: don't re-export last exported message next time... prefs.flush(); } catch (BackingStoreException ignore) { logger.warn("Can not store last export date: " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(lastExportDate), ignore); } } protected Preferences getUserNode(boolean create) throws BackingStoreException { Preferences prefs = Preferences.userNodeForPackage(this.getClass()); String key = this.getClass().getSimpleName() + '/' + iNotes.getUserName().replace('/', '\\') + '@' + (iNotes.getServerAddress().replace('/', '\\')) + '/' + (iNotes.getNotesFolderId().replace('/', '\\')); if (create || prefs.nodeExists(key)) { return prefs.node(key); } else { return null; } } }
true
true
protected void export(Folder folder, String[] args) throws IOException { boolean deleteExportedMessages = false; session.setCurrentFolder(folder); this.oldestMessageToFetch = null; // reset if (args.length > 1) { try { this.oldestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[1]); } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[1], ISO8601_DATE_SEMITIME); } if (args.length > 2) { try { this.newestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[2]); if (newestMessageToFetch.after(oldestMessageToFetch)) { logger.error("End date must be _after_ start date! Exiting…"); return; } } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[2], ISO8601_DATE_SEMITIME); } } if (args.length > 3) { if (this.newestMessageToFetch != null && "--delete".equals(args[3])) { logger.warn("Flagging exported messages for deletion"); deleteExportedMessages = true; } } } else if (shouldLoadOldestMessageToFetchFromPreferences()) { // set oldestMessageToFetch if file exists, and there is a Preference try { Preferences prefs = getUserNode(false); if (prefs != null) { long lastExportDate = prefs.getLong(PREF_LAST_EXPORT_DATE, -1); if (lastExportDate != -1) { this.oldestMessageToFetch = new Date(lastExportDate); this.newestMessageToFetch = null; } } } catch (BackingStoreException ignore) { logger.warn("Can not load last export date:", ignore); } } if (this.oldestMessageToFetch != null) { String msg = folder.name + ": incremental export from " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.oldestMessageToFetch); if (newestMessageToFetch != null) { msg += " to " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.newestMessageToFetch); } if (deleteExportedMessages) { msg += " with source deletion"; } logger.info(msg); } else { logger.info(folder.name + ": full export"); } // messages and meeting notices meta-data INotesMessagesMetaData<? extends BaseINotesMessage> messages = session.getMessagesAndMeetingNoticesMetaData(oldestMessageToFetch, newestMessageToFetch); if (folder.isInbox() || folder.isAllMails()) { checkQuota(messages); } if (! messages.entries.isEmpty()) { Date lastExportedMessageDate = this.export(messages, deleteExportedMessages); if (lastExportedMessageDate != null) { if (oldestMessageToFetch != null) { assert lastExportedMessageDate.after(oldestMessageToFetch); } if (newestMessageToFetch != null) { assert lastExportedMessageDate.before(newestMessageToFetch); } if (newestMessageToFetch == null) { // incremental export: set Preference to oldestMessageToFetch setPreferenceToOldestMessageToFetch(lastExportedMessageDate); } } } }
protected void export(Folder folder, String[] args) throws IOException { boolean deleteExportedMessages = false; session.setCurrentFolder(folder); this.oldestMessageToFetch = null; // reset if (args.length > 1) { try { this.oldestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[1]); } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[1], ISO8601_DATE_SEMITIME); } if (args.length > 2) { try { this.newestMessageToFetch = new SimpleDateFormat(ISO8601_DATE_SEMITIME).parse(args[2]); if (oldestMessageToFetch.after(newestMessageToFetch)) { logger.error("End date must be _after_ start date! Exiting…"); return; } } catch (ParseException ignore) { logger.warn("Bad date format: {} Please use {}", args[2], ISO8601_DATE_SEMITIME); } } if (args.length > 3) { if (this.newestMessageToFetch != null && "--delete".equals(args[3])) { logger.warn("Flagging exported messages for deletion"); deleteExportedMessages = true; } } } else if (shouldLoadOldestMessageToFetchFromPreferences()) { // set oldestMessageToFetch if file exists, and there is a Preference try { Preferences prefs = getUserNode(false); if (prefs != null) { long lastExportDate = prefs.getLong(PREF_LAST_EXPORT_DATE, -1); if (lastExportDate != -1) { this.oldestMessageToFetch = new Date(lastExportDate); this.newestMessageToFetch = null; } } } catch (BackingStoreException ignore) { logger.warn("Can not load last export date:", ignore); } } if (this.oldestMessageToFetch != null) { String msg = folder.name + ": incremental export from " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.oldestMessageToFetch); if (newestMessageToFetch != null) { msg += " to " + DateUtils.ISO8601_DATE_TIME_FORMAT.format(this.newestMessageToFetch); } if (deleteExportedMessages) { msg += " with source deletion"; } logger.info(msg); } else { logger.info(folder.name + ": full export"); } // messages and meeting notices meta-data INotesMessagesMetaData<? extends BaseINotesMessage> messages = session.getMessagesAndMeetingNoticesMetaData(oldestMessageToFetch, newestMessageToFetch); if (folder.isInbox() || folder.isAllMails()) { checkQuota(messages); } if (! messages.entries.isEmpty()) { Date lastExportedMessageDate = this.export(messages, deleteExportedMessages); if (lastExportedMessageDate != null) { if (oldestMessageToFetch != null) { assert lastExportedMessageDate.after(oldestMessageToFetch); } if (newestMessageToFetch != null) { assert lastExportedMessageDate.before(newestMessageToFetch); } if (newestMessageToFetch == null) { // incremental export: set Preference to oldestMessageToFetch setPreferenceToOldestMessageToFetch(lastExportedMessageDate); } } } }
diff --git a/morphia/src/main/java/com/google/code/morphia/VersionHelper.java b/morphia/src/main/java/com/google/code/morphia/VersionHelper.java index 3dece79..e86c85e 100644 --- a/morphia/src/main/java/com/google/code/morphia/VersionHelper.java +++ b/morphia/src/main/java/com/google/code/morphia/VersionHelper.java @@ -1,20 +1,17 @@ /** * */ package com.google.code.morphia; /** * @author Uwe Schaefer, ([email protected]) * */ public class VersionHelper { public static long nextValue(Long oldVersion) { - long currentTimeMillis = System.currentTimeMillis(); - // very unlikely, but you never know - if (oldVersion != null && oldVersion.longValue() == currentTimeMillis) - currentTimeMillis++; - return currentTimeMillis; + long newVersion = oldVersion == null ? 1 : oldVersion + 1; + return newVersion; } }
true
true
public static long nextValue(Long oldVersion) { long currentTimeMillis = System.currentTimeMillis(); // very unlikely, but you never know if (oldVersion != null && oldVersion.longValue() == currentTimeMillis) currentTimeMillis++; return currentTimeMillis; }
public static long nextValue(Long oldVersion) { long newVersion = oldVersion == null ? 1 : oldVersion + 1; return newVersion; }
diff --git a/src/com/woopra/tracking/android/WoopraEvent.java b/src/com/woopra/tracking/android/WoopraEvent.java index aea90cb..d3c30a9 100755 --- a/src/com/woopra/tracking/android/WoopraEvent.java +++ b/src/com/woopra/tracking/android/WoopraEvent.java @@ -1,49 +1,49 @@ /* * Copyright 2014 Woopra, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.woopra.tracking.android; import java.util.HashMap; import java.util.Map; /** * @author Woopra on 1/26/2013 * */ public class WoopraEvent { private final Map<String,String> properties = new HashMap<String,String>(); public WoopraEvent(String eventName) { this(eventName, null); } public WoopraEvent(String eventName, Map<String,String> properties) { - if (this.properties != null) { + if (properties != null) { this.properties.putAll(properties); } this.properties.put("name", eventName); } public Map<String,String> getProperties() { return properties; } public void setEventProperty(Map<String,String> newProperties) { properties.putAll(newProperties); } public void setEventProperty(String key, String value) { properties.put(key, value); } }
true
true
public WoopraEvent(String eventName, Map<String,String> properties) { if (this.properties != null) { this.properties.putAll(properties); } this.properties.put("name", eventName); }
public WoopraEvent(String eventName, Map<String,String> properties) { if (properties != null) { this.properties.putAll(properties); } this.properties.put("name", eventName); }
diff --git a/fap/app/validation/NipCheck.java b/fap/app/validation/NipCheck.java index adbccade..065f1ba0 100644 --- a/fap/app/validation/NipCheck.java +++ b/fap/app/validation/NipCheck.java @@ -1,112 +1,112 @@ package validation; import java.util.regex.*; import models.Nip; import play.Logger; import play.data.validation.Check; public class NipCheck extends Check { private static final Pattern NIF_PATTERN = Pattern.compile("\\d{8}[A-Z]"); private static final Pattern NIE_PATTERN = Pattern.compile("[XYZ]\\d{7}[A-Z]"); private static final String NIF_NIE_ASOCIATION = "TRWAGMYFPDXBNJZSQVHLCKET"; @Override public boolean isSatisfied(Object validatedObject, Object value) { StringBuilder texto = new StringBuilder(); if(value instanceof Nip){ Nip nip = (Nip)value; boolean result = validaNip(nip, texto); setMessage(texto.toString()); return result; } //No es un nip, no lo valida return true; } public static boolean validaNip (Nip nip, StringBuilder texto) { - if(nip.tipo.isEmpty() && nip.valor.isEmpty()) //Tipo y valor vacios, no valida + if ((nip.tipo == null || nip.tipo.isEmpty()) && ((nip.valor == null) || (nip.valor.isEmpty()))) return true; if(nip.tipo.isEmpty()){ //Falta tipo texto.append("validation.nip.notipo"); return false; } if(nip.valor.isEmpty()){ //Falta valor texto.append("validation.nip.novalor"); return false; } if(nip.tipo.equals("nif")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIF_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nif.format"); return false; } //Comprueba la letra if(!checkNifNieLetter(nip.valor.toUpperCase())){ texto.append("validation.nip.nif.letter"); return false; } //Nif correcto return true; }else if(nip.tipo.equals("nie")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIE_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nie.format"); return false; } //Comprueba la letra char charInicial = ' '; char firstLetter = nip.valor.toUpperCase().charAt(0); if (firstLetter == 'X') charInicial = '0'; else if (firstLetter == 'Y') charInicial = '1'; else if (firstLetter == 'Z') charInicial = '2'; String numero = charInicial + nip.valor.substring(1, nip.valor.length()); if(!checkNifNieLetter(numero)){ texto.append("validation.nip.nie.letter"); return false; } //NIE Correcto return true; }else if(nip.tipo.equals("pasaporte")){ //El pasaporte no se comprueba }else{ texto.append("validation.nip.tipo"); return false; } return true; } private static boolean checkNifNieLetter(String numero){ int digitosNif = Integer.parseInt(numero.substring(0,8)); int letraEsperada = NIF_NIE_ASOCIATION.charAt(digitosNif % 23); int letraActual = numero.charAt(8); return (letraEsperada == letraActual); } }
true
true
public static boolean validaNip (Nip nip, StringBuilder texto) { if(nip.tipo.isEmpty() && nip.valor.isEmpty()) //Tipo y valor vacios, no valida return true; if(nip.tipo.isEmpty()){ //Falta tipo texto.append("validation.nip.notipo"); return false; } if(nip.valor.isEmpty()){ //Falta valor texto.append("validation.nip.novalor"); return false; } if(nip.tipo.equals("nif")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIF_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nif.format"); return false; } //Comprueba la letra if(!checkNifNieLetter(nip.valor.toUpperCase())){ texto.append("validation.nip.nif.letter"); return false; } //Nif correcto return true; }else if(nip.tipo.equals("nie")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIE_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nie.format"); return false; } //Comprueba la letra char charInicial = ' '; char firstLetter = nip.valor.toUpperCase().charAt(0); if (firstLetter == 'X') charInicial = '0'; else if (firstLetter == 'Y') charInicial = '1'; else if (firstLetter == 'Z') charInicial = '2'; String numero = charInicial + nip.valor.substring(1, nip.valor.length()); if(!checkNifNieLetter(numero)){ texto.append("validation.nip.nie.letter"); return false; } //NIE Correcto return true; }else if(nip.tipo.equals("pasaporte")){ //El pasaporte no se comprueba }else{ texto.append("validation.nip.tipo"); return false; } return true; }
public static boolean validaNip (Nip nip, StringBuilder texto) { if ((nip.tipo == null || nip.tipo.isEmpty()) && ((nip.valor == null) || (nip.valor.isEmpty()))) return true; if(nip.tipo.isEmpty()){ //Falta tipo texto.append("validation.nip.notipo"); return false; } if(nip.valor.isEmpty()){ //Falta valor texto.append("validation.nip.novalor"); return false; } if(nip.tipo.equals("nif")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIF_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nif.format"); return false; } //Comprueba la letra if(!checkNifNieLetter(nip.valor.toUpperCase())){ texto.append("validation.nip.nif.letter"); return false; } //Nif correcto return true; }else if(nip.tipo.equals("nie")){ // Comprueba la longitud if (nip.valor.trim().length() != 9) { texto.append("validation.nip.nif.format"); return false; } //Comprueba el formato Matcher matcher = NIE_PATTERN.matcher(nip.valor.toUpperCase()); if(!matcher.find()){ texto.append("validation.nip.nie.format"); return false; } //Comprueba la letra char charInicial = ' '; char firstLetter = nip.valor.toUpperCase().charAt(0); if (firstLetter == 'X') charInicial = '0'; else if (firstLetter == 'Y') charInicial = '1'; else if (firstLetter == 'Z') charInicial = '2'; String numero = charInicial + nip.valor.substring(1, nip.valor.length()); if(!checkNifNieLetter(numero)){ texto.append("validation.nip.nie.letter"); return false; } //NIE Correcto return true; }else if(nip.tipo.equals("pasaporte")){ //El pasaporte no se comprueba }else{ texto.append("validation.nip.tipo"); return false; } return true; }
diff --git a/EchoLocation/src/com/amateurbikenerd/echoLocation/math/GenerateCodeThatIsTooBig.java b/EchoLocation/src/com/amateurbikenerd/echoLocation/math/GenerateCodeThatIsTooBig.java index fa83dc3..876097d 100644 --- a/EchoLocation/src/com/amateurbikenerd/echoLocation/math/GenerateCodeThatIsTooBig.java +++ b/EchoLocation/src/com/amateurbikenerd/echoLocation/math/GenerateCodeThatIsTooBig.java @@ -1,243 +1,246 @@ package com.amateurbikenerd.echoLocation.math; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.List; public class GenerateCodeThatIsTooBig { private Hashtable<Integer, Hashtable<Integer, List<Short>>> leftImpulses; private Hashtable<Integer, Hashtable<Integer, List<Short>>> rightImpulses; public static void main(String[] args)throws Exception{ //GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/darshan/src/echolocation/mit_full"); GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/dmiles/mit_full"); Hashtable<String, short[][]> ht = new Hashtable<String, short[][]>(); for(int azimuth : data.getAzimuths()){ for(int elevation : data.getElevations()){ - String compositeKey = azimuth + ":" + elevation; + String compositeKey = azimuth + "_" + elevation; //System.out.println(compositeKey); List<Short> listLeft = data.getImpulse('L', elevation, azimuth); if(listLeft == null) continue; short[] left = new short[listLeft.size()]; for(int i = 0; i < listLeft.size(); i++) left[i] = listLeft.get(i).shortValue(); List<Short> listRight = data.getImpulse('R', elevation, azimuth); short[] right = new short[listRight.size()]; for(int i = 0; i < listRight.size(); i++) right[i] = listRight.get(i).shortValue(); short[][] toStore = new short[][]{right, left}; ht.put(compositeKey, toStore); } } System.out.println("package com.amateurbikenerd.echoLocation.math;\n"); System.out.println("import java.util.Collections;"); System.out.println("import java.util.ArrayList;"); System.out.println("import java.util.Hashtable;"); System.out.println("public class MITData{"); System.out.println(" private static Hashtable<Integer, ArrayList<Integer>> azimuths;\n private static ArrayList<Integer> elevations;"); System.out.println(" static{"); System.out.print(" elevations = new ArrayList<Integer>(){{"); List<Integer> elevations = new ArrayList<Integer>(new HashSet<Integer>(data.getElevations())); Collections.sort(elevations); for(int elevation : elevations) System.out.print("add(" + elevation + ");"); System.out.println("}};"); System.out.print(" azimuths = new Hashtable<Integer, ArrayList<Integer>>(){{"); for(int elevation : data.getElevations()){ System.out.print("put(" + elevation + ",new ArrayList<Integer>(){{"); List<Integer> azimuths = data.getAzimuths(); Collections.sort(azimuths); for(int azimuth : azimuths){ List<Short> impulse = data.getImpulse('L', elevation, azimuth); if(impulse != null){ System.out.print("add(" + azimuth + ");"); } } System.out.print("}});"); } System.out.println("}};"); System.out.println(" }"); for(String compositeKey : ht.keySet()){ short[] left = ht.get(compositeKey)[1]; short[] right = ht.get(compositeKey)[0]; - System.out.print(" ht.put(\"" + compositeKey + "\", new short[][]{{"); + String funcName = "f" + compositeKey; + System.out.println(" public static short[][] " + funcName + "(){"); + System.out.print(" return new short[][]{{"); for(int i = 0; i < right.length; i++){ System.out.print(right[i]); if(i != right.length - 1) System.out.print(", "); } System.out.print("},{"); for(int i = 0; i < left.length; i++){ System.out.print(left[i]); if(i != left.length - 1) System.out.print(", "); } - System.out.println("}});"); + System.out.println("}};"); + System.out.println(" }"); } System.out.println(" public static short[][] get(int azimuth, int elevation){"); System.out.println(" if(! elevations.contains(elevation)){"); System.out.println(" int idx = (Collections.binarySearch(elevations, elevation) + 1) * -1;"); System.out.println(" if(idx == elevations.size())"); System.out.println(" idx--;"); System.out.println(" elevation = elevations.get(idx);"); System.out.println(" }"); System.out.println(" ArrayList<Integer> azimuthListForElevation = azimuths.get(elevation);"); System.out.println(" if (! azimuthListForElevation.contains(azimuth)){"); System.out.println(" int idx = (Collections.binarySearch(azimuthListForElevation, azimuth) + 1) * -1;"); System.out.println(" if(idx == azimuthListForElevation.size())"); System.out.println(" idx--;"); System.out.println(" azimuth = azimuthListForElevation.get(idx);"); System.out.println(" };"); System.out.println(" String mName = \"f\" + azimuth + \"_\" + elevation;"); System.out.println(" try {"); System.out.println(" java.lang.reflect.Method m = MITData.class.getMethod(mName, new Class[] {});"); System.out.println(" return (short[][]) m.invoke(MITData.class, new Object[] {});"); System.out.println(" } catch (Exception e) {return null;}"); System.out.println(" }"); System.out.println(" public static void main(String[] args){"); System.out.println(" short a = MITData.f220_10()[0][0] ;"); System.out.println(" System.out.println(\"Hello World!\");"); System.out.println(" System.out.println(\"MITData.f220_10()[0][0] = \" + a);"); System.out.println(" } // close main"); System.out.println("} //close class"); } public GenerateCodeThatIsTooBig(String directoryName) throws IllegalArgumentException, IllegalAccessException{ leftImpulses = new Hashtable<Integer, Hashtable<Integer, List<Short>>>(); rightImpulses = new Hashtable<Integer, Hashtable<Integer, List<Short>>>(); File mitDataDirectory = new File(directoryName); String[] elevationFolders = mitDataDirectory.list(); for(int i = 0; i < elevationFolders.length; i++){ String elevationFolderName = elevationFolders[i]; if(! (elevationFolderName.length() > 4 && elevationFolderName.substring(0, 4).toLowerCase().equals("elev"))) continue; // count backwards from the end of the file name until the character is // not a digit. Use that index to get the elevation number. int elevIdx = elevationFolderName.length() - 1; while(Character.isDigit(elevationFolderName.charAt(elevIdx))) elevIdx--; elevIdx++; int elevation = Integer.parseInt(elevationFolderName.subSequence(elevIdx, elevationFolderName.length()).toString()); File elevationFolder = new File(directoryName + "/" + elevationFolderName); String[] datFiles = elevationFolder.list(); for(int j = 0; j < datFiles.length; j++){ String datFileName = datFiles[j]; if(datFileName.length() > 0 && (datFileName.charAt(0) == 'L' || datFileName.charAt(0) == 'R')){ // Here, we're going to use a char for L or R (left or right) // and gather integers for elevation and azimuth int indexOfLetterE = datFileName.indexOf('e'); int indexOfLetterA = datFileName.indexOf('a'); int felevation = Integer.parseInt(datFileName.substring(1, indexOfLetterE)); assert(felevation == elevation); int azimuth = Integer.parseInt(datFileName.substring(indexOfLetterE + 1, indexOfLetterA)); List<Short> impulse = readImpulse(directoryName + "/" + elevationFolderName + "/" + datFileName); Integer elevationKey = new Integer(elevation); Hashtable<Integer, Hashtable<Integer, List<Short>>> impulses = leftImpulses; if(datFileName.toUpperCase().charAt(0) == 'R') impulses = rightImpulses; if(! impulses.containsKey(elevationKey)) impulses.put(elevationKey, new Hashtable<Integer, List<Short>>()); Integer azimuthKey = new Integer(azimuth); if(! impulses.get(elevationKey).containsKey(azimuthKey)) impulses.get(elevationKey).put(azimuthKey, impulse); } } } } public void serialize()throws Exception{ ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("/home/dmiles/two_channel_mit_data_serialized_file")); out.writeObject(this); } public static GenerateCodeThatIsTooBig deserialize(InputStream location){ try{ ObjectInputStream in = new ObjectInputStream(location); return (GenerateCodeThatIsTooBig)in.readObject(); }catch(IOException e){ e.printStackTrace(); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } public List<Integer> getElevations(){ // BOZO: this assumes left and right impulses all have the same elevations List<Integer> l = new ArrayList<Integer>(leftImpulses.size()); for(Integer i : leftImpulses.keySet()) l.add(i); return l; } public List<Integer> getAzimuths(){ // BOZO: this assumes left and right impulses all have the same azimuths List<Integer> l = new ArrayList<Integer>(); for(Integer elevation : leftImpulses.keySet()){ for(Integer azimuth : leftImpulses.get(elevation).keySet()){ l.add(azimuth); } } return l; } public List<Short> getImpulse(char channel, int elevation, int azimuth){ Hashtable<Integer, Hashtable<Integer, List<Short>>> impulses = leftImpulses; if(channel == 'R') impulses = rightImpulses; if(azimuth == 360) azimuth = 0; Integer elevationKey = new Integer(elevation); Integer azimuthKey = new Integer(azimuth); if(! impulses.containsKey(elevationKey)) return null; if(! impulses.get(elevationKey).containsKey(azimuthKey)) return null; return impulses.get(elevationKey).get(azimuthKey); } private static List<Short> readImpulse(String filename){ File file = new File(filename); int fileLength = (int) file.length(); if (fileLength % 2 != 0) { System.err .println("Error, file does not contain an even number of bytes. Invalid format"); System.exit(1); } InputStream is = null; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte[] bytes = new byte[fileLength]; int read = 0; try { read = is.read(bytes, 0, fileLength); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (read != fileLength) { System.err.println("Error, did not read whole file"); System.exit(1); } ByteBuffer byteBuf = ByteBuffer.wrap(bytes); List<Short> values = new ArrayList<Short>(); for(int bytesIdx = 0; bytesIdx < fileLength; bytesIdx += 2){ values.add(byteBuf.getShort(bytesIdx)); } return values; } }
false
true
public static void main(String[] args)throws Exception{ //GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/darshan/src/echolocation/mit_full"); GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/dmiles/mit_full"); Hashtable<String, short[][]> ht = new Hashtable<String, short[][]>(); for(int azimuth : data.getAzimuths()){ for(int elevation : data.getElevations()){ String compositeKey = azimuth + ":" + elevation; //System.out.println(compositeKey); List<Short> listLeft = data.getImpulse('L', elevation, azimuth); if(listLeft == null) continue; short[] left = new short[listLeft.size()]; for(int i = 0; i < listLeft.size(); i++) left[i] = listLeft.get(i).shortValue(); List<Short> listRight = data.getImpulse('R', elevation, azimuth); short[] right = new short[listRight.size()]; for(int i = 0; i < listRight.size(); i++) right[i] = listRight.get(i).shortValue(); short[][] toStore = new short[][]{right, left}; ht.put(compositeKey, toStore); } } System.out.println("package com.amateurbikenerd.echoLocation.math;\n"); System.out.println("import java.util.Collections;"); System.out.println("import java.util.ArrayList;"); System.out.println("import java.util.Hashtable;"); System.out.println("public class MITData{"); System.out.println(" private static Hashtable<Integer, ArrayList<Integer>> azimuths;\n private static ArrayList<Integer> elevations;"); System.out.println(" static{"); System.out.print(" elevations = new ArrayList<Integer>(){{"); List<Integer> elevations = new ArrayList<Integer>(new HashSet<Integer>(data.getElevations())); Collections.sort(elevations); for(int elevation : elevations) System.out.print("add(" + elevation + ");"); System.out.println("}};"); System.out.print(" azimuths = new Hashtable<Integer, ArrayList<Integer>>(){{"); for(int elevation : data.getElevations()){ System.out.print("put(" + elevation + ",new ArrayList<Integer>(){{"); List<Integer> azimuths = data.getAzimuths(); Collections.sort(azimuths); for(int azimuth : azimuths){ List<Short> impulse = data.getImpulse('L', elevation, azimuth); if(impulse != null){ System.out.print("add(" + azimuth + ");"); } } System.out.print("}});"); } System.out.println("}};"); System.out.println(" }"); for(String compositeKey : ht.keySet()){ short[] left = ht.get(compositeKey)[1]; short[] right = ht.get(compositeKey)[0]; System.out.print(" ht.put(\"" + compositeKey + "\", new short[][]{{"); for(int i = 0; i < right.length; i++){ System.out.print(right[i]); if(i != right.length - 1) System.out.print(", "); } System.out.print("},{"); for(int i = 0; i < left.length; i++){ System.out.print(left[i]); if(i != left.length - 1) System.out.print(", "); } System.out.println("}});"); } System.out.println(" public static short[][] get(int azimuth, int elevation){"); System.out.println(" if(! elevations.contains(elevation)){"); System.out.println(" int idx = (Collections.binarySearch(elevations, elevation) + 1) * -1;"); System.out.println(" if(idx == elevations.size())"); System.out.println(" idx--;"); System.out.println(" elevation = elevations.get(idx);"); System.out.println(" }"); System.out.println(" ArrayList<Integer> azimuthListForElevation = azimuths.get(elevation);"); System.out.println(" if (! azimuthListForElevation.contains(azimuth)){"); System.out.println(" int idx = (Collections.binarySearch(azimuthListForElevation, azimuth) + 1) * -1;"); System.out.println(" if(idx == azimuthListForElevation.size())"); System.out.println(" idx--;"); System.out.println(" azimuth = azimuthListForElevation.get(idx);"); System.out.println(" };"); System.out.println(" String mName = \"f\" + azimuth + \"_\" + elevation;"); System.out.println(" try {"); System.out.println(" java.lang.reflect.Method m = MITData.class.getMethod(mName, new Class[] {});"); System.out.println(" return (short[][]) m.invoke(MITData.class, new Object[] {});"); System.out.println(" } catch (Exception e) {return null;}"); System.out.println(" }"); System.out.println(" public static void main(String[] args){"); System.out.println(" short a = MITData.f220_10()[0][0] ;"); System.out.println(" System.out.println(\"Hello World!\");"); System.out.println(" System.out.println(\"MITData.f220_10()[0][0] = \" + a);"); System.out.println(" } // close main"); System.out.println("} //close class"); }
public static void main(String[] args)throws Exception{ //GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/darshan/src/echolocation/mit_full"); GenerateCodeThatIsTooBig data = new GenerateCodeThatIsTooBig("/home/dmiles/mit_full"); Hashtable<String, short[][]> ht = new Hashtable<String, short[][]>(); for(int azimuth : data.getAzimuths()){ for(int elevation : data.getElevations()){ String compositeKey = azimuth + "_" + elevation; //System.out.println(compositeKey); List<Short> listLeft = data.getImpulse('L', elevation, azimuth); if(listLeft == null) continue; short[] left = new short[listLeft.size()]; for(int i = 0; i < listLeft.size(); i++) left[i] = listLeft.get(i).shortValue(); List<Short> listRight = data.getImpulse('R', elevation, azimuth); short[] right = new short[listRight.size()]; for(int i = 0; i < listRight.size(); i++) right[i] = listRight.get(i).shortValue(); short[][] toStore = new short[][]{right, left}; ht.put(compositeKey, toStore); } } System.out.println("package com.amateurbikenerd.echoLocation.math;\n"); System.out.println("import java.util.Collections;"); System.out.println("import java.util.ArrayList;"); System.out.println("import java.util.Hashtable;"); System.out.println("public class MITData{"); System.out.println(" private static Hashtable<Integer, ArrayList<Integer>> azimuths;\n private static ArrayList<Integer> elevations;"); System.out.println(" static{"); System.out.print(" elevations = new ArrayList<Integer>(){{"); List<Integer> elevations = new ArrayList<Integer>(new HashSet<Integer>(data.getElevations())); Collections.sort(elevations); for(int elevation : elevations) System.out.print("add(" + elevation + ");"); System.out.println("}};"); System.out.print(" azimuths = new Hashtable<Integer, ArrayList<Integer>>(){{"); for(int elevation : data.getElevations()){ System.out.print("put(" + elevation + ",new ArrayList<Integer>(){{"); List<Integer> azimuths = data.getAzimuths(); Collections.sort(azimuths); for(int azimuth : azimuths){ List<Short> impulse = data.getImpulse('L', elevation, azimuth); if(impulse != null){ System.out.print("add(" + azimuth + ");"); } } System.out.print("}});"); } System.out.println("}};"); System.out.println(" }"); for(String compositeKey : ht.keySet()){ short[] left = ht.get(compositeKey)[1]; short[] right = ht.get(compositeKey)[0]; String funcName = "f" + compositeKey; System.out.println(" public static short[][] " + funcName + "(){"); System.out.print(" return new short[][]{{"); for(int i = 0; i < right.length; i++){ System.out.print(right[i]); if(i != right.length - 1) System.out.print(", "); } System.out.print("},{"); for(int i = 0; i < left.length; i++){ System.out.print(left[i]); if(i != left.length - 1) System.out.print(", "); } System.out.println("}};"); System.out.println(" }"); } System.out.println(" public static short[][] get(int azimuth, int elevation){"); System.out.println(" if(! elevations.contains(elevation)){"); System.out.println(" int idx = (Collections.binarySearch(elevations, elevation) + 1) * -1;"); System.out.println(" if(idx == elevations.size())"); System.out.println(" idx--;"); System.out.println(" elevation = elevations.get(idx);"); System.out.println(" }"); System.out.println(" ArrayList<Integer> azimuthListForElevation = azimuths.get(elevation);"); System.out.println(" if (! azimuthListForElevation.contains(azimuth)){"); System.out.println(" int idx = (Collections.binarySearch(azimuthListForElevation, azimuth) + 1) * -1;"); System.out.println(" if(idx == azimuthListForElevation.size())"); System.out.println(" idx--;"); System.out.println(" azimuth = azimuthListForElevation.get(idx);"); System.out.println(" };"); System.out.println(" String mName = \"f\" + azimuth + \"_\" + elevation;"); System.out.println(" try {"); System.out.println(" java.lang.reflect.Method m = MITData.class.getMethod(mName, new Class[] {});"); System.out.println(" return (short[][]) m.invoke(MITData.class, new Object[] {});"); System.out.println(" } catch (Exception e) {return null;}"); System.out.println(" }"); System.out.println(" public static void main(String[] args){"); System.out.println(" short a = MITData.f220_10()[0][0] ;"); System.out.println(" System.out.println(\"Hello World!\");"); System.out.println(" System.out.println(\"MITData.f220_10()[0][0] = \" + a);"); System.out.println(" } // close main"); System.out.println("} //close class"); }
diff --git a/src/main/java/freenet/winterface/web/markup/NavPanel.java b/src/main/java/freenet/winterface/web/markup/NavPanel.java index 6d5a870..39be6db 100644 --- a/src/main/java/freenet/winterface/web/markup/NavPanel.java +++ b/src/main/java/freenet/winterface/web/markup/NavPanel.java @@ -1,129 +1,130 @@ package freenet.winterface.web.markup; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import freenet.winterface.web.nav.NavItem; import freenet.winterface.web.nav.PageNavItem; /** * {@link Panel} that renders the navigation menu. * <p> * The navigation menu is built in a hierarchical manner, so that each submenu * itself is an instance of {@link NavPanel} * </p> * * @author pausb * @see NavCallbackInterface * @see PageNavItem */ @SuppressWarnings("serial") public final class NavPanel extends Panel { /** * Denotes the depth level */ private int level; /** * Constructs. * * @param id * wicket:id of desired {@link Component} * @param itemModel * {@link IModel} used to generate navigation content */ public NavPanel(String id, IModel<NavItem> itemModel) { this(id, itemModel, 0); } /** * Constructs * * @param id * wicket:id of desired {@link Component} * @param itemModel * {@link IModel} used to generate navigation content * @param level * depth level */ public NavPanel(String id, IModel<NavItem> itemModel, int level) { super(id,itemModel); this.level = level; } @Override protected void onInitialize() { + super.onInitialize(); @SuppressWarnings("unchecked") final IModel<NavItem> itemModel = (IModel<NavItem>) getDefaultModel(); // Use field called "name" to get name of menu // TODO support i18n final IModel<String> nameModel = new PropertyModel<String>(itemModel, "Name"); // Model to add "active" class to menu if currently in respective page LoadableDetachableModel<String> classModel = new LoadableDetachableModel<String>() { @Override protected String load() { return itemModel.getObject().isActive(getPage()) ? "active" : null; } @Override protected void onDetach() { super.onDetach(); itemModel.detach(); } }; // Menu link to page Link<NavItem> link = new Link<NavItem>("nav-link", itemModel) { @Override public void onClick() { itemModel.getObject().onClick(getPage()); } @Override protected void onBeforeRender() { super.onBeforeRender(); boolean visible = (nameModel.getObject() == null) ? false : true; setVisible(visible); } }; // Adding link link.add(new Label("nav-name", nameModel)); link.add(new AttributeAppender("class", classModel)); link.add(new AttributeAppender("class", Model.of(" level-" + this.level))); add(link); // Model used to generate children (if any) LoadableDetachableModel<List<NavItem>> childModel = new LoadableDetachableModel<List<NavItem>>() { @Override protected List<NavItem> load() { return itemModel.getObject().getChilds(getPage()); } }; // Add Children ListView<NavItem> childList = new ListView<NavItem>("nav-children", childModel) { @Override protected void populateItem(ListItem<NavItem> item) { item.add(new NavPanel("nav-child", item.getModel(), level + 1)); } }; add(childList); } }
true
true
protected void onInitialize() { @SuppressWarnings("unchecked") final IModel<NavItem> itemModel = (IModel<NavItem>) getDefaultModel(); // Use field called "name" to get name of menu // TODO support i18n final IModel<String> nameModel = new PropertyModel<String>(itemModel, "Name"); // Model to add "active" class to menu if currently in respective page LoadableDetachableModel<String> classModel = new LoadableDetachableModel<String>() { @Override protected String load() { return itemModel.getObject().isActive(getPage()) ? "active" : null; } @Override protected void onDetach() { super.onDetach(); itemModel.detach(); } }; // Menu link to page Link<NavItem> link = new Link<NavItem>("nav-link", itemModel) { @Override public void onClick() { itemModel.getObject().onClick(getPage()); } @Override protected void onBeforeRender() { super.onBeforeRender(); boolean visible = (nameModel.getObject() == null) ? false : true; setVisible(visible); } }; // Adding link link.add(new Label("nav-name", nameModel)); link.add(new AttributeAppender("class", classModel)); link.add(new AttributeAppender("class", Model.of(" level-" + this.level))); add(link); // Model used to generate children (if any) LoadableDetachableModel<List<NavItem>> childModel = new LoadableDetachableModel<List<NavItem>>() { @Override protected List<NavItem> load() { return itemModel.getObject().getChilds(getPage()); } }; // Add Children ListView<NavItem> childList = new ListView<NavItem>("nav-children", childModel) { @Override protected void populateItem(ListItem<NavItem> item) { item.add(new NavPanel("nav-child", item.getModel(), level + 1)); } }; add(childList); }
protected void onInitialize() { super.onInitialize(); @SuppressWarnings("unchecked") final IModel<NavItem> itemModel = (IModel<NavItem>) getDefaultModel(); // Use field called "name" to get name of menu // TODO support i18n final IModel<String> nameModel = new PropertyModel<String>(itemModel, "Name"); // Model to add "active" class to menu if currently in respective page LoadableDetachableModel<String> classModel = new LoadableDetachableModel<String>() { @Override protected String load() { return itemModel.getObject().isActive(getPage()) ? "active" : null; } @Override protected void onDetach() { super.onDetach(); itemModel.detach(); } }; // Menu link to page Link<NavItem> link = new Link<NavItem>("nav-link", itemModel) { @Override public void onClick() { itemModel.getObject().onClick(getPage()); } @Override protected void onBeforeRender() { super.onBeforeRender(); boolean visible = (nameModel.getObject() == null) ? false : true; setVisible(visible); } }; // Adding link link.add(new Label("nav-name", nameModel)); link.add(new AttributeAppender("class", classModel)); link.add(new AttributeAppender("class", Model.of(" level-" + this.level))); add(link); // Model used to generate children (if any) LoadableDetachableModel<List<NavItem>> childModel = new LoadableDetachableModel<List<NavItem>>() { @Override protected List<NavItem> load() { return itemModel.getObject().getChilds(getPage()); } }; // Add Children ListView<NavItem> childList = new ListView<NavItem>("nav-children", childModel) { @Override protected void populateItem(ListItem<NavItem> item) { item.add(new NavPanel("nav-child", item.getModel(), level + 1)); } }; add(childList); }
diff --git a/main/src/cgeo/geocaching/Geocache.java b/main/src/cgeo/geocaching/Geocache.java index 836cccbe0..7057ab327 100644 --- a/main/src/cgeo/geocaching/Geocache.java +++ b/main/src/cgeo/geocaching/Geocache.java @@ -1,1727 +1,1731 @@ package cgeo.geocaching; import cgeo.geocaching.cgData.StorageLocation; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.IAbstractActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.capability.ISearchByCenter; import cgeo.geocaching.connector.capability.ISearchByGeocode; import cgeo.geocaching.connector.gc.GCConnector; import cgeo.geocaching.connector.gc.GCConstants; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.enumerations.CacheAttribute; import cgeo.geocaching.enumerations.CacheRealm; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.LoadFlag; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.GPXParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.LazyInitializedList; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.LogTemplateProvider; import cgeo.geocaching.utils.LogTemplateProvider.LogContext; import cgeo.geocaching.utils.MatcherWrapper; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.text.Html; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Internal c:geo representation of a "cache" */ public class Geocache implements ICache, IWaypoint { private long updated = 0; private long detailedUpdate = 0; private long visitedDate = 0; private int listId = StoredList.TEMPORARY_LIST_ID; private boolean detailed = false; private String geocode = ""; private String cacheId = ""; private String guid = ""; private CacheType cacheType = CacheType.UNKNOWN; private String name = ""; private String ownerDisplayName = ""; private String ownerUserId = ""; private Date hidden = null; /** * lazy initialized */ private String hint = null; private CacheSize size = CacheSize.UNKNOWN; private float difficulty = 0; private float terrain = 0; private Float direction = null; private Float distance = null; /** * lazy initialized */ private String location = null; private Geopoint coords = null; private boolean reliableLatLon = false; private Double elevation = null; private String personalNote = null; /** * lazy initialized */ private String shortdesc = null; /** * lazy initialized */ private String description = null; private boolean disabled = false; private boolean archived = false; private boolean premiumMembersOnly = false; private boolean found = false; private boolean favorite = false; private int favoritePoints = 0; private float rating = 0; // valid ratings are larger than zero private int votes = 0; private float myVote = 0; // valid ratings are larger than zero private int inventoryItems = 0; private boolean onWatchlist = false; private List<String> attributes = new LazyInitializedList<String>() { @Override public List<String> call() { return cgData.loadAttributes(geocode); } }; private List<Waypoint> waypoints = new LazyInitializedList<Waypoint>() { @Override public List<Waypoint> call() { return cgData.loadWaypoints(geocode); } }; private List<Image> spoilers = null; private List<LogEntry> logs = new LazyInitializedList<LogEntry>() { @Override public List<LogEntry> call() { return cgData.loadLogs(geocode); } }; private List<Trackable> inventory = null; private Map<LogType, Integer> logCounts = new HashMap<LogType, Integer>(); private boolean logOffline = false; private boolean userModifiedCoords = false; // temporary values private boolean statusChecked = false; private String directionImg = ""; private String nameForSorting; private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP); private boolean finalDefined = false; private int zoomlevel = Tile.ZOOMLEVEL_MAX + 1; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+"); private Handler changeNotificationHandler = null; /** * Create a new cache. To be used everywhere except for the GPX parser */ public Geocache() { // empty } /** * Cache constructor to be used by the GPX parser only. This constructor explicitly sets several members to empty * lists. * * @param gpxParser */ public Geocache(GPXParser gpxParser) { setReliableLatLon(true); setAttributes(Collections.<String> emptyList()); setWaypoints(Collections.<Waypoint> emptyList(), false); setLogs(Collections.<LogEntry> emptyList()); } public void setChangeNotificationHandler(Handler newNotificationHandler) { changeNotificationHandler = newNotificationHandler; } /** * Sends a change notification to interested parties */ private void notifyChange() { if (changeNotificationHandler != null) { changeNotificationHandler.sendEmptyMessage(0); } } /** * Gather missing information from another cache object. * * @param other * the other version, or null if non-existent * @return true if this cache is "equal" to the other version */ public boolean gatherMissingFrom(final Geocache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) { detailed = other.detailed; detailedUpdate = other.detailedUpdate; coords = other.coords; cacheType = other.cacheType; zoomlevel = other.zoomlevel; // boolean values must be enumerated here. Other types are assigned outside this if-statement + // TODO: check whether a search or a live map systematically returns those, in which case + // we want to keep the most recent one instead of getting information from the previously + // stored data. This is the case for "archived" for example which has been taken out of this + // list. premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; - archived = other.archived; found = other.found; disabled = other.disabled; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; + // archived is kept from the most recent data } /* * No gathering for boolean members if other cache is not-detailed * and does not have information with higher reliability (denoted by zoomlevel) * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.visitedDate; } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.geocode; } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.guid; } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.cacheType; } if (StringUtils.isBlank(name)) { name = other.name; } if (StringUtils.isBlank(ownerDisplayName)) { ownerDisplayName = other.ownerDisplayName; } if (StringUtils.isBlank(ownerUserId)) { ownerUserId = other.ownerUserId; } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(getHint())) { hint = other.getHint(); } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.difficulty; } if (terrain == 0) { terrain = other.terrain; } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.distance; } if (StringUtils.isBlank(getLocation())) { location = other.getLocation(); } if (coords == null) { coords = other.coords; } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(getShortDescription())) { shortdesc = other.getShortDescription(); } if (StringUtils.isBlank(getDescription())) { description = other.getDescription(); } // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too. if (favoritePoints == 0) { favoritePoints = other.favoritePoints; } if (rating == 0) { rating = other.rating; } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.myVote; } if (attributes.isEmpty()) { attributes.clear(); if (other.attributes != null) { attributes.addAll(other.attributes); } } if (waypoints.isEmpty()) { this.setWaypoints(other.waypoints, false); } else { ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>(waypoints); Waypoint.mergeWayPoints(newPoints, other.waypoints, false); this.setWaypoints(newPoints, false); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (logs.isEmpty()) { // keep last known logs if none logs.clear(); if (other.logs != null) { logs.addAll(other.logs); } } if (logCounts.isEmpty()) { logCounts = other.logCounts; } // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not userModifiedCoords = false; if (waypoints != null) { for (Waypoint wpt : waypoints) { if (wpt.getWaypointType() == WaypointType.ORIGINAL) { userModifiedCoords = true; break; } } } if (!reliableLatLon) { reliableLatLon = other.reliableLatLon; } if (zoomlevel == -1) { zoomlevel = other.zoomlevel; } return isEqualTo(other); } /** * Compare two caches quickly. For map and list fields only the references are compared ! * * @param other * the other cache to compare this one to * @return true if both caches have the same content */ private boolean isEqualTo(final Geocache other) { return detailed == other.detailed && StringUtils.equalsIgnoreCase(geocode, other.geocode) && StringUtils.equalsIgnoreCase(name, other.name) && cacheType == other.cacheType && size == other.size && found == other.found && premiumMembersOnly == other.premiumMembersOnly && difficulty == other.difficulty && terrain == other.terrain && (coords != null ? coords.equals(other.coords) : null == other.coords) && reliableLatLon == other.reliableLatLon && disabled == other.disabled && archived == other.archived && listId == other.listId && StringUtils.equalsIgnoreCase(ownerDisplayName, other.ownerDisplayName) && StringUtils.equalsIgnoreCase(ownerUserId, other.ownerUserId) && StringUtils.equalsIgnoreCase(getDescription(), other.getDescription()) && StringUtils.equalsIgnoreCase(personalNote, other.personalNote) && StringUtils.equalsIgnoreCase(getShortDescription(), other.getShortDescription()) && StringUtils.equalsIgnoreCase(getLocation(), other.getLocation()) && favorite == other.favorite && favoritePoints == other.favoritePoints && onWatchlist == other.onWatchlist && (hidden != null ? hidden.equals(other.hidden) : null == other.hidden) && StringUtils.equalsIgnoreCase(guid, other.guid) && StringUtils.equalsIgnoreCase(getHint(), other.getHint()) && StringUtils.equalsIgnoreCase(cacheId, other.cacheId) && (direction != null ? direction.equals(other.direction) : null == other.direction) && (distance != null ? distance.equals(other.distance) : null == other.distance) && (elevation != null ? elevation.equals(other.elevation) : null == other.elevation) && rating == other.rating && votes == other.votes && myVote == other.myVote && inventoryItems == other.inventoryItems && attributes == other.attributes && waypoints == other.waypoints && spoilers == other.spoilers && logs == other.logs && inventory == other.inventory && logCounts == other.logCounts && logOffline == other.logOffline && finalDefined == other.finalDefined; } public boolean hasTrackables() { return inventoryItems > 0; } public boolean canBeAddedToCalendar() { // is event type? if (!isEventCache()) { return false; } // has event date set? if (hidden == null) { return false; } // is not in the past? final Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return hidden.compareTo(cal.getTime()) >= 0; } /** * Checks if a page contains the guid of a cache * * @param page * the page to search in, may be null * @return true if the page contains the guid of the cache, false otherwise */ public boolean isGuidContainedInPage(final String page) { if (StringUtils.isBlank(page) || StringUtils.isBlank(guid)) { return false; } final Boolean found = Pattern.compile(guid, Pattern.CASE_INSENSITIVE).matcher(page).find(); Log.i("Geocache.isGuidContainedInPage: guid '" + guid + "' " + (found ? "" : "not ") + "found"); return found; } public boolean isEventCache() { return cacheType.isEvent(); } public void logVisit(final IAbstractActivity fromActivity) { if (StringUtils.isBlank(cacheId)) { fromActivity.showToast(((Activity) fromActivity).getResources().getString(R.string.err_cannot_log_visit)); return; } Intent logVisitIntent = new Intent((Activity) fromActivity, VisitCacheActivity.class); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_ID, cacheId); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_GEOCODE, geocode); ((Activity) fromActivity).startActivity(logVisitIntent); } public void logOffline(final Activity fromActivity, final LogType logType) { final boolean mustIncludeSignature = StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature(); final String initial = mustIncludeSignature ? LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(this, true)) : ""; logOffline(fromActivity, initial, Calendar.getInstance(), logType); } void logOffline(final Activity fromActivity, final String log, Calendar date, final LogType logType) { if (logType == LogType.UNKNOWN) { return; } final boolean status = cgData.saveLogOffline(geocode, date.getTime(), logType, log); Resources res = fromActivity.getResources(); if (status) { ActivityMixin.showToast(fromActivity, res.getString(R.string.info_log_saved)); cgData.saveVisitDate(geocode); logOffline = true; notifyChange(); } else { ActivityMixin.showToast(fromActivity, res.getString(R.string.err_log_post_failed)); } } public List<LogType> getPossibleLogTypes() { final List<LogType> logTypes = new LinkedList<LogType>(); if (isEventCache()) { logTypes.add(LogType.WILL_ATTEND); logTypes.add(LogType.NOTE); logTypes.add(LogType.ATTENDED); logTypes.add(LogType.NEEDS_ARCHIVE); if (isOwner()) { logTypes.add(LogType.ANNOUNCEMENT); } } else if (CacheType.WEBCAM == cacheType) { logTypes.add(LogType.WEBCAM_PHOTO_TAKEN); logTypes.add(LogType.DIDNT_FIND_IT); logTypes.add(LogType.NOTE); logTypes.add(LogType.NEEDS_ARCHIVE); logTypes.add(LogType.NEEDS_MAINTENANCE); } else { logTypes.add(LogType.FOUND_IT); logTypes.add(LogType.DIDNT_FIND_IT); logTypes.add(LogType.NOTE); logTypes.add(LogType.NEEDS_ARCHIVE); logTypes.add(LogType.NEEDS_MAINTENANCE); } if (isOwner()) { logTypes.add(LogType.OWNER_MAINTENANCE); logTypes.add(LogType.TEMP_DISABLE_LISTING); logTypes.add(LogType.ENABLE_LISTING); logTypes.add(LogType.ARCHIVE); logTypes.remove(LogType.UPDATE_COORDINATES); } return logTypes; } public void openInBrowser(Activity fromActivity) { fromActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getBrowserCacheUrl()))); } private String getCacheUrl() { return getConnector().getCacheUrl(this); } private String getBrowserCacheUrl() { return getConnector().getLongCacheUrl(this); } private IConnector getConnector() { return ConnectorFactory.getConnector(this); } public boolean canOpenInBrowser() { return getCacheUrl() != null; } public boolean supportsRefresh() { return getConnector() instanceof ISearchByGeocode; } public boolean supportsWatchList() { return getConnector().supportsWatchList(); } public boolean supportsFavoritePoints() { return getConnector().supportsFavoritePoints(); } public boolean supportsLogging() { return getConnector().supportsLogging(); } public boolean supportsOwnCoordinates() { return getConnector().supportsOwnCoordinates(); } public CacheRealm getCacheRealm() { return getConnector().getCacheRealm(); } @Override public float getDifficulty() { return difficulty; } @Override public String getGeocode() { return geocode; } @Override public String getOwnerDisplayName() { return ownerDisplayName; } @Override public CacheSize getSize() { if (size == null) { return CacheSize.UNKNOWN; } return size; } @Override public float getTerrain() { return terrain; } @Override public boolean isArchived() { return archived; } @Override public boolean isDisabled() { return disabled; } @Override public boolean isPremiumMembersOnly() { return premiumMembersOnly; } public void setPremiumMembersOnly(boolean members) { this.premiumMembersOnly = members; } @Override public boolean isOwner() { return getConnector().isOwner(this); } @Override public String getOwnerUserId() { return ownerUserId; } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getHint() { initializeCacheTexts(); assertTextNotNull(hint, "Hint"); return hint; } /** * After lazy loading the lazily loaded field must be non {@code null}. * */ private static void assertTextNotNull(final String field, final String name) throws InternalError { if (field == null) { throw new InternalError(name + " field is not allowed to be null here"); } } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getDescription() { initializeCacheTexts(); assertTextNotNull(description, "Description"); return description; } /** * loads long text parts of a cache on demand (but all fields together) */ private void initializeCacheTexts() { if (description == null || shortdesc == null || hint == null || location == null) { Geocache partial = cgData.loadCacheTexts(this.getGeocode()); if (description == null) { setDescription(partial.getDescription()); } if (shortdesc == null) { setShortDescription(partial.getShortDescription()); } if (hint == null) { setHint(partial.getHint()); } if (location == null) { setLocation(partial.getLocation()); } } } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getShortDescription() { initializeCacheTexts(); assertTextNotNull(shortdesc, "Short description"); return shortdesc; } @Override public String getName() { return name; } @Override public String getCacheId() { if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) { return String.valueOf(GCConstants.gccodeToGCId(geocode)); } return cacheId; } @Override public String getGuid() { return guid; } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getLocation() { initializeCacheTexts(); assertTextNotNull(location, "Location"); return location; } @Override public String getPersonalNote() { // non premium members have no personal notes, premium members have an empty string by default. // map both to null, so other code doesn't need to differentiate if (StringUtils.isBlank(personalNote)) { return null; } return personalNote; } public boolean supportsUserActions() { return getConnector().supportsUserActions(); } public boolean supportsCachesAround() { return getConnector() instanceof ISearchByCenter; } public void shareCache(Activity fromActivity, Resources res) { if (geocode == null) { return; } StringBuilder subject = new StringBuilder("Geocache "); subject.append(geocode); if (StringUtils.isNotBlank(name)) { subject.append(" - ").append(name); } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); intent.putExtra(Intent.EXTRA_TEXT, getUrl()); fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.action_bar_share_title))); } public String getUrl() { return getConnector().getCacheUrl(this); } public boolean supportsGCVote() { return StringUtils.startsWithIgnoreCase(geocode, "GC"); } public void setDescription(final String description) { this.description = description; } @Override public boolean isFound() { return found; } @Override public boolean isFavorite() { return favorite; } public void setFavorite(boolean favourite) { this.favorite = favourite; } @Override public boolean isWatchlist() { return onWatchlist; } @Override public Date getHiddenDate() { return hidden; } @Override public List<String> getAttributes() { return attributes; } @Override public List<Trackable> getInventory() { return inventory; } public void addSpoiler(final Image spoiler) { if (spoilers == null) { spoilers = new ArrayList<Image>(); } spoilers.add(spoiler); } @Override public List<Image> getSpoilers() { if (spoilers == null) { return Collections.emptyList(); } return Collections.unmodifiableList(spoilers); } @Override public Map<LogType, Integer> getLogCounts() { return logCounts; } @Override public int getFavoritePoints() { return favoritePoints; } @Override public String getNameForSorting() { if (null == nameForSorting) { final MatcherWrapper matcher = new MatcherWrapper(NUMBER_PATTERN, name); if (matcher.find()) { nameForSorting = name.replace(matcher.group(), StringUtils.leftPad(matcher.group(), 6, '0')); } else { nameForSorting = name; } } return nameForSorting; } public boolean isVirtual() { return CacheType.VIRTUAL == cacheType || CacheType.WEBCAM == cacheType || CacheType.EARTH == cacheType; } public boolean showSize() { return !((isEventCache() || isVirtual()) && size == CacheSize.NOT_CHOSEN); } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public long getDetailedUpdate() { return detailedUpdate; } public void setDetailedUpdate(long detailedUpdate) { this.detailedUpdate = detailedUpdate; } public long getVisitedDate() { return visitedDate; } public void setVisitedDate(long visitedDate) { this.visitedDate = visitedDate; } public int getListId() { return listId; } public void setListId(int listId) { this.listId = listId; } public boolean isDetailed() { return detailed; } public void setDetailed(boolean detailed) { this.detailed = detailed; } public void setHidden(final Date hidden) { if (hidden == null) { this.hidden = null; } else { this.hidden = new Date(hidden.getTime()); // avoid storing the external reference in this object } } public Float getDirection() { return direction; } public void setDirection(Float direction) { this.direction = direction; } public Float getDistance() { return distance; } public void setDistance(Float distance) { this.distance = distance; } @Override public Geopoint getCoords() { return coords; } public void setCoords(Geopoint coords) { this.coords = coords; } /** * @return true if the coords are from the cache details page and the user has been logged in */ public boolean isReliableLatLon() { return getConnector().isReliableLatLon(reliableLatLon); } public void setReliableLatLon(boolean reliableLatLon) { this.reliableLatLon = reliableLatLon; } public Double getElevation() { return elevation; } public void setElevation(Double elevation) { this.elevation = elevation; } public void setShortDescription(String shortdesc) { this.shortdesc = shortdesc; } public void setFavoritePoints(int favoriteCnt) { this.favoritePoints = favoriteCnt; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public int getVotes() { return votes; } public void setVotes(int votes) { this.votes = votes; } public float getMyVote() { return myVote; } public void setMyVote(float myVote) { this.myVote = myVote; } public int getInventoryItems() { return inventoryItems; } public void setInventoryItems(int inventoryItems) { this.inventoryItems = inventoryItems; } public boolean isOnWatchlist() { return onWatchlist; } public void setOnWatchlist(boolean onWatchlist) { this.onWatchlist = onWatchlist; } /** * return an immutable list of waypoints. * * @return always non <code>null</code> */ public List<Waypoint> getWaypoints() { return waypoints; } /** * @param waypoints * List of waypoints to set for cache * @param saveToDatabase * Indicates whether to add the waypoints to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoints successfully added to waypoint database */ public boolean setWaypoints(List<Waypoint> waypoints, boolean saveToDatabase) { this.waypoints.clear(); if (waypoints != null) { this.waypoints.addAll(waypoints); } finalDefined = false; if (waypoints != null) { for (Waypoint waypoint : waypoints) { waypoint.setGeocode(geocode); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } } return saveToDatabase && cgData.saveWaypoints(this); } /** * @return never <code>null</code> */ public List<LogEntry> getLogs() { return logs; } /** * @return only the logs of friends, never <code>null</code> */ public List<LogEntry> getFriendsLogs() { ArrayList<LogEntry> friendLogs = new ArrayList<LogEntry>(); for (LogEntry log : logs) { if (log.friend) { friendLogs.add(log); } } return Collections.unmodifiableList(friendLogs); } /** * @param logs * the log entries */ public void setLogs(List<LogEntry> logs) { this.logs.clear(); if (logs != null) { this.logs.addAll(logs); } } public boolean isLogOffline() { return logOffline; } public void setLogOffline(boolean logOffline) { this.logOffline = logOffline; } public boolean isStatusChecked() { return statusChecked; } public void setStatusChecked(boolean statusChecked) { this.statusChecked = statusChecked; } public String getDirectionImg() { return directionImg; } public void setDirectionImg(String directionImg) { this.directionImg = directionImg; } public void setGeocode(String geocode) { this.geocode = StringUtils.upperCase(geocode); } public void setCacheId(String cacheId) { this.cacheId = cacheId; } public void setGuid(String guid) { this.guid = guid; } public void setName(String name) { this.name = name; } public void setOwnerDisplayName(String ownerDisplayName) { this.ownerDisplayName = ownerDisplayName; } public void setOwnerUserId(String ownerUserId) { this.ownerUserId = ownerUserId; } public void setHint(String hint) { this.hint = hint; } public void setSize(CacheSize size) { if (size == null) { this.size = CacheSize.UNKNOWN; } else { this.size = size; } } public void setDifficulty(float difficulty) { this.difficulty = difficulty; } public void setTerrain(float terrain) { this.terrain = terrain; } public void setLocation(String location) { this.location = location; } public void setPersonalNote(String personalNote) { this.personalNote = personalNote; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void setArchived(boolean archived) { this.archived = archived; } public void setFound(boolean found) { this.found = found; } public void setAttributes(List<String> attributes) { this.attributes.clear(); if (attributes != null) { this.attributes.addAll(attributes); } } public void setSpoilers(List<Image> spoilers) { this.spoilers = spoilers; } public void setInventory(List<Trackable> inventory) { this.inventory = inventory; } public void setLogCounts(Map<LogType, Integer> logCounts) { this.logCounts = logCounts; } /* * (non-Javadoc) * * @see cgeo.geocaching.IBasicCache#getType() * * @returns Never null */ @Override public CacheType getType() { return cacheType; } public void setType(CacheType cacheType) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = cacheType; } public boolean hasDifficulty() { return difficulty > 0f; } public boolean hasTerrain() { return terrain > 0f; } /** * @return the storageLocation */ public EnumSet<StorageLocation> getStorageLocation() { return storageLocation; } /** * @param storageLocation * the storageLocation to set */ public void addStorageLocation(final StorageLocation storageLocation) { this.storageLocation.add(storageLocation); } /** * @param waypoint * Waypoint to add to the cache * @param saveToDatabase * Indicates whether to add the waypoint to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoint successfully added to waypoint database */ public boolean addOrChangeWaypoint(final Waypoint waypoint, boolean saveToDatabase) { waypoint.setGeocode(geocode); if (waypoint.getId() < 0) { // this is a new waypoint waypoints.add(waypoint); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } else { // this is a waypoint being edited final int index = getWaypointIndex(waypoint); if (index >= 0) { waypoints.remove(index); } waypoints.add(waypoint); // when waypoint was edited, finalDefined may have changed resetFinalDefined(); } return saveToDatabase && cgData.saveWaypoint(waypoint.getId(), geocode, waypoint); } public boolean hasWaypoints() { return !waypoints.isEmpty(); } public boolean hasFinalDefined() { return finalDefined; } // Only for loading public void setFinalDefined(boolean finalDefined) { this.finalDefined = finalDefined; } /** * Reset <code>finalDefined</code> based on current list of stored waypoints */ private void resetFinalDefined() { finalDefined = false; for (Waypoint wp : waypoints) { if (wp.isFinalWithCoords()) { finalDefined = true; break; } } } public boolean hasUserModifiedCoords() { return userModifiedCoords; } public void setUserModifiedCoords(boolean coordsChanged) { userModifiedCoords = coordsChanged; } /** * Duplicate a waypoint. * * @param original * the waypoint to duplicate * @return <code>true</code> if the waypoint was duplicated, <code>false</code> otherwise (invalid index) */ public boolean duplicateWaypoint(final Waypoint original) { if (original == null) { return false; } final int index = getWaypointIndex(original); final Waypoint copy = new Waypoint(original); copy.setUserDefined(); copy.setName(cgeoapplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName()); waypoints.add(index + 1, copy); return cgData.saveWaypoint(-1, geocode, copy); } /** * delete a user defined waypoint * * @param waypoint * to be removed from cache * @return <code>true</code>, if the waypoint was deleted */ public boolean deleteWaypoint(final Waypoint waypoint) { if (waypoint == null) { return false; } if (waypoint.getId() < 0) { return false; } if (waypoint.isUserDefined()) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); cgData.deleteWaypoint(waypoint.getId()); cgData.removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE)); // Check status if Final is defined if (waypoint.isFinalWithCoords()) { resetFinalDefined(); } return true; } return false; } /** * deletes any waypoint * * @param waypoint */ public void deleteWaypointForce(Waypoint waypoint) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); cgData.deleteWaypoint(waypoint.getId()); cgData.removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE)); resetFinalDefined(); } /** * Find index of given <code>waypoint</code> in cache's <code>waypoints</code> list * * @param waypoint * to find index for * @return index in <code>waypoints</code> if found, -1 otherwise */ private int getWaypointIndex(final Waypoint waypoint) { final int id = waypoint.getId(); for (int index = 0; index < waypoints.size(); index++) { if (waypoints.get(index).getId() == id) { return index; } } return -1; } /** * Retrieve a given waypoint. * * @param index * the index of the waypoint * @return waypoint or <code>null</code> if index is out of range */ public Waypoint getWaypoint(final int index) { return index >= 0 && index < waypoints.size() ? waypoints.get(index) : null; } /** * Lookup a waypoint by its id. * * @param id * the id of the waypoint to look for * @return waypoint or <code>null</code> */ public Waypoint getWaypointById(final int id) { for (final Waypoint waypoint : waypoints) { if (waypoint.getId() == id) { return waypoint; } } return null; } public void parseWaypointsFromNote() { try { if (StringUtils.isBlank(getPersonalNote())) { return; } final Pattern coordPattern = Pattern.compile("\\b[nNsS]{1}\\s*\\d"); // begin of coordinates int count = 1; String note = getPersonalNote(); MatcherWrapper matcher = new MatcherWrapper(coordPattern, note); while (matcher.find()) { try { final Geopoint point = new Geopoint(note.substring(matcher.start())); // Coords must have non zero latitude and longitude, at least one part shall have fractional degrees, // and there must exist no waypoint with the same coordinates already. if (point.getLatitudeE6() != 0 && point.getLongitudeE6() != 0 && ((point.getLatitudeE6() % 1000) != 0 || (point.getLongitudeE6() % 1000) != 0) && !hasIdenticalWaypoint(point)) { final String name = cgeoapplication.getInstance().getString(R.string.cache_personal_note) + " " + count; final Waypoint waypoint = new Waypoint(name, WaypointType.WAYPOINT, false); waypoint.setCoords(point); addOrChangeWaypoint(waypoint, false); count++; } } catch (Geopoint.ParseException e) { // ignore } note = note.substring(matcher.start() + 1); matcher = new MatcherWrapper(coordPattern, note); } } catch (Exception e) { Log.e("Geocache.parseWaypointsFromNote", e); } } private boolean hasIdenticalWaypoint(final Geopoint point) { for (final Waypoint waypoint: waypoints) { if (waypoint.getCoords().equals(point)) { return true; } } return false; } /* * For working in the debugger * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return this.geocode + " " + this.name; } @Override public int hashCode() { return geocode.hashCode() * name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Geocache)) { return false; } // just compare the geocode even if that is not what "equals" normally does return StringUtils.isNotBlank(geocode) && geocode.equals(((Geocache) obj).geocode); } public void store(CancellableHandler handler) { store(StoredList.TEMPORARY_LIST_ID, handler); } public void store(final int listId, CancellableHandler handler) { int newListId = listId < StoredList.STANDARD_LIST_ID ? Math.max(getListId(), StoredList.STANDARD_LIST_ID) : listId; storeCache(this, null, newListId, false, handler); } public void setZoomlevel(int zoomlevel) { this.zoomlevel = zoomlevel; } @Override public int getId() { return 0; } @Override public WaypointType getWaypointType() { return null; } @Override public String getCoordType() { return "cache"; } public void drop(Handler handler) { try { cgData.markDropped(Collections.singletonList(this)); cgData.removeCache(getGeocode(), EnumSet.of(RemoveFlag.REMOVE_CACHE)); handler.sendMessage(Message.obtain()); } catch (Exception e) { Log.e("cache.drop: ", e); } } public void checkFields() { if (StringUtils.isBlank(getGeocode())) { Log.w("geo code not parsed correctly for " + geocode); } if (StringUtils.isBlank(getName())) { Log.w("name not parsed correctly for " + geocode); } if (StringUtils.isBlank(getGuid())) { Log.w("guid not parsed correctly for " + geocode); } if (getTerrain() == 0.0) { Log.w("terrain not parsed correctly for " + geocode); } if (getDifficulty() == 0.0) { Log.w("difficulty not parsed correctly for " + geocode); } if (StringUtils.isBlank(getOwnerDisplayName())) { Log.w("owner display name not parsed correctly for " + geocode); } if (StringUtils.isBlank(getOwnerUserId())) { Log.w("owner user id real not parsed correctly for " + geocode); } if (getHiddenDate() == null) { Log.w("hidden not parsed correctly for " + geocode); } if (getFavoritePoints() < 0) { Log.w("favoriteCount not parsed correctly for " + geocode); } if (getSize() == null) { Log.w("size not parsed correctly for " + geocode); } if (getType() == null || getType() == CacheType.UNKNOWN) { Log.w("type not parsed correctly for " + geocode); } if (getCoords() == null) { Log.w("coordinates not parsed correctly for " + geocode); } if (StringUtils.isBlank(getLocation())) { Log.w("location not parsed correctly for " + geocode); } } public void refresh(int newListId, CancellableHandler handler) { cgData.removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE)); storeCache(null, geocode, newListId, true, handler); } public static void storeCache(Geocache origCache, String geocode, int listId, boolean forceRedownload, CancellableHandler handler) { try { Geocache cache; // get cache details, they may not yet be complete if (origCache != null) { // only reload the cache if it was already stored or doesn't have full details (by checking the description) if (origCache.isOffline() || StringUtils.isBlank(origCache.getDescription())) { final SearchResult search = searchByGeocode(origCache.getGeocode(), null, listId, false, handler); cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } else { cache = origCache; } } else if (StringUtils.isNotBlank(geocode)) { final SearchResult search = searchByGeocode(geocode, null, listId, forceRedownload, handler); cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } else { cache = null; } if (cache == null) { if (handler != null) { handler.sendMessage(Message.obtain()); } return; } if (CancellableHandler.isCancelled(handler)) { return; } final HtmlImage imgGetter = new HtmlImage(cache.getGeocode(), false, listId, true); // store images from description if (StringUtils.isNotBlank(cache.getDescription())) { Html.fromHtml(cache.getDescription(), imgGetter, null); } if (CancellableHandler.isCancelled(handler)) { return; } // store spoilers if (CollectionUtils.isNotEmpty(cache.getSpoilers())) { for (Image oneSpoiler : cache.getSpoilers()) { imgGetter.getDrawable(oneSpoiler.getUrl()); } } if (CancellableHandler.isCancelled(handler)) { return; } // store images from logs if (Settings.isStoreLogImages()) { for (LogEntry log : cache.getLogs()) { if (log.hasLogImages()) { for (Image oneLogImg : log.getLogImages()) { imgGetter.getDrawable(oneLogImg.getUrl()); } } } } if (CancellableHandler.isCancelled(handler)) { return; } cache.setListId(listId); cgData.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); if (CancellableHandler.isCancelled(handler)) { return; } StaticMapsProvider.downloadMaps(cache); if (handler != null) { handler.sendMessage(Message.obtain()); } } catch (Exception e) { Log.e("cgBase.storeCache"); } } public static SearchResult searchByGeocode(final String geocode, final String guid, final int listId, final boolean forceReload, final CancellableHandler handler) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { Log.e("Geocache.searchByGeocode: No geocode nor guid given"); return null; } if (!forceReload && listId == StoredList.TEMPORARY_LIST_ID && (cgData.isOffline(geocode, guid) || cgData.isThere(geocode, guid, true, true))) { final SearchResult search = new SearchResult(); final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : cgData.getGeocodeForGuid(guid); search.addGeocode(realGeocode); return search; } // if we have no geocode, we can't dynamically select the handler, but must explicitly use GC if (geocode == null && guid != null) { return GCConnector.getInstance().searchByGeocode(null, guid, handler); } final IConnector connector = ConnectorFactory.getConnector(geocode); if (connector instanceof ISearchByGeocode) { return ((ISearchByGeocode) connector).searchByGeocode(geocode, guid, handler); } return null; } public boolean isOffline() { return listId >= StoredList.STANDARD_LIST_ID; } /** * guess an event start time from the description * * @return start time in minutes after midnight */ public String guessEventTimeMinutes() { if (!isEventCache()) { return null; } // 12:34 final Pattern time = Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)\\b"); final MatcherWrapper matcher = new MatcherWrapper(time, getDescription()); while (matcher.find()) { try { final int hours = Integer.valueOf(matcher.group(1)); final int minutes = Integer.valueOf(matcher.group(2)); if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) { return String.valueOf(hours * 60 + minutes); } } catch (NumberFormatException e) { // cannot happen, but static code analysis doesn't know } } // 12 o'clock final String hourLocalized = cgeoapplication.getInstance().getString(R.string.cache_time_full_hours); if (StringUtils.isNotBlank(hourLocalized)) { final Pattern fullHours = Pattern.compile("\\b(\\d{1,2})\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE); final MatcherWrapper matcherHours = new MatcherWrapper(fullHours, getDescription()); if (matcherHours.find()) { try { final int hours = Integer.valueOf(matcherHours.group(1)); if (hours >= 0 && hours < 24) { return String.valueOf(hours * 60); } } catch (NumberFormatException e) { // cannot happen, but static code analysis doesn't know } } } return null; } /** * check whether the cache has a given attribute * * @param attribute * @param yes * true if we are looking for the attribute_yes version, false for the attribute_no version * @return */ public boolean hasAttribute(CacheAttribute attribute, boolean yes) { Geocache fullCache = cgData.loadCache(getGeocode(), EnumSet.of(LoadFlag.LOAD_ATTRIBUTES)); if (fullCache == null) { fullCache = this; } return fullCache.getAttributes().contains(attribute.getAttributeName(yes)); } public boolean hasStaticMap() { return StaticMapsProvider.hasStaticMap(this); } public List<Image> getImages() { List<Image> result = new ArrayList<Image>(); result.addAll(getSpoilers()); for (LogEntry log : getLogs()) { result.addAll(log.getLogImages()); } return result; } public void setDetailedUpdatedNow() { final long now = System.currentTimeMillis(); setUpdated(now); setDetailedUpdate(now); setDetailed(true); } /** * Gets whether the user has logged the specific log type for this cache. Only checks the currently stored logs of * the cache, so the result might be wrong. */ public boolean hasOwnLog(LogType logType) { for (LogEntry logEntry : getLogs()) { if (logEntry.type == logType && logEntry.isOwn()) { return true; } } return false; } }
false
true
public boolean gatherMissingFrom(final Geocache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) { detailed = other.detailed; detailedUpdate = other.detailedUpdate; coords = other.coords; cacheType = other.cacheType; zoomlevel = other.zoomlevel; // boolean values must be enumerated here. Other types are assigned outside this if-statement premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; archived = other.archived; found = other.found; disabled = other.disabled; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; } /* * No gathering for boolean members if other cache is not-detailed * and does not have information with higher reliability (denoted by zoomlevel) * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.visitedDate; } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.geocode; } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.guid; } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.cacheType; } if (StringUtils.isBlank(name)) { name = other.name; } if (StringUtils.isBlank(ownerDisplayName)) { ownerDisplayName = other.ownerDisplayName; } if (StringUtils.isBlank(ownerUserId)) { ownerUserId = other.ownerUserId; } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(getHint())) { hint = other.getHint(); } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.difficulty; } if (terrain == 0) { terrain = other.terrain; } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.distance; } if (StringUtils.isBlank(getLocation())) { location = other.getLocation(); } if (coords == null) { coords = other.coords; } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(getShortDescription())) { shortdesc = other.getShortDescription(); } if (StringUtils.isBlank(getDescription())) { description = other.getDescription(); } // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too. if (favoritePoints == 0) { favoritePoints = other.favoritePoints; } if (rating == 0) { rating = other.rating; } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.myVote; } if (attributes.isEmpty()) { attributes.clear(); if (other.attributes != null) { attributes.addAll(other.attributes); } } if (waypoints.isEmpty()) { this.setWaypoints(other.waypoints, false); } else { ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>(waypoints); Waypoint.mergeWayPoints(newPoints, other.waypoints, false); this.setWaypoints(newPoints, false); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (logs.isEmpty()) { // keep last known logs if none logs.clear(); if (other.logs != null) { logs.addAll(other.logs); } } if (logCounts.isEmpty()) { logCounts = other.logCounts; } // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not userModifiedCoords = false; if (waypoints != null) { for (Waypoint wpt : waypoints) { if (wpt.getWaypointType() == WaypointType.ORIGINAL) { userModifiedCoords = true; break; } } } if (!reliableLatLon) { reliableLatLon = other.reliableLatLon; } if (zoomlevel == -1) { zoomlevel = other.zoomlevel; } return isEqualTo(other); }
public boolean gatherMissingFrom(final Geocache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) { detailed = other.detailed; detailedUpdate = other.detailedUpdate; coords = other.coords; cacheType = other.cacheType; zoomlevel = other.zoomlevel; // boolean values must be enumerated here. Other types are assigned outside this if-statement // TODO: check whether a search or a live map systematically returns those, in which case // we want to keep the most recent one instead of getting information from the previously // stored data. This is the case for "archived" for example which has been taken out of this // list. premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; found = other.found; disabled = other.disabled; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; // archived is kept from the most recent data } /* * No gathering for boolean members if other cache is not-detailed * and does not have information with higher reliability (denoted by zoomlevel) * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.visitedDate; } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.geocode; } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.guid; } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.cacheType; } if (StringUtils.isBlank(name)) { name = other.name; } if (StringUtils.isBlank(ownerDisplayName)) { ownerDisplayName = other.ownerDisplayName; } if (StringUtils.isBlank(ownerUserId)) { ownerUserId = other.ownerUserId; } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(getHint())) { hint = other.getHint(); } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.difficulty; } if (terrain == 0) { terrain = other.terrain; } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.distance; } if (StringUtils.isBlank(getLocation())) { location = other.getLocation(); } if (coords == null) { coords = other.coords; } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(getShortDescription())) { shortdesc = other.getShortDescription(); } if (StringUtils.isBlank(getDescription())) { description = other.getDescription(); } // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too. if (favoritePoints == 0) { favoritePoints = other.favoritePoints; } if (rating == 0) { rating = other.rating; } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.myVote; } if (attributes.isEmpty()) { attributes.clear(); if (other.attributes != null) { attributes.addAll(other.attributes); } } if (waypoints.isEmpty()) { this.setWaypoints(other.waypoints, false); } else { ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>(waypoints); Waypoint.mergeWayPoints(newPoints, other.waypoints, false); this.setWaypoints(newPoints, false); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (logs.isEmpty()) { // keep last known logs if none logs.clear(); if (other.logs != null) { logs.addAll(other.logs); } } if (logCounts.isEmpty()) { logCounts = other.logCounts; } // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not userModifiedCoords = false; if (waypoints != null) { for (Waypoint wpt : waypoints) { if (wpt.getWaypointType() == WaypointType.ORIGINAL) { userModifiedCoords = true; break; } } } if (!reliableLatLon) { reliableLatLon = other.reliableLatLon; } if (zoomlevel == -1) { zoomlevel = other.zoomlevel; } return isEqualTo(other); }
diff --git a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/format/AutoFormatter.java b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/format/AutoFormatter.java index a37dbc7..7ba8b09 100644 --- a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/format/AutoFormatter.java +++ b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/format/AutoFormatter.java @@ -1,72 +1,72 @@ /******************************************************************************* * Copyright (c) 2010 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.core.format; import org.eclipse.birt.core.exception.BirtException; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; /** * */ public class AutoFormatter implements IFormatter { private String pattern; private ULocale locale; private TimeZone timeZone; private IFormatter directFormatter = null; public AutoFormatter( String pattern, ULocale locale, TimeZone timeZone ) { this.pattern = pattern; this.locale = locale; this.timeZone = timeZone; } /* * (non-Javadoc) * * @see * org.eclipse.birt.core.format.IFormatter#formatValue(java.lang.Object) */ public String formatValue( Object value ) throws BirtException { if ( directFormatter == null ) { // implicitly includes its child classes java.sql.Date, // java.sql.Time and java.sql.Timestamp if ( value instanceof java.util.Date ) { directFormatter = new DateFormatter( pattern, this.locale, this.timeZone ); } else if ( value instanceof Number ) { directFormatter = new NumberFormatter( pattern, this.locale ); } - else if ( value instanceof String ) + else if ( pattern != null && value instanceof String ) { directFormatter = new StringFormatter( pattern, this.locale ); } else { directFormatter = new DefaultFormatter( locale ); } } return directFormatter.formatValue( value ); } }
true
true
public String formatValue( Object value ) throws BirtException { if ( directFormatter == null ) { // implicitly includes its child classes java.sql.Date, // java.sql.Time and java.sql.Timestamp if ( value instanceof java.util.Date ) { directFormatter = new DateFormatter( pattern, this.locale, this.timeZone ); } else if ( value instanceof Number ) { directFormatter = new NumberFormatter( pattern, this.locale ); } else if ( value instanceof String ) { directFormatter = new StringFormatter( pattern, this.locale ); } else { directFormatter = new DefaultFormatter( locale ); } } return directFormatter.formatValue( value ); }
public String formatValue( Object value ) throws BirtException { if ( directFormatter == null ) { // implicitly includes its child classes java.sql.Date, // java.sql.Time and java.sql.Timestamp if ( value instanceof java.util.Date ) { directFormatter = new DateFormatter( pattern, this.locale, this.timeZone ); } else if ( value instanceof Number ) { directFormatter = new NumberFormatter( pattern, this.locale ); } else if ( pattern != null && value instanceof String ) { directFormatter = new StringFormatter( pattern, this.locale ); } else { directFormatter = new DefaultFormatter( locale ); } } return directFormatter.formatValue( value ); }
diff --git a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java b/src/main/java/net/h31ix/anticheat/event/InventoryListener.java index 0098b04..b81d644 100644 --- a/src/main/java/net/h31ix/anticheat/event/InventoryListener.java +++ b/src/main/java/net/h31ix/anticheat/event/InventoryListener.java @@ -1,65 +1,65 @@ /* * AntiCheat for Bukkit. * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net * * 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 net.h31ix.anticheat.event; import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.util.CheckResult; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; public class InventoryListener extends EventListener { @EventHandler public void onInventoryClick(InventoryClickEvent event) { - if (!event.isRightClick() && event.getWhoClicked() instanceof Player) { + if (!event.isRightClick() && !event.isShiftClick() && event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) { CheckResult result = getBackend().checkInventoryClicks(player); if (result.failed()) { if (!silentMode()) { getUserManager().getUser(player.getName()).restore(event.getInventory()); player.getInventory().clear(); } log(result.getMessage(), player, CheckType.FAST_INVENTORY); } else { decrease(player); } } } Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); } @EventHandler public void onInventoryOpen(InventoryOpenEvent event) { if(event.getInventory().getType() != InventoryType.BEACON) { getUserManager().getUser(event.getPlayer().getName()).setSnapshot(event.getInventory().getContents()); } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { getUserManager().getUser(event.getPlayer().getName()).removeSnapshot(); } }
true
true
public void onInventoryClick(InventoryClickEvent event) { if (!event.isRightClick() && event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) { CheckResult result = getBackend().checkInventoryClicks(player); if (result.failed()) { if (!silentMode()) { getUserManager().getUser(player.getName()).restore(event.getInventory()); player.getInventory().clear(); } log(result.getMessage(), player, CheckType.FAST_INVENTORY); } else { decrease(player); } } } Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); }
public void onInventoryClick(InventoryClickEvent event) { if (!event.isRightClick() && !event.isShiftClick() && event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if (getCheckManager().willCheck(player, CheckType.FAST_INVENTORY)) { CheckResult result = getBackend().checkInventoryClicks(player); if (result.failed()) { if (!silentMode()) { getUserManager().getUser(player.getName()).restore(event.getInventory()); player.getInventory().clear(); } log(result.getMessage(), player, CheckType.FAST_INVENTORY); } else { decrease(player); } } } Anticheat.getManager().addEvent(event.getEventName(), event.getHandlers().getRegisteredListeners()); }
diff --git a/src/main/java/se/llbit/chunky/main/Chunky.java b/src/main/java/se/llbit/chunky/main/Chunky.java index aae38c6e..2f0a9dcc 100644 --- a/src/main/java/se/llbit/chunky/main/Chunky.java +++ b/src/main/java/se/llbit/chunky/main/Chunky.java @@ -1,1026 +1,1026 @@ /* Copyright (c) 2010-2012 Jesper Öqvist <[email protected]> * * This file is part of Chunky. * * Chunky 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. * * Chunky 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 Chunky. If not, see <http://www.gnu.org/licenses/>. */ package se.llbit.chunky.main; import java.awt.Color; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import se.llbit.chunky.renderer.AbstractRenderManager; import se.llbit.chunky.renderer.BenchmarkManager; import se.llbit.chunky.renderer.ConsoleRenderListener; import se.llbit.chunky.renderer.PlaceholderRenderCanvas; import se.llbit.chunky.renderer.RenderContext; import se.llbit.chunky.renderer.RenderManager; import se.llbit.chunky.renderer.scene.SceneLoadingError; import se.llbit.chunky.renderer.ui.BenchmarkDialog; import se.llbit.chunky.renderer.ui.CLDeviceSelector; import se.llbit.chunky.renderer.ui.NewSceneDialog; import se.llbit.chunky.renderer.ui.RenderControls; import se.llbit.chunky.renderer.ui.SceneDirectoryPicker; import se.llbit.chunky.renderer.ui.SceneSelector; import se.llbit.chunky.resources.TexturePackLoader; import se.llbit.chunky.ui.ChunkMap; import se.llbit.chunky.ui.ChunkyFrame; import se.llbit.chunky.ui.Controls; import se.llbit.chunky.ui.Minimap; import se.llbit.chunky.ui.ProgressPanel; import se.llbit.chunky.world.Block; import se.llbit.chunky.world.Chunk; import se.llbit.chunky.world.Chunk.Renderer; import se.llbit.chunky.world.listeners.ChunkDiscoveryListener; import se.llbit.chunky.world.ChunkParser; import se.llbit.chunky.world.ChunkPosition; import se.llbit.chunky.world.ChunkSelectionTracker; import se.llbit.chunky.world.ChunkView; import se.llbit.chunky.world.DeleteChunksJob; import se.llbit.chunky.world.EmptyChunk; import se.llbit.chunky.world.EmptyChunkView; import se.llbit.chunky.world.EmptyWorld; import se.llbit.chunky.world.Region; import se.llbit.chunky.world.RegionParser; import se.llbit.chunky.world.World; import se.llbit.chunky.world.WorldRenderer; import se.llbit.util.ProgramProperties; /** * Chunky is a Minecraft mapping and rendering tool created by * Jesper Öqvist. * * There is a Wiki for Chunky at http://chunky.llbit.se * * @author Jesper Öqvist ([email protected]) */ public class Chunky implements ChunkDiscoveryListener { /** * Minimum block scale for the map view */ public static final int BLOCK_SCALE_MIN = 0; /** * Maximum block scale for the map view */ public static final int BLOCK_SCALE_MAX = 32; /** * Default block scale for the map view */ public static final int DEFAULT_BLOCK_SCALE = 4; private int chunkScale = DEFAULT_BLOCK_SCALE*16; private World world = EmptyWorld.instance; private ChunkParser chunkParser = new ChunkParser(); private RegionParser regionParser = new RegionParser(); private int currentDimension = 0; private Chunk.Renderer chunkRenderer = Chunk.surfaceRenderer; private WorldRenderer worldRenderer = new WorldRenderer(); protected ChunkSelectionTracker chunkSelection = new ChunkSelectionTracker(); protected boolean ctrlModifier = false; protected boolean shiftModifier = false; private RenderControls renderControls = null; private ChunkyFrame frame; private ChunkView map = EmptyChunkView.instance; private ChunkView minimap = EmptyChunkView.instance; private int mapWidth = ChunkMap.DEFAULT_WIDTH; private int mapHeight = ChunkMap.DEFAULT_HEIGHT; private int minimapWidth = Minimap.DEFAULT_WIDTH; private int minimapHeight = Minimap.DEFAULT_HEIGHT; private Chunk hoveredChunk = EmptyChunk.instance; /** * Whether or not OpenCL rendering is enabled */ public boolean openCLEnabled = false; /** * Logger object. */ private static Logger logger = Logger.getLogger(Chunky.class); /** * @return The name of this application */ public static final String getAppName() { return String.format("%s %s", //$NON-NLS-1$ Messages.getString("Chunky.appname"), //$NON-NLS-1$ Messages.getString("Chunky.version")); //$NON-NLS-1$ } /** * @return Chunky revision */ public static final String getRevision() { return Messages.getString("Chunky.revision"); //$NON-NLS-1$ } static { // Configure the logger PropertyConfigurator.configure( Chunky.class.getResource("/log4j.properties")); } private int tileWidth = AbstractRenderManager.TILE_WIDTH_DEFAULT; /** * The help string */ private static final String USAGE = "Usage: chunky [OPTIONS] [WORLD DIRECTORY]\n" + "Options:\n" + " -texture <FILE> use FILE as the texture pack (must be a zip file)\n" + " -watermark add a watermark to saved frame\n" + " -render <SCENE> render the specified scene (name of .cfv file,\n" + " relative to the scenes directory) in headless mode\n" + " -scene-dir <DIR> use the directory DIR for loading/saving scenes\n" + " -benchmark run the benchmark and exit\n" + " -threads <NUM> use the specified number of threads for rendering\n" + " -tile-width <NUM> use the specified job tile width\n" + " -opencl enables OpenCL rendering in the GUI\n" + " -help show this text"; /** * Constructor */ public Chunky() { } /** * Create a new instance of the application GUI. * @param args * @return Program exit code (0 = success) */ public int run(String[] args) { boolean selectedWorld = false; File sceneDir = ProgramProperties.getPreferredSceneDirectory(); String sceneName = null; String texturePack = null; int renderThreads = Runtime.getRuntime().availableProcessors(); File worldDir = null; boolean doBench = false; for (int i = 0; i < args.length; ++i) { if (args[i].equals("-texture") && args.length > i+1) { texturePack = args[++i]; } else if (args[i].equals("-watermark")) { RenderManager.useWatermark = true; } else if (args[i].equals("-scene-dir")) { sceneDir = new File(args[++i]); } else if (args[i].equals("-render")) { sceneName = args[++i]; } else if (args[i].equals("-benchmark")) { doBench = true; } else if (args[i].equals("-threads")) { renderThreads = Math.max(1, Integer.parseInt(args[++i])); - } else if (args[i].equals("-tileWidth")) { + } else if (args[i].equals("-tile-width")) { tileWidth = Math.max(1, Integer.parseInt(args[++i])); } else if (args[i].equals("-opencl")) { openCLEnabled = true; } else if (args[i].equals("-h") || args[i].equals("-?") || args[i].equals("-help") || args[i].equals("--help")) { System.out.println(USAGE); return 0; } else if (!args[i].startsWith("-") && !selectedWorld) { worldDir = new File(args[i]); } else { System.err.println("Unrecognised argument: "+args[i]); System.err.println(USAGE); return 1; } } if (texturePack != null) { TexturePackLoader.loadTexturePack(new File(texturePack), false); } else { String lastTexturePack = ProgramProperties.getProperty("lastTexturePack"); if (lastTexturePack != null) TexturePackLoader.loadTexturePack(new File(lastTexturePack), false); else TexturePackLoader.loadTexturePack(getMinecraftJar(), false); } if (doBench) { doBenchmark(renderThreads); return 0; } if (sceneName != null) { // start headless mode System.setProperty("java.awt.headless", "true"); RenderContext renderContext = new RenderContext(sceneDir, renderThreads, tileWidth); RenderManager renderManager = new RenderManager( new PlaceholderRenderCanvas(), renderContext, new ConsoleRenderListener()); renderManager.start(); try { renderManager.loadScene(sceneName); if (!renderManager.scene().pathTrace()) { renderManager.scene().startRender(); } else { renderManager.scene().resumeRender(); } } catch (IOException e) { logger.error("IO error while loading scene", e); } catch (SceneLoadingError e) { logger.error("Scene loading error", e); } catch (InterruptedException e) { logger.error("Interrupted while loading scene", e); } return 0; } // load the world if (worldDir != null && World.isWorldDir(worldDir)) { loadWorld(new World(worldDir, false)); } else { String lastWorld = ProgramProperties.getProperty("lastWorld"); File lastWorldDir = lastWorld != null ? new File(lastWorld) : null; if (lastWorldDir != null && World.isWorldDir(lastWorldDir)) { loadWorld(new World(lastWorldDir, false)); } } // Start the worker threads chunkParser.start(); regionParser.start(); // Create UI in the event dispatch thread try { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { logger.warn("Failed to set native Look and Feel"); } SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { buildUI(); } }); } catch (InterruptedException e) { logger.fatal("Failed to initialize UI", e); } catch (InvocationTargetException e) { logger.fatal("Failed to initialize UI", e); } refreshLoop(); return 0; } /** * Perform a benchmark in headless mode * @param renderThreads */ private void doBenchmark(int renderThreads) { System.setProperty("java.awt.headless", "true"); File sceneDir = ProgramProperties.getPreferredSceneDirectory(); RenderContext renderContext = new RenderContext(sceneDir, renderThreads, tileWidth); BenchmarkManager benchmark = new BenchmarkManager(renderContext, new ConsoleRenderListener()); benchmark.start(); try { benchmark.join(); BenchmarkDialog.recordBenchmarkScore(benchmark.getSceneName(), benchmark.getScore()); System.out.println("Benchmark completed with score " + benchmark.getScore() + " (" + benchmark.getSceneName() + ")"); } catch (InterruptedException e) { logger.warn("Benchmarking interrupted"); } } protected void buildUI() { frame = new ChunkyFrame(this); frame.initComponents(); frame.setVisible(true); if (world.isEmptyWorld()) getControls().openWorldSelector(); else updateView(); } /** * Flush all cached chunks and regions, forcing them to be reloaded * for the current world. */ public synchronized void reloadWorld() { chunkSelection.clearSelection(); world.reload(); if (frame != null) { viewUpdated(); frame.getMap().redraw(); frame.getMinimap().redraw(); } } /** * Load a new world. * * @param newWorld */ public synchronized void loadWorld(World newWorld) { newWorld.reload(); regionParser.clearQueue(); chunkParser.clearQueue(); chunkSelection.clearSelection(); // dispose old world world.dispose(); world = newWorld; world.addChunkDeletionListener(chunkSelection); world.addChunkDiscoveryListener(this); // dimension must be set before chunks are loaded world.setDimension(currentDimension); updateView(); ProgramProperties.setProperty("lastWorld", world.getWorldDirectory().getAbsolutePath()); if (frame != null) { frame.worldLoaded(world); viewUpdated(); frame.getMap().redraw(); frame.getMinimap().redraw(); } } private void updateView() { if (world.havePlayerPos()) { setView( world.playerPosX() / 16, world.playerPosZ() / 16); } else { setView(0, 0); } } /** * Called when the map view has changed. */ public synchronized void viewUpdated() { minimap = new ChunkView(map.x, map.z, minimapWidth, minimapHeight, 1); // clear the region and chunk parse queues regionParser.clearQueue(); chunkParser.clearQueue(); // enqueue visible regions and chunks for (int rx = Math.min(minimap.rx0, map.prx0); rx <= Math.max(minimap.rx1, map.prx1); ++rx) { for (int rz = Math.min(minimap.rz0, map.prz0); rz <= Math.max(minimap.rz1, map.prz1); ++rz) { Region region = world.getRegion(ChunkPosition.get(rx, rz)); if (!region.isEmpty() && (map.isVisible(region) || minimap.isVisible(region))) { if (!region.isParsed()) { regionParser.addRegion(region); } else { // parse visible chunks region.preloadChunks(map, chunkParser); } } } } if (frame != null) { frame.getMap().viewUpdated(map); frame.getMinimap().viewUpdated(minimap); } } /** * Entry point for Chunky * * @param args */ public static void main(final String[] args) { Chunky chunky = new Chunky(); System.exit(chunky.run(args)); } /** * Periodically check for changes in the world state and * refresh the view if necessary. */ private void refreshLoop() { try { while (!Thread.interrupted()) { frame.refresh(); Thread.sleep(125); } } catch (InterruptedException e) { } } /** * Set the current map renderer * * @param renderer */ public synchronized void setRenderer(Chunk.Renderer renderer) { this.chunkRenderer = renderer; getMap().repaint(); } /** * Open the 3D chunk view */ public synchronized void open3DView() { if (renderControls == null || !renderControls.isDisplayable()) { File sceneDir = SceneDirectoryPicker.getSceneDirectory(frame); RenderContext context = new RenderContext(sceneDir, getControls().getNumThreads(), tileWidth); if (sceneDir != null) { NewSceneDialog dialog = new NewSceneDialog(getFrame(), context, world.levelName()); dialog.setVisible(true); if (dialog.isAccepted()) { renderControls = new RenderControls(Chunky.this, context); renderControls.setSceneName(dialog.getSceneName()); Collection<ChunkPosition> selection = chunkSelection.getSelection(); if (!selection.isEmpty()) renderControls.loadChunks(world, selection); else renderControls.show3DView(); } } } } /** * Set the hovered chunk by chunk coordinates * @param cx * @param cz */ public synchronized void setHoveredChunk(int cx, int cz) { hoveredChunk = world.getChunk(ChunkPosition.get(cx, cz)); } /** * @return The currently hovered chunk */ public synchronized Chunk getHoveredChunk() { return hoveredChunk; } /** * Select specific chunk * @param cx * @param cz */ public synchronized void selectChunk(int cx, int cz) { chunkSelection.selectChunk(world, cx, cz); getControls().setChunksSelected(chunkSelection.numSelectedChunks() > 0); } /** * Set the map view * @param cx * @param cz */ public synchronized void setView(final double cx, final double cz) { map = new ChunkView(cx, cz, mapWidth, mapHeight, chunkScale); if (frame != null) { getControls().setPosition(cx, getLayer(), cz); } viewUpdated(); } /** * Set the currently viewed layer * @param value */ public synchronized void setLayer(int value) { int layerNew = Math.max(0, Math.min(Chunk.Y_MAX-1, value)); if (layerNew != world.currentLayer()) { chunkParser.clearQueue(); world.setCurrentLayer(layerNew); if (chunkRenderer == Chunk.layerRenderer) getMap().redraw(); // force the chunks to redraw viewUpdated(); } getControls().setLayer(world.currentLayer()); } /** * @return The currently viewed layer */ public synchronized int getLayer() { return world.currentLayer(); } /** * Delete the currently selected chunks from the current world. */ public void deleteSelectedChunks() { Object[] options = {Messages.getString("Chunky.Cancel_lbl"), //$NON-NLS-1$ Messages.getString("Chunky.AcceptDelete_lbl")}; //$NON-NLS-1$ int n = JOptionPane.showOptionDialog(null, Messages.getString("Chunky.DeleteDialog_msg"), //$NON-NLS-1$ Messages.getString("Chunky.DeleteDialog_title"), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (n == 1) { Collection<ChunkPosition> selected = chunkSelection.getSelection(); ProgressPanel progress = getControls().getProgressPanel(); if (!selected.isEmpty() && !progress.isBusy()) { DeleteChunksJob job = new DeleteChunksJob(world, selected, progress); job.start(); } } } /** * Set the current dimension * @param value Must be a valid dimension index */ public void setDimension(int value) { if (value != currentDimension) { currentDimension = value; loadWorld(world); } } /** * Clears the chunk selection */ public synchronized void clearSelectedChunks() { chunkSelection.clearSelection(); getControls().setChunksSelected(chunkSelection.numSelectedChunks() > 0); } /** * @return The directory of the local Minecraft installation */ public static File getMinecraftDirectory() { String home = System.getProperty("user.home", "."); //$NON-NLS-1$ //$NON-NLS-2$ String os = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$ if (os.contains("win")) { //$NON-NLS-1$ String appdata = System.getenv("APPDATA"); //$NON-NLS-1$ if (appdata != null) return new File(appdata, ".minecraft"); //$NON-NLS-1$ else return new File(home, ".minecraft"); //$NON-NLS-1$ } else if (os.contains("mac")) { //$NON-NLS-1$ return new File(home, "Library/Application Support/minecraft"); //$NON-NLS-1$ } else { return new File(home, ".minecraft"); //$NON-NLS-1$ } } /** * @return The saves directory of the local Minecraft installation */ public static File getSavesDirectory() { return new File(getMinecraftDirectory(), "saves"); } /** * @return The texture pack directory of the local Minecraft installation */ public static File getTexturePacksDirectory() { return new File(getMinecraftDirectory(), "texturepacks"); } /** * @return The current highlight color */ public Color getHighlightColor() { return worldRenderer.getHighlightColor(); } /** * @return The currently highlighted block type */ public Block getHighlightBlock() { return worldRenderer.getHighlightBlock(); } /** * Set block type highlighting * @param value */ public void setHighlightEnable(boolean value) { if (value != worldRenderer.isHighlightEnabled()) { worldRenderer.setHighlightEnabled(value); getMap().redraw(); } } /** * @return <code>true</code> if block type highlighting is currently active */ public boolean isHighlightEnabled() { return worldRenderer.isHighlightEnabled(); } /** * Set a new block type to highlight * @param hlBlock */ public void highlightBlock(Block hlBlock) { worldRenderer.highlightBlock(hlBlock); if (worldRenderer.isHighlightEnabled()) getMap().redraw(); } /** * Set a new highlight color * @param newColor */ public void setHighlightColor(Color newColor) { worldRenderer.setHighlightColor(newColor); if (worldRenderer.isHighlightEnabled()) getMap().redraw(); } /** * @return The name of the current world */ public String getWorldName() { return world.levelName(); } /** * Export the selected chunks to a zip file * @param targetFile * @param progress */ public synchronized void exportZip(File targetFile, ProgressPanel progress) { if (!progress.isBusy()) { if (targetFile.exists()) { Object[] options = {Messages.getString("Chunky.Cancel_lbl"), //$NON-NLS-1$ Messages.getString("Chunky.AcceptOverwrite_lbl")}; //$NON-NLS-1$ int n = JOptionPane.showOptionDialog(null, String.format(Messages.getString("Chunky.Confirm_overwrite_msg"), //$NON-NLS-1$ targetFile.getName()), Messages.getString("Chunky.Confirm_overwrite_title"), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (n != 1) return; } new ZipExportJob(world, chunkSelection.getSelection(), targetFile, progress).start(); } } /** * Render the current view to a PNG image * @param targetFile * @param progress */ public void renderView(File targetFile, ProgressPanel progress) { if (!progress.isBusy()) { if (targetFile.exists()) { Object[] options = {Messages.getString("Chunky.Cancel_lbl"), //$NON-NLS-1$ Messages.getString("Chunky.AcceptOverwrite_lbl")}; //$NON-NLS-1$ int n = JOptionPane.showOptionDialog(null, String.format(Messages.getString("Chunky.Confirm_overwrite_msg"), //$NON-NLS-1$ targetFile.getName()), Messages.getString("Chunky.Confirm_overwrite_title"), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (n != 1) return; } if (progress.tryStartJob()) { progress.setJobName("PNG export"); progress.setJobSize(1); getMap().renderPng(targetFile); progress.finishJob(); } } } /** * @return The current world */ public World getWorld() { return world; } /** * @return The currently selected chunks */ public Collection<ChunkPosition> getSelectedChunks() { return chunkSelection.getSelection(); } /** * @return <code>true</code> if the Shift key is pressed */ public boolean getShiftModifier() { return shiftModifier; } /** * @return <code>true</code> if the Ctrl key is pressed */ public boolean getCtrlModifier() { return ctrlModifier; } /** * Select chunks within a rectangle * @param cx0 * @param cx1 * @param cz0 * @param cz1 */ public void selectChunks(int cx0, int cx1, int cz0, int cz1) { if (!ctrlModifier) chunkSelection.selectChunks(world, cx0, cz0, cx1, cz1); else chunkSelection.deselectChunks(world, cx0, cz0, cx1, cz1); getControls().setChunksSelected(chunkSelection.numSelectedChunks() > 0); } /** * @return The Controls UI element */ public Controls getControls() { return frame.getControls(); } /** * @return The chunk selection tracker */ public ChunkSelectionTracker getChunkSelection() { return chunkSelection; } /** * @return The world renderer */ public WorldRenderer getWorldRenderer() { return worldRenderer; } /** * Update the Ctrl key modifier * @param value */ public void setCtrlModifier(boolean value) { ctrlModifier = value; } /** * Update the Shift key modifier * @param value */ public void setShiftModifier(boolean value) { shiftModifier = value; } /** * @return The main Chunky frame UI element */ public ChunkyFrame getFrame() { return frame; } /** * @return The main chunk map */ public ChunkMap getMap() { return frame.getMap(); } /** * @return The current map renderer */ public Renderer getChunkRenderer() { return chunkRenderer; } /** * @return The minimap UI element */ public Minimap getMinimap() { return frame.getMinimap(); } @Override public void chunksDiscovered(Collection<Chunk> chunks) { for (Chunk chunk: chunks) { if (map.shouldPreload(chunk)) chunkParser.addChunk(chunk); } } /** * @return <code>true</code> if chunks or regions are currently being parsed */ public boolean isLoading() { return chunkParser.isWorking() || regionParser.isWorking(); } /** * Modify the block scale of the map view * @param blockScale */ public synchronized void setScale(int blockScale) { int scaleNew = Math.max(BLOCK_SCALE_MIN, Math.min(BLOCK_SCALE_MAX, blockScale)); scaleNew = scaleNew == 0 ? 1 : scaleNew*16; if (scaleNew != chunkScale) { chunkScale = scaleNew; getControls().setScale(getScale()); setView(map.x, map.z); } } /** * @return The current block scale of the map view */ public int getScale() { return chunkScale/16; } /** * Called when the map view has been dragged by the user * @param dx * @param dy */ public void viewDragged(int dx, int dy) { moveView(dx / (double) chunkScale, dy / (double) chunkScale); } /** * Move the map view * @param dx * @param dz */ public synchronized void moveView(double dx, double dz) { setView(map.x + dx, map.z + dz); } /** * @return The current map view */ public ChunkView getMapView() { return map; } /** * Called when the map has been resized * @param width * @param height */ public void mapResized(int width, int height) { if (width != mapWidth || height != mapHeight) { mapWidth = width; mapHeight = height; setView(map.x, map.z); } } /** * Called when the user has moved the mouse wheel * @param diff */ public synchronized void onMouseWheelMotion(int diff) { if (!ctrlModifier) { setLayer(getLayer() + diff); } else { setScale(getScale() - diff); } } /** * @return The current minimap view */ public ChunkView getMinimapView() { return minimap; } /** * Called when the minimap has been resized * @param width * @param height */ public void minimapResized(int width, int height) { if (width != minimapWidth || height != minimapHeight) { minimapWidth = width; minimapHeight = height; viewUpdated(); } } /** * @return The minecraft.jar of the local Minecraft installation */ public static final File getMinecraftJar() { return new File(Chunky.getMinecraftDirectory(), "bin/minecraft.jar"); } /** * Show the scene selector dialog. */ public void loadScene() { if (renderControls == null || !renderControls.isDisplayable()) { File sceneDir = SceneDirectoryPicker.getSceneDirectory(frame); if (sceneDir != null) { RenderContext context = new RenderContext(sceneDir, getControls().getNumThreads(), tileWidth); SceneSelector sceneSelector = new SceneSelector(null, context); sceneSelector.setLocationRelativeTo(frame); if (sceneSelector.isAccepted()) { String scene = sceneSelector.getSelectedScene(); renderControls = new RenderControls(Chunky.this, context); renderControls.loadScene(scene); } } } else { SceneSelector sceneSelector = new SceneSelector(null, renderControls.getContext()); sceneSelector.setLocationRelativeTo(frame); if (sceneSelector.isAccepted()) { String scene = sceneSelector.getSelectedScene(); renderControls.loadScene(scene); } } } /** * Open the OpenCL test renderer */ public void openCLTestRenderer() { new CLDeviceSelector(getFrame(), getWorld(), getSelectedChunks()); } /** * Benchmark the path tracing renderer. */ public void runBenchmark() { RenderContext context = new RenderContext(null, getControls().getNumThreads(), tileWidth); new BenchmarkDialog(getFrame(), context); } }
true
true
public int run(String[] args) { boolean selectedWorld = false; File sceneDir = ProgramProperties.getPreferredSceneDirectory(); String sceneName = null; String texturePack = null; int renderThreads = Runtime.getRuntime().availableProcessors(); File worldDir = null; boolean doBench = false; for (int i = 0; i < args.length; ++i) { if (args[i].equals("-texture") && args.length > i+1) { texturePack = args[++i]; } else if (args[i].equals("-watermark")) { RenderManager.useWatermark = true; } else if (args[i].equals("-scene-dir")) { sceneDir = new File(args[++i]); } else if (args[i].equals("-render")) { sceneName = args[++i]; } else if (args[i].equals("-benchmark")) { doBench = true; } else if (args[i].equals("-threads")) { renderThreads = Math.max(1, Integer.parseInt(args[++i])); } else if (args[i].equals("-tileWidth")) { tileWidth = Math.max(1, Integer.parseInt(args[++i])); } else if (args[i].equals("-opencl")) { openCLEnabled = true; } else if (args[i].equals("-h") || args[i].equals("-?") || args[i].equals("-help") || args[i].equals("--help")) { System.out.println(USAGE); return 0; } else if (!args[i].startsWith("-") && !selectedWorld) { worldDir = new File(args[i]); } else { System.err.println("Unrecognised argument: "+args[i]); System.err.println(USAGE); return 1; } } if (texturePack != null) { TexturePackLoader.loadTexturePack(new File(texturePack), false); } else { String lastTexturePack = ProgramProperties.getProperty("lastTexturePack"); if (lastTexturePack != null) TexturePackLoader.loadTexturePack(new File(lastTexturePack), false); else TexturePackLoader.loadTexturePack(getMinecraftJar(), false); } if (doBench) { doBenchmark(renderThreads); return 0; } if (sceneName != null) { // start headless mode System.setProperty("java.awt.headless", "true"); RenderContext renderContext = new RenderContext(sceneDir, renderThreads, tileWidth); RenderManager renderManager = new RenderManager( new PlaceholderRenderCanvas(), renderContext, new ConsoleRenderListener()); renderManager.start(); try { renderManager.loadScene(sceneName); if (!renderManager.scene().pathTrace()) { renderManager.scene().startRender(); } else { renderManager.scene().resumeRender(); } } catch (IOException e) { logger.error("IO error while loading scene", e); } catch (SceneLoadingError e) { logger.error("Scene loading error", e); } catch (InterruptedException e) { logger.error("Interrupted while loading scene", e); } return 0; } // load the world if (worldDir != null && World.isWorldDir(worldDir)) { loadWorld(new World(worldDir, false)); } else { String lastWorld = ProgramProperties.getProperty("lastWorld"); File lastWorldDir = lastWorld != null ? new File(lastWorld) : null; if (lastWorldDir != null && World.isWorldDir(lastWorldDir)) { loadWorld(new World(lastWorldDir, false)); } } // Start the worker threads chunkParser.start(); regionParser.start(); // Create UI in the event dispatch thread try { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { logger.warn("Failed to set native Look and Feel"); } SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { buildUI(); } }); } catch (InterruptedException e) { logger.fatal("Failed to initialize UI", e); } catch (InvocationTargetException e) { logger.fatal("Failed to initialize UI", e); } refreshLoop(); return 0; }
public int run(String[] args) { boolean selectedWorld = false; File sceneDir = ProgramProperties.getPreferredSceneDirectory(); String sceneName = null; String texturePack = null; int renderThreads = Runtime.getRuntime().availableProcessors(); File worldDir = null; boolean doBench = false; for (int i = 0; i < args.length; ++i) { if (args[i].equals("-texture") && args.length > i+1) { texturePack = args[++i]; } else if (args[i].equals("-watermark")) { RenderManager.useWatermark = true; } else if (args[i].equals("-scene-dir")) { sceneDir = new File(args[++i]); } else if (args[i].equals("-render")) { sceneName = args[++i]; } else if (args[i].equals("-benchmark")) { doBench = true; } else if (args[i].equals("-threads")) { renderThreads = Math.max(1, Integer.parseInt(args[++i])); } else if (args[i].equals("-tile-width")) { tileWidth = Math.max(1, Integer.parseInt(args[++i])); } else if (args[i].equals("-opencl")) { openCLEnabled = true; } else if (args[i].equals("-h") || args[i].equals("-?") || args[i].equals("-help") || args[i].equals("--help")) { System.out.println(USAGE); return 0; } else if (!args[i].startsWith("-") && !selectedWorld) { worldDir = new File(args[i]); } else { System.err.println("Unrecognised argument: "+args[i]); System.err.println(USAGE); return 1; } } if (texturePack != null) { TexturePackLoader.loadTexturePack(new File(texturePack), false); } else { String lastTexturePack = ProgramProperties.getProperty("lastTexturePack"); if (lastTexturePack != null) TexturePackLoader.loadTexturePack(new File(lastTexturePack), false); else TexturePackLoader.loadTexturePack(getMinecraftJar(), false); } if (doBench) { doBenchmark(renderThreads); return 0; } if (sceneName != null) { // start headless mode System.setProperty("java.awt.headless", "true"); RenderContext renderContext = new RenderContext(sceneDir, renderThreads, tileWidth); RenderManager renderManager = new RenderManager( new PlaceholderRenderCanvas(), renderContext, new ConsoleRenderListener()); renderManager.start(); try { renderManager.loadScene(sceneName); if (!renderManager.scene().pathTrace()) { renderManager.scene().startRender(); } else { renderManager.scene().resumeRender(); } } catch (IOException e) { logger.error("IO error while loading scene", e); } catch (SceneLoadingError e) { logger.error("Scene loading error", e); } catch (InterruptedException e) { logger.error("Interrupted while loading scene", e); } return 0; } // load the world if (worldDir != null && World.isWorldDir(worldDir)) { loadWorld(new World(worldDir, false)); } else { String lastWorld = ProgramProperties.getProperty("lastWorld"); File lastWorldDir = lastWorld != null ? new File(lastWorld) : null; if (lastWorldDir != null && World.isWorldDir(lastWorldDir)) { loadWorld(new World(lastWorldDir, false)); } } // Start the worker threads chunkParser.start(); regionParser.start(); // Create UI in the event dispatch thread try { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { logger.warn("Failed to set native Look and Feel"); } SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { buildUI(); } }); } catch (InterruptedException e) { logger.fatal("Failed to initialize UI", e); } catch (InvocationTargetException e) { logger.fatal("Failed to initialize UI", e); } refreshLoop(); return 0; }
diff --git a/src/org/eclipse/jface/bindings/keys/SWTKeySupport.java b/src/org/eclipse/jface/bindings/keys/SWTKeySupport.java index 76087f34..1ea239a9 100644 --- a/src/org/eclipse/jface/bindings/keys/SWTKeySupport.java +++ b/src/org/eclipse/jface/bindings/keys/SWTKeySupport.java @@ -1,247 +1,247 @@ /******************************************************************************* * Copyright (c) 2004, 2005 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.jface.bindings.keys; import org.eclipse.jface.bindings.keys.formatting.IKeyFormatter; import org.eclipse.jface.bindings.keys.formatting.NativeKeyFormatter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Event; /** * <p> * A utility class for converting SWT events into key strokes. * </p> * <p> * <em>EXPERIMENTAL</em>. The commands architecture is currently under * development for Eclipse 3.1. This class -- its existence, its name and its * methods -- are in flux. Do not use this class yet. * </p> * * @since 3.1 */ public final class SWTKeySupport { /** * A formatter that displays key sequences in a style native to the * platform. */ private static final IKeyFormatter NATIVE_FORMATTER = new NativeKeyFormatter(); /** * Given an SWT accelerator value, provide the corresponding key stroke. * * @param accelerator * The accelerator to convert; should be a valid SWT accelerator * value. * @return The equivalent key stroke; never <code>null</code>. */ public static final KeyStroke convertAcceleratorToKeyStroke(int accelerator) { final int modifierKeys = accelerator & SWT.MODIFIER_MASK; final int naturalKey; if (accelerator == modifierKeys) { - naturalKey = Integer.MIN_VALUE; + naturalKey = KeyStroke.NO_KEY; } else { naturalKey = accelerator - modifierKeys; } return KeyStroke.getInstance(modifierKeys, naturalKey); } /** * <p> * Converts the given event into an SWT accelerator value -- considering the * modified character with the shift modifier. This is the third accelerator * value that should be checked. * </p> * <p> * For example, on a standard US keyboard, "Ctrl+Shift+5" would be viewed as * "Ctrl+Shift+%". * </p> * * @param event * The event to be converted; must not be <code>null</code>. * @return The combination of the state mask and the unmodified character. */ public static final int convertEventToModifiedAccelerator(final Event event) { int modifiers = event.stateMask & SWT.MODIFIER_MASK; char character = topKey(event); return modifiers + toUpperCase(character); } /** * <p> * Converts the given event into an SWT accelerator value -- considering the * unmodified character with all modifier keys. This is the first * accelerator value that should be checked. However, all alphabetic * characters are considered as their uppercase equivalents. * </p> * <p> * For example, on a standard US keyboard, "Ctrl+Shift+5" would be viewed as * "Ctrl+Shift+5". * </p> * * @param event * The event to be converted; must not be <code>null</code>. * @return The combination of the state mask and the unmodified character. */ public static final int convertEventToUnmodifiedAccelerator( final Event event) { return convertEventToUnmodifiedAccelerator(event.stateMask, event.keyCode); } /** * <p> * Converts the given state mask and key code into an SWT accelerator value -- * considering the unmodified character with all modifier keys. All * alphabetic characters are considered as their uppercase equivalents. * </p> * <p> * For example, on a standard US keyboard, "Ctrl+Shift+5" would be viewed as * "Ctrl+Shift+5". * </p> * * @param stateMask * The integer mask of modifiers keys depressed when this was * pressed. * @param keyCode * The key that was pressed, before being modified. * @return The combination of the state mask and the unmodified character. */ private static final int convertEventToUnmodifiedAccelerator( final int stateMask, final int keyCode) { int modifiers = stateMask & SWT.MODIFIER_MASK; int character = keyCode; return modifiers + toUpperCase(character); } /** * <p> * Converts the given event into an SWT accelerator value -- considering the * unmodified character with all modifier keys. This is the first * accelerator value that should be checked. However, all alphabetic * characters are considered as their uppercase equivalents. * </p> * <p> * For example, on a standard US keyboard, "Ctrl+Shift+5" would be viewed as * "Ctrl+%". * </p> * * @param event * The event to be converted; must not be <code>null</code>. * @return The combination of the state mask and the unmodified character. */ public static final int convertEventToUnmodifiedAccelerator( final KeyEvent event) { return convertEventToUnmodifiedAccelerator(event.stateMask, event.keyCode); } /** * Converts the given event into an SWT accelerator value -- considering the * modified character without the shift modifier. This is the second * accelerator value that should be checked. Key strokes with alphabetic * natural keys are run through * <code>convertEventToUnmodifiedAccelerator</code> * * @param event * The event to be converted; must not be <code>null</code>. * @return The combination of the state mask without shift, and the modified * character. */ public static final int convertEventToUnshiftedModifiedAccelerator( final Event event) { // Disregard alphabetic key strokes. if (Character.isLetter((char) event.keyCode)) { return convertEventToUnmodifiedAccelerator(event); } int modifiers = event.stateMask & (SWT.MODIFIER_MASK ^ SWT.SHIFT); char character = topKey(event); return modifiers + toUpperCase(character); } /** * Given a key stroke, this method provides the equivalent SWT accelerator * value. The functional inverse of * <code>convertAcceleratorToKeyStroke</code>. * * @param keyStroke * The key stroke to convert; must not be <code>null</code>. * @return The SWT accelerator value */ public static final int convertKeyStrokeToAccelerator( final KeyStroke keyStroke) { return keyStroke.getModifierKeys() + keyStroke.getNaturalKey(); } /** * Provides an instance of <code>IKeyFormatter</code> appropriate for the * current instance. * * @return an instance of <code>IKeyFormatter</code> appropriate for the * current instance; never <code>null</code>. */ public static IKeyFormatter getKeyFormatterForPlatform() { return NATIVE_FORMATTER; } /** * Makes sure that a fully-modified character is converted to the normal * form. This means that "Ctrl+" key strokes must reverse the modification * caused by control-escaping. Also, all lower case letters are converted to * uppercase. * * @param event * The event from which the fully-modified character should be * pulled. * @return The modified character, uppercase and without control-escaping. */ private static final char topKey(final Event event) { char character = event.character; boolean ctrlDown = (event.stateMask & SWT.CTRL) != 0; if (ctrlDown && event.character != event.keyCode && event.character < 0x20) character += 0x40; return character; } /** * Makes the given character uppercase if it is a letter. * * @param keyCode * The character to convert. * @return The uppercase equivalent, if any; otherwise, the character * itself. */ private static final int toUpperCase(int keyCode) { // Will this key code be truncated? if (keyCode > 0xFFFF) { return keyCode; } // Downcast in safety. Only make characters uppercase. final char character = (char) keyCode; return Character.isLetter(character) ? Character.toUpperCase(character) : keyCode; } /** * This class should never be instantiated. */ protected SWTKeySupport() { // This class should never be instantiated. } }
true
true
public static final KeyStroke convertAcceleratorToKeyStroke(int accelerator) { final int modifierKeys = accelerator & SWT.MODIFIER_MASK; final int naturalKey; if (accelerator == modifierKeys) { naturalKey = Integer.MIN_VALUE; } else { naturalKey = accelerator - modifierKeys; } return KeyStroke.getInstance(modifierKeys, naturalKey); }
public static final KeyStroke convertAcceleratorToKeyStroke(int accelerator) { final int modifierKeys = accelerator & SWT.MODIFIER_MASK; final int naturalKey; if (accelerator == modifierKeys) { naturalKey = KeyStroke.NO_KEY; } else { naturalKey = accelerator - modifierKeys; } return KeyStroke.getInstance(modifierKeys, naturalKey); }
diff --git a/src/com/itmill/toolkit/tests/TestForWindowOpen.java b/src/com/itmill/toolkit/tests/TestForWindowOpen.java index 8588630bb..63a15f6ae 100644 --- a/src/com/itmill/toolkit/tests/TestForWindowOpen.java +++ b/src/com/itmill/toolkit/tests/TestForWindowOpen.java @@ -1,54 +1,55 @@ package com.itmill.toolkit.tests; import com.itmill.toolkit.terminal.ExternalResource; import com.itmill.toolkit.ui.Button; import com.itmill.toolkit.ui.CustomComponent; import com.itmill.toolkit.ui.OrderedLayout; import com.itmill.toolkit.ui.Button.ClickEvent; public class TestForWindowOpen extends CustomComponent { public TestForWindowOpen() { OrderedLayout main = new OrderedLayout(); setCompositionRoot(main); main.addComponent(new Button("Open in this window", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r); } })); - main.addComponent(new Button("Open in target \"asd\"", + main.addComponent(new Button("Open in target \"mytarget\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); - getApplication().getMainWindow().open(r, "asd"); + getApplication().getMainWindow().open(r, "mytarget"); } })); - main.addComponent(new Button("Open in target \"foo\"", + main.addComponent(new Button("Open in target \"secondtarget\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); - getApplication().getMainWindow().open(r, "foo"); + getApplication().getMainWindow() + .open(r, "secondtarget"); } })); } }
false
true
public TestForWindowOpen() { OrderedLayout main = new OrderedLayout(); setCompositionRoot(main); main.addComponent(new Button("Open in this window", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r); } })); main.addComponent(new Button("Open in target \"asd\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r, "asd"); } })); main.addComponent(new Button("Open in target \"foo\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r, "foo"); } })); }
public TestForWindowOpen() { OrderedLayout main = new OrderedLayout(); setCompositionRoot(main); main.addComponent(new Button("Open in this window", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r); } })); main.addComponent(new Button("Open in target \"mytarget\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow().open(r, "mytarget"); } })); main.addComponent(new Button("Open in target \"secondtarget\"", new Button.ClickListener() { public void buttonClick(ClickEvent event) { ExternalResource r = new ExternalResource( "http://www.google.com"); getApplication().getMainWindow() .open(r, "secondtarget"); } })); }
diff --git a/tomcat-main/src/test/java/org/collectionspace/chain/csp/webui/main/TestUISpecs.java b/tomcat-main/src/test/java/org/collectionspace/chain/csp/webui/main/TestUISpecs.java index 6bc4719d..2c706b6f 100644 --- a/tomcat-main/src/test/java/org/collectionspace/chain/csp/webui/main/TestUISpecs.java +++ b/tomcat-main/src/test/java/org/collectionspace/chain/csp/webui/main/TestUISpecs.java @@ -1,114 +1,115 @@ package org.collectionspace.chain.csp.webui.main; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.collectionspace.bconfigutils.bootstrap.BootstrapConfigController; import org.collectionspace.chain.controller.ChainServlet; import org.collectionspace.chain.util.json.JSONUtils; import org.json.JSONObject; import org.junit.Test; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.testing.HttpTester; import org.mortbay.jetty.testing.ServletTester; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestUISpecs { private static final Logger log=LoggerFactory.getLogger(TestUISpecs.class); private static String cookie; // XXX refactor protected InputStream getResource(String name) { String path=getClass().getPackage().getName().replaceAll("\\.","/")+"/"+name; return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); } // XXX refactor private String getResourceString(String name) throws IOException { InputStream in=getResource(name); return IOUtils.toString(in); } private static void login(ServletTester tester) throws IOException, Exception { HttpTester out=jettyDo(tester,"GET","/chain/[email protected]&password=testtest",null); assertEquals(303,out.getStatus()); cookie=out.getHeader("Set-Cookie"); log.debug("Got cookie "+cookie); } // XXX refactor into other copy of this method private ServletTester setupJetty() throws Exception { BootstrapConfigController config_controller=new BootstrapConfigController(null); config_controller.addSearchSuffix("test-config-loader2.xml"); config_controller.go(); String base=config_controller.getOption("services-url"); ServletTester tester=new ServletTester(); tester.setContextPath("/chain"); tester.addServlet(ChainServlet.class, "/*"); tester.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/"); tester.setAttribute("storage","service"); tester.setAttribute("store-url",base+"/cspace-services/"); tester.setAttribute("config-filename","default.xml"); tester.start(); login(tester); return tester; } private static HttpTester jettyDo(ServletTester tester,String method,String path,String data) throws IOException, Exception { HttpTester request = new HttpTester(); HttpTester response = new HttpTester(); request.setMethod(method); request.setHeader("Host","tester"); request.setURI(path); request.setVersion("HTTP/1.0"); if(data!=null) request.setContent(data); if(cookie!=null) request.addHeader(HttpHeaders.COOKIE,cookie); response.parse(tester.getResponses(request.generate())); return response; } private void uispec(ServletTester jetty, String url, String uijson) throws Exception { HttpTester response; JSONObject generated; JSONObject comparison; response=jettyDo(jetty,"GET",url,null); assertEquals(200,response.getStatus()); generated=new JSONObject(response.getContent()); comparison=new JSONObject(getResourceString(uijson)); log.info(response.getContent()); log.info(comparison.toString()); log.info(generated.toString()); assertTrue("Failed to create correct uispec for "+url,JSONUtils.checkJSONEquivOrEmptyStringKey(generated,comparison)); } @Test public void testUISpec() throws Exception { ServletTester jetty=setupJetty(); - uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); +/* uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/objects/uispec","collection-object.uispec"); uispec(jetty,"/chain/object-tab/uispec","object-tab.uispec"); uispec(jetty,"/chain/intake/uispec","intake.uispec"); uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/loanout/uispec","loanout.uispec"); uispec(jetty,"/chain/person/uispec","person.uispec"); uispec(jetty,"/chain/organization/uispec","organization-authority.uispec"); uispec(jetty,"/chain/loanin/uispec","loanin.uispec"); uispec(jetty,"/chain/users/uispec","users.uispec"); uispec(jetty,"/chain/role/uispec","roles.uispec"); uispec(jetty,"/chain/permission/uispec","permissions.uispec"); uispec(jetty,"/chain/permrole/uispec","permroles.uispec"); uispec(jetty,"/chain/movement/uispec","movement.uispec"); + */ uispec(jetty,"/chain/find-edit/uispec","find-edit.uispec"); } }
false
true
@Test public void testUISpec() throws Exception { ServletTester jetty=setupJetty(); uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/objects/uispec","collection-object.uispec"); uispec(jetty,"/chain/object-tab/uispec","object-tab.uispec"); uispec(jetty,"/chain/intake/uispec","intake.uispec"); uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/loanout/uispec","loanout.uispec"); uispec(jetty,"/chain/person/uispec","person.uispec"); uispec(jetty,"/chain/organization/uispec","organization-authority.uispec"); uispec(jetty,"/chain/loanin/uispec","loanin.uispec"); uispec(jetty,"/chain/users/uispec","users.uispec"); uispec(jetty,"/chain/role/uispec","roles.uispec"); uispec(jetty,"/chain/permission/uispec","permissions.uispec"); uispec(jetty,"/chain/permrole/uispec","permroles.uispec"); uispec(jetty,"/chain/movement/uispec","movement.uispec"); uispec(jetty,"/chain/find-edit/uispec","find-edit.uispec"); }
@Test public void testUISpec() throws Exception { ServletTester jetty=setupJetty(); /* uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/objects/uispec","collection-object.uispec"); uispec(jetty,"/chain/object-tab/uispec","object-tab.uispec"); uispec(jetty,"/chain/intake/uispec","intake.uispec"); uispec(jetty,"/chain/acquisition/uispec","acquisition.uispec"); uispec(jetty,"/chain/loanout/uispec","loanout.uispec"); uispec(jetty,"/chain/person/uispec","person.uispec"); uispec(jetty,"/chain/organization/uispec","organization-authority.uispec"); uispec(jetty,"/chain/loanin/uispec","loanin.uispec"); uispec(jetty,"/chain/users/uispec","users.uispec"); uispec(jetty,"/chain/role/uispec","roles.uispec"); uispec(jetty,"/chain/permission/uispec","permissions.uispec"); uispec(jetty,"/chain/permrole/uispec","permroles.uispec"); uispec(jetty,"/chain/movement/uispec","movement.uispec"); */ uispec(jetty,"/chain/find-edit/uispec","find-edit.uispec"); }
diff --git a/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LArcView.java b/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LArcView.java index 0e452128..a228f3e5 100644 --- a/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LArcView.java +++ b/LaTeXDraw/src/net/sf/latexdraw/glib/views/Java2D/impl/LArcView.java @@ -1,125 +1,127 @@ package net.sf.latexdraw.glib.views.Java2D.impl; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Path2D; import net.sf.latexdraw.glib.models.interfaces.IArc; import net.sf.latexdraw.glib.views.Java2D.interfaces.IViewArc; import net.sf.latexdraw.util.LNumber; /** * Defines a view of the IArc model.<br> * <br> * This file is part of LaTeXDraw.<br> * Copyright (c) 2005-2012 Arnaud BLOUIN<br> * <br> * LaTeXDraw 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. * <br> * LaTeXDraw is distributed 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.<br> * <br> * 03/20/2008<br> * @author Arnaud BLOUIN * @since 3.0 */ class LArcView<M extends IArc> extends LEllipseView<IArc> implements IViewArc { /** * Creates an initialises the Java view of a LArc. * @param model The model to view. * @since 3.0 */ protected LArcView(final IArc model) { super(model); update(); } @Override protected void setRectangularShape(final Path2D path, final double tlx, final double tly, final double width, final double height) { setArcPath(path, tlx, tly, width, height, shape.getAngleStart(), shape.getAngleEnd(), getJava2DArcStyle()); } @Override public void updateBorder() { final Shape sh = LNumber.INSTANCE.equals(shape.getRotationAngle(), 0.) ? path : getRotatedShape2D(); border.setFrame(getStroke().createStrokedShape(sh).getBounds2D()); } protected int getJava2DArcStyle() { switch(shape.getArcStyle()) { case ARC : return Arc2D.OPEN; case CHORD : return Arc2D.CHORD; case WEDGE : return Arc2D.PIE; } return -1; } /** * Appends an arc to the given path. * @param path The path to fill. * @param tlx The top-left point of the arc. * @param tly The bottom right point of the arc. * @param width The width of the arc. * @param height The height of the arc. * @param startAngle The start angle of the arc. * @param endAngle The end angle of the arc. * @param style The style of the arc. See Arc2D.OPEN etc. * @since 3.0 */ public static void setArcPath(final Path2D path, final double tlx, final double tly, final double width, final double height, final double startAngle, final double endAngle, final int style) { if(path!=null) { + final double w2 = Math.max(1., width); + final double h2 = Math.max(1., height); double sAngle = Math.toDegrees(startAngle%(Math.PI*2.)); double eAngle = Math.toDegrees(endAngle%(Math.PI*2.)); if(LNumber.INSTANCE.equals(sAngle, eAngle)) eAngle += 0.1; - path.append(new Arc2D.Double(tlx, tly, width, height, sAngle<eAngle ? sAngle : eAngle, eAngle>sAngle ? eAngle-sAngle : sAngle-eAngle, style), false); + path.append(new Arc2D.Double(tlx, tly, w2, h2, sAngle<eAngle ? sAngle : eAngle, eAngle>sAngle ? eAngle-sAngle : sAngle-eAngle, style), false); } } // // /** // * Sets the starting or ending angle of the arc. // * @param isStartAngle True: the starting angle will be set. Otherwise it is the ending angle. // * @param pos The new position of the angle. // * @since 3.0 // */ // public void setAngle(boolean isStartAngle, IPoint pos) // { // if(!GLibUtilities.INSTANCE.isValidPoint(pos)) // return ; // // IArc arc = (IArc)shape; // // ILine line = new LLine(arc.getGravityCentre(), pos); // IPoint[] inters = arc.getIntersection(line); // // if(inters==null) // return ; // // IPoint inter = inters.length==1 ? inters[0] : // inters[0].distance(pos)<inters[1].distance(pos) ? inters[0] : inters[1]; // // double angle = Math.acos((inter.getX()-arc.getGravityCentre().getX())/arc.getA()); // // if(pos.getY()>arc.getGravityCentre().getY()) // angle = 2*Math.PI - angle; // // if(isStartAngle) // arc.setAngleStart(angle); // else // arc.setAngleEnd(angle); // // update(); // } }
false
true
public static void setArcPath(final Path2D path, final double tlx, final double tly, final double width, final double height, final double startAngle, final double endAngle, final int style) { if(path!=null) { double sAngle = Math.toDegrees(startAngle%(Math.PI*2.)); double eAngle = Math.toDegrees(endAngle%(Math.PI*2.)); if(LNumber.INSTANCE.equals(sAngle, eAngle)) eAngle += 0.1; path.append(new Arc2D.Double(tlx, tly, width, height, sAngle<eAngle ? sAngle : eAngle, eAngle>sAngle ? eAngle-sAngle : sAngle-eAngle, style), false); } }
public static void setArcPath(final Path2D path, final double tlx, final double tly, final double width, final double height, final double startAngle, final double endAngle, final int style) { if(path!=null) { final double w2 = Math.max(1., width); final double h2 = Math.max(1., height); double sAngle = Math.toDegrees(startAngle%(Math.PI*2.)); double eAngle = Math.toDegrees(endAngle%(Math.PI*2.)); if(LNumber.INSTANCE.equals(sAngle, eAngle)) eAngle += 0.1; path.append(new Arc2D.Double(tlx, tly, w2, h2, sAngle<eAngle ? sAngle : eAngle, eAngle>sAngle ? eAngle-sAngle : sAngle-eAngle, style), false); } }
diff --git a/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java b/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java index b928c1eeb2..2eef5fd65c 100644 --- a/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java +++ b/main/src/main/java/org/vfny/geoserver/servlets/AbstractService.java @@ -1,978 +1,981 @@ /* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.vfny.geoserver.servlets; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.Reader; import java.net.SocketException; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.web.context.WebApplicationContext; import org.vfny.geoserver.ExceptionHandler; import org.vfny.geoserver.Request; import org.vfny.geoserver.Response; import org.vfny.geoserver.ServiceException; import org.vfny.geoserver.global.Data; import org.vfny.geoserver.global.GeoServer; import org.vfny.geoserver.global.Service; import org.vfny.geoserver.util.PartialBufferedOutputStream; import org.vfny.geoserver.util.requests.XmlCharsetDetector; import org.vfny.geoserver.util.requests.readers.KvpRequestReader; import org.vfny.geoserver.util.requests.readers.XmlRequestReader; /** * Represents a service that all others extend from. Subclasses should provide * response and exception handlers as appropriate. * * <p> * It is <b>really</b> important to adhere to the following workflow: * * <ol> * <li> * get a Request reader * </li> * <li> * ask the Request Reader for the Request object * </li> * <li> * Provide the resulting Request with the ServletRequest that generated it * </li> * <li> * get the appropiate ResponseHandler * </li> * <li> * ask it to execute the Request * </li> * <li> * set the response content type * </li> * <li> * write to the http response's output stream * </li> * <li> * pending - call Response cleanup * </li> * </ol> * </p> * * <p> * If anything goes wrong a ServiceException can be thrown and will be written * to the output stream instead. * </p> * * <p> * This is because we have to be sure that no exception have been produced * before setting the response's content type, so we can set the exception * specific content type; and that Response.getContentType is called AFTER * Response.execute, since the MIME type can depend on any request parameter * or another kind of desission making during the execute process. (i.e. * FORMAT in WMS GetMap) * </p> * * <p> * TODO: We need to call Response.abort() if anything goes wrong to allow the * Response a chance to cleanup after itself. * </p> * * @author Gabriel Rold?n * @author Chris Holmes * @author Jody Garnett, Refractions Research * @version $Id: AbstractService.java,v 1.23 2004/09/08 17:34:38 cholmesny Exp $ */ public abstract class AbstractService extends HttpServlet implements ApplicationContextAware { /** Class logger */ protected static Logger LOGGER = Logger.getLogger( "org.vfny.geoserver.servlets"); /** * Servivce group (maps to 'SERVICE' parameter in OGC service urls) */ String service; /** * Request type (maps to 'REQUEST' parameter in OGC service urls) */ String request; /** * Application context used to look up "Services" */ WebApplicationContext context; /** * Reference to the global geoserver instnace. */ GeoServer geoServer; /** * Reference to the catalog. */ Data catalog; /** * Id of the service strategy to use. */ String serviceStrategy; /** * buffer size to use when PARTIAL-BUFFER is being used */ int partialBufferSize; /** * Cached service strategy object */ // ServiceStrategy strategy; /** * Reference to the service */ Service serviceRef; private String kvpString; // /** DOCUMENT ME! */ // protected HttpServletRequest curRequest; /** * Constructor for abstract service. * * @param service The service group the service falls into (WFS,WMS,...) * @param request The service being requested (GetCapabilities, GetMap, ...) * @param serviceRef The global service this "servlet" falls into */ public AbstractService(String service, String request, Service serviceRef) { this.service = service; this.request = request; this.serviceRef = serviceRef; } /** * @return Returns the "service group" that this service falls into. */ public String getService() { return service; } /** * @return Returns the "request" this service maps to. */ public String getRequest() { return request; } /** * Sets a refeference to the global service instance. */ public void setServiceRef(Service serviceRef) { this.serviceRef = serviceRef; } /** * @return The reference to the global service instance. */ public Service getServiceRef() { return serviceRef; } /** * Sets the application context. * <p> * Used to process the {@link Service} extension point. * </p> */ public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = (WebApplicationContext) context; } /** * @return The application context. */ public WebApplicationContext getApplicationContext() { return context; } /** * Sets the reference to the global geoserver instance. */ public void setGeoServer(GeoServer geoServer) { this.geoServer = geoServer; } /** * @return the reference to the global geoserver instance. */ public GeoServer getGeoServer() { return geoServer; } /** * @return The reference to the global catalog instance. */ public Data getCatalog() { return catalog; } /** * Sets the reference to the global catalog instance. * */ public void setCatalog(Data catalog) { this.catalog = catalog; } /** * @return The id used to identify the service strategy to be used. * @see ServiceStrategy#getId() */ public String getServiceStrategy() { return serviceStrategy; } /** * Sets the id used to identify the service strategy to be used. */ public void setServiceStrategy(String serviceStrategy) { this.serviceStrategy = serviceStrategy; } /** * Determines if the service is enabled. * <p> * Subclass should override this method if the service can be turned on/off. * This implementation returns <code>true</code> * </p> */ protected boolean isServiceEnabled(HttpServletRequest req) { return true; } /** * Override and use spring set servlet context. */ public ServletContext getServletContext() { //override and use spring return ((WebApplicationContext)context).getServletContext(); } /** * DOCUMENT ME! * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // implements the main request/response logic // this.curRequest = request; Request serviceRequest = null; if (!isServiceEnabled(request)) { sendDisabledServiceError(response); return; } try { Map requestParams = new HashMap(); String qString = (this.kvpString != null ? this.kvpString : request.getQueryString()); LOGGER.fine("reading request: " + qString); if (this.kvpString != null) { requestParams = KvpRequestReader.parseKvpSet(qString); } else { String paramName; String paramValue; for (Enumeration pnames = request.getParameterNames(); pnames.hasMoreElements();) { paramName = (String) pnames.nextElement(); paramValue = request.getParameter(paramName); requestParams.put(paramName.toUpperCase(), paramValue); } } KvpRequestReader requestReader = getKvpReader(requestParams ); serviceRequest = requestReader.getRequest(request); LOGGER.finer("serviceRequest provided with HttpServletRequest: " + request); //serviceRequest.setHttpServletRequest(request); } catch (ServiceException se) { sendError(request, response, se); return; } catch (Throwable e) { sendError(request, response, e); return; } finally { this.kvpString = null; } doService(request, response, serviceRequest); } /** * Sends the standard disabled service error message (a 503 error followed by an english description). * @param response * @throws IOException */ protected void sendDisabledServiceError(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, getService() + " service is not enabled. " + "You can enable it in the web admin tool."); } /** * Performs the post method. Simply passes itself on to the three argument * doPost method, with null for the reader, because the * request.getReader() will not have been used if this servlet is called * directly. * * @param request DOCUMENT ME! * @param response DOCUMENT ME! * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response, null); } /** * Performs the post method. Gets the appropriate xml reader and * determines the request from that, and then passes the request on to * doService. * * @param request The request made. * @param response The response to be returned. * @param requestXml A reader of the xml to be read. This is only used by * the dispatcher, everyone else should just pass in null. This is * needed because afaik HttpServletRequest.getReader() can not be * used twice. So in a dispatched case we write it to a temp file, * which we can then read in twice. * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ public void doPost(HttpServletRequest request, HttpServletResponse response, Reader requestXml) throws ServletException, IOException { // this.curRequest = request; Request serviceRequest = null; //TODO: This isn't a proper ogc service response. if (!isServiceEnabled(request)) { sendDisabledServiceError(response); return; } // implements the main request/response logic try { XmlRequestReader requestReader = getXmlRequestReader(); //JD: GEOS-323, adding support for character encoding detection // Reader xml = (requestXml != null) ? requestXml : request.getReader(); Reader xml; if (null != requestXml) { xml = requestXml; } else { /* * `getCharsetAwareReader` returns a reader which not support * mark/reset. So it is a good idea to wrap it into BufferedReader. * In this case the below debug output will work. */ xml = new BufferedReader( XmlCharsetDetector.getCharsetAwareReader( request.getInputStream())); } //JD: GEOS-323 //DJB: add support for POST loggin if (LOGGER.isLoggable(Level.FINE)) { if (xml.markSupported()) { // a little protection for large POSTs (ie. updates) // for FINE, I assume people just want to see the "normal" ones - not the big ones // for FINER, I assume they would want to see a bit more // for FINEST, I assume they would want to see even more int maxChars = 16000; if (LOGGER.isLoggable(Level.FINER)) maxChars = 64000; if (LOGGER.isLoggable(Level.FINEST)) maxChars = 640000; // Bill gates says 640k is good enough for anyone xml.mark(maxChars+1); // +1 so if you read the whole thing you can still reset() char buffer[] = new char[maxChars]; int actualRead = xml.read(buffer); xml.reset(); LOGGER.fine("------------XML POST START-----------\n"+new String(buffer,0,actualRead)+"\n------------XML POST END-----------"); if (actualRead ==maxChars ) LOGGER.fine("------------XML POST REPORT WAS TRUNCATED AT "+maxChars+" CHARACTERS. RUN WITH HIGHER LOGGING LEVEL TO SEE MORE"); } else { LOGGER.fine("ATTEMPTED TO LOG POST XML, BUT WAS PREVENTED BECAUSE markSupported() IS FALSE"); } } serviceRequest = requestReader.read(xml, request); serviceRequest.setHttpServletRequest(request); } catch (ServiceException se) { sendError(request, response, se); return; } catch (Throwable e) { sendError(request, response, e); return; } doService(request, response, serviceRequest); } /** * Peforms service according to ServiceStrategy. * * <p> * This method has very strict requirements, please see the class * description for the specifics. * </p> * * <p> * It has a lot of try/catch blocks, but they are fairly necessary to * handle things correctly and to avoid as many ugly servlet responses, so * that everything is wrapped correctly. * </p> * * @param request The httpServlet of the request. * @param response The response to be returned. * @param serviceRequest The OGC request to service. * * @throws ServletException if the strategy can't be instantiated */ protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { sendDisabledServiceError(response); } catch(IOException e) { LOGGER.log(Level.WARNING, "Error writing service unavailable response", e); } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(request, response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(request, response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(request, response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(request, response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Encoding", encoding); } String disposition = serviceResponse.getContentDisposition(); if(disposition != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Disposition", disposition); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(request, response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error + response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned LOGGER.log(Level.SEVERE, "Error writing out " + ioException.getMessage(), ioException); serviceResponse.abort(s); strategy.abort(); sendError(request, response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure + response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned serviceResponse.abort(s); strategy.abort(); sendError(request, response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) + response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(request, response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); } /** * Gets the response class that should handle the request of this service. * All subclasses must implement. * <p> * This method is not abstract to support subclasses that use the * request-response mechanism. * </p> * * @return The response that the request read by this servlet should be * passed to. */ protected Response getResponseHandler() { return null; } /** * Gets a reader that will figure out the correct Key Vaule Pairs for this * service. * <p> * Subclasses should override to supply a specific kvp reader. Default * implementation returns <code>null</code> * </p> * @param params A map of the kvp pairs. * * @return An initialized KVP reader to decode the request. */ protected KvpRequestReader getKvpReader(Map params) { return null; } /** * Gets a reader that will handle a posted xml request for this servlet. * <p> * Subclasses should override to supply a specific xml reader. Default * implementation returns <code>null</code> * </p> * @return An XmlRequestReader appropriate to this service. */ protected XmlRequestReader getXmlRequestReader() { return null; } /** * Gets the exception handler for this service. * * @return The correct ExceptionHandler */ protected abstract ExceptionHandler getExceptionHandler(); /** * Gets the strategy for outputting the response. This method gets the * strategy from the serviceStrategy param in the web.xml file. This is * sort of odd behavior, as all other such parameters are set in the * services and catalog xml files, and this param may move there. But as * it is much more of a programmer configuration than a user * configuration there is no rush to move it. * * <p> * Subclasses may choose to override this method in order to get a strategy * more suited to their response. Currently only Transaction will do * this, since the commit is only called after writeTo, and it often * messes up, so we want to be able to see the error message (SPEED writes * the output directly, so errors in writeTo do not show up.) * </p> * * <p> * Most subclasses should not override, this method will most always return * the SPEED strategy, since it is the fastest response and should work * fine if everything is well tested. FILE and BUFFER should be used when * there are errors in writeTo methods of child classes, set by the * programmer in the web.xml file. * </p> * * @return The service strategy found in the web.xml serviceStrategy * parameter. The code that finds this is in the init method * * @throws ServiceException If the service strategy set in #init() is not * valid. * * @see #init() for the code that sets the serviceStrategy. */ protected ServiceStrategy createServiceStrategy() throws ServiceException { // If verbose exceptions is on then lets make sure they actually get the // exception by using the file strategy. ServiceStrategy theStrategy = null; if (geoServer.isVerboseExceptions()) { theStrategy = (ServiceStrategy) context .getBean("fileServiceStrategy"); } else { if (serviceStrategy == null) { // none set, look up in web applicatino context serviceStrategy = getServletContext().getInitParameter( "serviceStrategy"); } // do a lookup if(serviceStrategy != null) { Map strategies = context.getBeansOfType(ServiceStrategy.class); for (Iterator itr = strategies.values().iterator(); itr.hasNext();) { ServiceStrategy bean = (ServiceStrategy) itr.next(); if (bean.getId().equals(serviceStrategy)) { theStrategy = bean; break; } } } } if (theStrategy == null) { // default to buffer theStrategy = (ServiceStrategy) context.getBean("bufferServiceStrategy"); } // clone the strategy since at the moment the strategies are marked as singletons // in the web.xml file. try { theStrategy = (ServiceStrategy) theStrategy.clone(); } catch(CloneNotSupportedException e) { LOGGER.log(Level.SEVERE, "Programming error found, service strategies should be cloneable, " + e, e); throw new RuntimeException("Found a strategy that does not support cloning...", e); } // TODO: this hack should be removed once modules have their own config if (theStrategy instanceof PartialBufferStrategy) { if(partialBufferSize == 0) { String size = getServletContext().getInitParameter( "PARTIAL_BUFFER_STRATEGY_SIZE"); if(size != null) { try { partialBufferSize = Integer.valueOf(size).intValue(); if (partialBufferSize <= 0) { LOGGER .warning("Invalid partial buffer size, defaulting to " + PartialBufferedOutputStream.DEFAULT_BUFFER_SIZE + " (was " + partialBufferSize + ")"); partialBufferSize = 0; } } catch (NumberFormatException nfe) { LOGGER .warning("Invalid partial buffer size, defaulting to " + PartialBufferedOutputStream.DEFAULT_BUFFER_SIZE + " (was " + partialBufferSize + ")"); partialBufferSize = 0; } } } ((PartialBufferStrategy) theStrategy) .setBufferSize(partialBufferSize); } return theStrategy; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ protected String getMimeType() { ServletContext servContext = getServletContext(); try { return ((GeoServer) servContext.getAttribute("GeoServer")) .getMimeType(); } catch (NullPointerException e) { return "text/xml; charset=" + Charset.forName("UTF-8").displayName(); } } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param content DOCUMENT ME! */ protected void send(HttpServletResponse response, CharSequence content) { send(response, content, getMimeType()); } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param content DOCUMENT ME! * @param mimeType DOCUMENT ME! */ protected void send(HttpServletResponse response, CharSequence content, String mimeType) { try { response.setContentType(mimeType); response.getWriter().write(content.toString()); } catch (IOException ex) { //stream closed by client, do nothing LOGGER.fine(ex.getMessage()); } } /** * Send error produced during getService opperation. * * <p> * Some errors know how to write themselves out WfsTransactionException for * instance. It looks like this might be is handled by * getExceptionHandler().newServiceException( t, pre, null ). I still * would not mind seeing a check for ServiceConfig Exception here. * </p> * * <p> * This code says that it deals with UNCAUGHT EXCEPTIONS, so I think it * would be wise to explicitly catch ServiceExceptions. * </p> * * @param response DOCUMENT ME! * @param t DOCUMENT ME! */ protected void sendError(HttpServletRequest request, HttpServletResponse response, Throwable t) { if (t instanceof ServiceException) { sendError(request, response, (ServiceException) t); return; } LOGGER.info("Had an undefined error: " + t.getMessage()); //TODO: put the stack trace in the logger. //t.printStackTrace(); //String pre = "UNCAUGHT EXCEPTION"; ExceptionHandler exHandler = getExceptionHandler(); ServiceException se = exHandler.newServiceException(t); sendError(request, response, se); //GeoServer geoServer = (GeoServer) this.getServletConfig() // .getServletContext().getAttribute(GeoServer.WEB_CONTAINER_KEY); //send(response, se.getXmlResponse(geoServer.isVerboseExceptions())); } /** * Send a serviceException produced during getService opperation. * * @param response DOCUMENT ME! * @param se DOCUMENT ME! */ protected void sendError(HttpServletRequest request, HttpServletResponse response, ServiceException se) { String mimeType = se.getMimeType(geoServer); send(response, se.getXmlResponse(geoServer.isVerboseExceptions(), request, geoServer), mimeType); se.printStackTrace(); } /** * DOCUMENT ME! * * @param response DOCUMENT ME! * @param result DOCUMENT ME! */ protected void send(HttpServletRequest httpRequest, HttpServletResponse response, Response result) { OutputStream responseOut = null; try { responseOut = response.getOutputStream(); } catch (IOException ex) { //stream closed, do nothing. LOGGER.info("apparently client has closed stream: " + ex.getMessage()); } OutputStream out = new BufferedOutputStream(responseOut); ServletContext servContext = getServletContext(); response.setContentType(result.getContentType( (GeoServer) servContext.getAttribute("GeoServer"))); try { result.writeTo(out); out.flush(); responseOut.flush(); } catch (IOException ioe) { //user just closed the socket stream, do nothing LOGGER.fine("connection closed by user: " + ioe.getMessage()); } catch (ServiceException ex) { sendError(httpRequest, response, ex); } } /** * Checks if the client requests supports gzipped responses by quering it's * 'accept-encoding' header. * * @param request the request to query the HTTP header from * * @return true if 'gzip' if one of the supported content encodings of * <code>request</code>, false otherwise. */ protected boolean requestSupportsGzip(HttpServletRequest request) { boolean supportsGzip = false; String header = request.getHeader("accept-encoding"); if ((header != null) && (header.indexOf("gzip") > -1)) { supportsGzip = true; } if (LOGGER.isLoggable(Level.CONFIG)) { LOGGER.config("user-agent=" + request.getHeader("user-agent")); LOGGER.config("accept=" + request.getHeader("accept")); LOGGER.config("accept-encoding=" + request.getHeader("accept-encoding")); } return supportsGzip; } public String getKvpString() { return kvpString; } public void setKvpString(String kvpString) { this.kvpString = kvpString; } }
false
true
protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { sendDisabledServiceError(response); } catch(IOException e) { LOGGER.log(Level.WARNING, "Error writing service unavailable response", e); } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(request, response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(request, response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(request, response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(request, response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Encoding", encoding); } String disposition = serviceResponse.getContentDisposition(); if(disposition != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Disposition", disposition); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(request, response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error LOGGER.log(Level.SEVERE, "Error writing out " + ioException.getMessage(), ioException); serviceResponse.abort(s); strategy.abort(); sendError(request, response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure serviceResponse.abort(s); strategy.abort(); sendError(request, response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(request, response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); }
protected void doService(HttpServletRequest request, HttpServletResponse response, Request serviceRequest) throws ServletException { LOGGER.info("handling request: " + serviceRequest); if (!isServiceEnabled(request)) { try { sendDisabledServiceError(response); } catch(IOException e) { LOGGER.log(Level.WARNING, "Error writing service unavailable response", e); } return; } ServiceStrategy strategy = null; Response serviceResponse = null; try { strategy = createServiceStrategy(); LOGGER.fine("strategy is: " + strategy.getId()); serviceResponse = getResponseHandler(); } catch (Throwable t) { sendError(request, response, t); return; } Map services = context.getBeansOfType(Service.class); Service s = null; for (Iterator itr = services.entrySet().iterator(); itr.hasNext();) { Map.Entry entry = (Map.Entry) itr.next(); String id = (String) entry.getKey(); Service service = (Service) entry.getValue(); if (id.equalsIgnoreCase(serviceRequest.getService())) { s = service; break; } } if (s == null) { String msg = "No service found matching: " + serviceRequest.getService(); sendError(request, response,new ServiceException ( msg )); return; } try { // execute request LOGGER.finer("executing request"); serviceResponse.execute(serviceRequest); LOGGER.finer("execution succeed"); } catch (ServiceException serviceException) { LOGGER.warning("service exception while executing request: " + serviceRequest + "\ncause: " + serviceException.getMessage()); serviceResponse.abort(s); sendError(request, response, serviceException); return; } catch (Throwable t) { //we can safelly send errors here, since we have not touched response yet serviceResponse.abort(s); sendError(request, response, t); return; } OutputStream strategyOuput = null; //obtain the strategy output stream try { LOGGER.finest("getting strategy output"); strategyOuput = strategy.getDestination(response); LOGGER.finer("strategy output is: " + strategyOuput.getClass().getName()); String mimeType = serviceResponse.getContentType(s.getGeoServer()); LOGGER.fine("mime type is: " + mimeType); response.setContentType(mimeType); String encoding = serviceResponse.getContentEncoding(); if (encoding != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Encoding", encoding); } String disposition = serviceResponse.getContentDisposition(); if(disposition != null) { LOGGER.fine("content encoding is: " + encoding); response.setHeader("Content-Disposition", disposition); } } catch (SocketException socketException) { LOGGER.fine( "it seems that the user has closed the request stream: " + socketException.getMessage()); // It seems the user has closed the request stream // Apparently this is a "cancel" and will quietly go away // // I will still give strategy and serviceResponse // a chance to clean up // serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ex) { serviceResponse.abort(s); strategy.abort(); sendError(request, response, ex); return; } try { // gather response serviceResponse.writeTo(strategyOuput); strategyOuput.flush(); strategy.flush(); } catch (java.net.SocketException sockEx) { // user cancel serviceResponse.abort(s); strategy.abort(); return; } catch (IOException ioException) { // strategyOutput error response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned LOGGER.log(Level.SEVERE, "Error writing out " + ioException.getMessage(), ioException); serviceResponse.abort(s); strategy.abort(); sendError(request, response, ioException); return; } catch (ServiceException writeToFailure) { // writeTo Failure response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned serviceResponse.abort(s); strategy.abort(); sendError(request, response, writeToFailure); return; } catch (Throwable help) { // This is an unexpected error(!) response.setHeader("Content-Disposition", ""); // reset it so we get a proper XML error returned help.printStackTrace(); serviceResponse.abort(s); strategy.abort(); sendError(request, response, help); return; } // Finish Response // I have moved closing the output stream out here, it was being // done by a few of the ServiceStrategy // // By this time serviceResponse has finished successfully // and strategy is also finished // try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (SocketException sockEx) { // user cancel LOGGER.warning("Could not send completed response to user:" + sockEx); return; } catch (IOException ioException) { // This is bad, the user did not get the completed response LOGGER.warning("Could not send completed response to user:" + ioException); return; } LOGGER.info("Service handled"); }
diff --git a/src/net/sf/cpsolver/coursett/TimetableSolver.java b/src/net/sf/cpsolver/coursett/TimetableSolver.java index 6ede3c0..5ba6910 100644 --- a/src/net/sf/cpsolver/coursett/TimetableSolver.java +++ b/src/net/sf/cpsolver/coursett/TimetableSolver.java @@ -1,129 +1,130 @@ package net.sf.cpsolver.coursett; import net.sf.cpsolver.coursett.heuristics.NeighbourSelectionWithSuggestions; import net.sf.cpsolver.coursett.model.Lecture; import net.sf.cpsolver.coursett.model.Placement; import net.sf.cpsolver.coursett.model.TimetableModel; import net.sf.cpsolver.ifs.model.Neighbour; import net.sf.cpsolver.ifs.solver.Solver; import net.sf.cpsolver.ifs.util.DataProperties; import net.sf.cpsolver.ifs.util.JProf; import net.sf.cpsolver.ifs.util.Progress; /** * University course timetabling solver. <br> * <br> * When a complete solution is found, it is improved by limited depth * backtracking search. This way it is ensured that the fund solution is at * least locally optimal. * * @version CourseTT 1.2 (University Course Timetabling)<br> * Copyright (C) 2006 - 2010 Tomas Muller<br> * <a href="mailto:[email protected]">[email protected]</a><br> * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> * <br> * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. <br> * <br> * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. <br> * <br> * You should have received a copy of the GNU Lesser General Public * License along with this library; if not see * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. */ public class TimetableSolver extends Solver<Lecture, Placement> { public TimetableSolver(DataProperties properties) { super(properties); } @Override protected void onAssigned(double startTime) { // Check if the solution is the best ever found one if (iCurrentSolution.getModel().unassignedVariables().isEmpty() && getSolutionComparator().isBetterThanBestSolution(iCurrentSolution)) { fixCompleteSolution(startTime); } /* * else { // If the solver is not able to improve solution in the last * 5000 iterations, take the best one and try to fix it if * (iCurrentSolution.getBestInfo()!=null && * iCurrentSolution.getModel().getBestUnassignedVariables()>0 && * iCurrentSolution * .getIteration()==iCurrentSolution.getBestIteration()+5000) { * iCurrentSolution.restoreBest(); fixCompleteSolution(startTime); } } */ } /** * Try to improve existing solution by backtracking search of very limited * depth. See {@link NeighbourSelectionWithSuggestions} for more details. */ protected void fixCompleteSolution(double startTime) { Progress progress = Progress.getInstance(currentSolution().getModel()); TimetableModel model = (TimetableModel) iCurrentSolution.getModel(); + iCurrentSolution.saveBest(); progress.save(); double solutionValue = 0.0, newSolutionValue = model.getTotalValue(); do { solutionValue = newSolutionValue; progress.setPhase("Fixing solution", model.variables().size()); for (Lecture variable : model.variables()) { Placement bestValue = null; double bestVal = 0.0; Placement currentValue = variable.getAssignment(); if (currentValue == null) continue; double currentVal = currentValue.toDouble(); for (Placement value : variable.values()) { if (value.equals(currentValue)) continue; if (model.conflictValues(value).isEmpty()) { double val = value.toDouble(); if (bestValue == null || val < bestVal) { bestValue = value; bestVal = val; } } } if (bestValue != null && bestVal < currentVal) variable.assign(0, bestValue); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } newSolutionValue = model.getTotalValue(); if (newSolutionValue < solutionValue) { progress.debug("New solution value is " + newSolutionValue); } } while (!iStop && newSolutionValue < solutionValue && getTerminationCondition().canContinue(iCurrentSolution)); progress.restore(); if (!iCurrentSolution.getModel().unassignedVariables().isEmpty()) return; progress.save(); try { progress.setPhase("Fixing solution [2]", model.variables().size()); NeighbourSelectionWithSuggestions ns = new NeighbourSelectionWithSuggestions(this); for (Lecture lecture : model.variables()) { Neighbour<Lecture, Placement> n = ns.selectNeighbourWithSuggestions(iCurrentSolution, lecture, 2); - if (n != null) + if (n != null && n.value() <= 0.0) n.assign(0); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } } catch (Exception e) { sLogger.debug(e.getMessage(), e); } finally { progress.restore(); } } }
false
true
protected void fixCompleteSolution(double startTime) { Progress progress = Progress.getInstance(currentSolution().getModel()); TimetableModel model = (TimetableModel) iCurrentSolution.getModel(); progress.save(); double solutionValue = 0.0, newSolutionValue = model.getTotalValue(); do { solutionValue = newSolutionValue; progress.setPhase("Fixing solution", model.variables().size()); for (Lecture variable : model.variables()) { Placement bestValue = null; double bestVal = 0.0; Placement currentValue = variable.getAssignment(); if (currentValue == null) continue; double currentVal = currentValue.toDouble(); for (Placement value : variable.values()) { if (value.equals(currentValue)) continue; if (model.conflictValues(value).isEmpty()) { double val = value.toDouble(); if (bestValue == null || val < bestVal) { bestValue = value; bestVal = val; } } } if (bestValue != null && bestVal < currentVal) variable.assign(0, bestValue); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } newSolutionValue = model.getTotalValue(); if (newSolutionValue < solutionValue) { progress.debug("New solution value is " + newSolutionValue); } } while (!iStop && newSolutionValue < solutionValue && getTerminationCondition().canContinue(iCurrentSolution)); progress.restore(); if (!iCurrentSolution.getModel().unassignedVariables().isEmpty()) return; progress.save(); try { progress.setPhase("Fixing solution [2]", model.variables().size()); NeighbourSelectionWithSuggestions ns = new NeighbourSelectionWithSuggestions(this); for (Lecture lecture : model.variables()) { Neighbour<Lecture, Placement> n = ns.selectNeighbourWithSuggestions(iCurrentSolution, lecture, 2); if (n != null) n.assign(0); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } } catch (Exception e) { sLogger.debug(e.getMessage(), e); } finally { progress.restore(); } }
protected void fixCompleteSolution(double startTime) { Progress progress = Progress.getInstance(currentSolution().getModel()); TimetableModel model = (TimetableModel) iCurrentSolution.getModel(); iCurrentSolution.saveBest(); progress.save(); double solutionValue = 0.0, newSolutionValue = model.getTotalValue(); do { solutionValue = newSolutionValue; progress.setPhase("Fixing solution", model.variables().size()); for (Lecture variable : model.variables()) { Placement bestValue = null; double bestVal = 0.0; Placement currentValue = variable.getAssignment(); if (currentValue == null) continue; double currentVal = currentValue.toDouble(); for (Placement value : variable.values()) { if (value.equals(currentValue)) continue; if (model.conflictValues(value).isEmpty()) { double val = value.toDouble(); if (bestValue == null || val < bestVal) { bestValue = value; bestVal = val; } } } if (bestValue != null && bestVal < currentVal) variable.assign(0, bestValue); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } newSolutionValue = model.getTotalValue(); if (newSolutionValue < solutionValue) { progress.debug("New solution value is " + newSolutionValue); } } while (!iStop && newSolutionValue < solutionValue && getTerminationCondition().canContinue(iCurrentSolution)); progress.restore(); if (!iCurrentSolution.getModel().unassignedVariables().isEmpty()) return; progress.save(); try { progress.setPhase("Fixing solution [2]", model.variables().size()); NeighbourSelectionWithSuggestions ns = new NeighbourSelectionWithSuggestions(this); for (Lecture lecture : model.variables()) { Neighbour<Lecture, Placement> n = ns.selectNeighbourWithSuggestions(iCurrentSolution, lecture, 2); if (n != null && n.value() <= 0.0) n.assign(0); iCurrentSolution.update(JProf.currentTimeSec() - startTime); progress.incProgress(); if (iStop) break; } } catch (Exception e) { sLogger.debug(e.getMessage(), e); } finally { progress.restore(); } }
diff --git a/src/ContactManagerImpl.java b/src/ContactManagerImpl.java index 3feda84..9e9e191 100644 --- a/src/ContactManagerImpl.java +++ b/src/ContactManagerImpl.java @@ -1,351 +1,352 @@ import java.io.*; import java.util.*; public class ContactManagerImpl implements ContactManager, Serializable { private static final File dataOnDisk = new File("./contacts.txt"); public Set<Contact> contactSet = new HashSet<Contact>(); public Set<Meeting> meetingSet = new HashSet<Meeting>(); private List<FutureMeeting> futureMeetings = new ArrayList<FutureMeeting>(); private List<PastMeeting> pastMeetings = new ArrayList<PastMeeting>(); /** @param firstRun a flag so the program can distinguish between contacts.txt being absent due to a first run OR an error. * In full program user would call program with command line options -n [short] or --new [long], which would * set firstRun to true before calling the constructor. In this case brand new sets and lists would be created and * a FileNotFoundException would not be thrown. If user does not launch program with one of the command line flags, * the error message of the FileNotFoundException informs them to do so if this is their first time */ private static boolean firstRun = false; public ContactManagerImpl() { /** method load reads in data objects from disk (or instantiates new ones) */ this.load(); } public int addFutureMeeting(Set<Contact> contacts, Calendar date) { /** @param currentDate an instance of Calendar to get the current date in order to see if the date provided is valid */ Calendar currentDate = GregorianCalendar.getInstance(); if (currentDate.after(date)) // i.e if user's date is in the past { throw new IllegalArgumentException("Specified date is in the past! Please try again."); } for (Iterator<Contact> itr = contacts.iterator(); itr.hasNext();) { if (!contactSet.contains(itr.next())) // if contactSet does NOT contain itr.next() { throw new IllegalArgumentException("Contact \"" + itr.next().getName() + "\" does not exist! Please try again."); } } /** if neither exception thrown, FutureMeeting object can be instantiated */ FutureMeeting tmp = new FutureMeetingImpl(contacts, date); meetingSet.add(tmp); futureMeetings.add(tmp); /** @return the ID for the meeting by calling getId() */ System.out.println("Success - Meeting Scheduled!"); return tmp.getId(); } public PastMeeting getPastMeeting(int id) { char flag = 'p'; // 'p' for past meeting Meeting meeting = new MeetingImpl(); meeting = ((MeetingImpl)meeting).returnMeeting(meetingSet, id, flag); // call the method in MeetingImpl return (PastMeeting) meeting; // cast to correct type on return } public FutureMeeting getFutureMeeting(int id) { char flag = 'f'; // 'f' for future meeting Meeting meeting = new MeetingImpl(); meeting = ((MeetingImpl)meeting).returnMeeting(meetingSet, id, flag); // call the method in MeetingImpl return (FutureMeeting) meeting; // cast to correct type on return } public Meeting getMeeting(int id) { char flag = 'm'; // 'm' for simply meeting Meeting meeting = new MeetingImpl(); meeting = ((MeetingImpl)meeting).returnMeeting(meetingSet, id, flag); // call the method in MeetingImpl return meeting; // no need for casting here } public List<Meeting> getFutureMeetingList(Contact contact) { /** @throws IllegalArgumentException if the contact does not exist */ if (!contactSet.contains(contact)) { throw new IllegalArgumentException("Contact \"" + contact.getName() + "\" does not exist! Please try again"); } else { /** @param list a list to store any matching Meetings; will be returned empty if no matches */ List<Meeting> list = new ArrayList<Meeting>(); for (Meeting m : meetingSet) { if (m.getContacts().contains(contact)) { /** each time a matching Meeting is found, it is added to the list. */ list.add(m); } } /** call custom comparator in MeetingImpl to chronologically sort */ Collections.sort(list, MeetingImpl.MeetingComparator); return list; } } /** THIS METHOD GETS BOTH PAST AND FUTURE MEETINGS DEPENDING ON DATE GIVEN */ public List<Meeting> getFutureMeetingList(Calendar date) { /** @param list a list to store any matching Meetings; will be returned empty if no matches */ List<Meeting> list = new ArrayList<Meeting>(); for (Meeting m : meetingSet) { if (m.getDate().equals(date)) { /** each time a matching Meeting is found, it is added to the list. */ list.add(m); } } /** call custom comparator in MeetingImpl to chronologically sort */ Collections.sort(list, MeetingImpl.MeetingComparator); return list; } public List<PastMeeting> getPastMeetingList(Contact contact) { /** @throws IllegalArgumentException if the contact does not exist */ if (!contactSet.contains(contact)) { throw new IllegalArgumentException("Contact \"" + contact.getName() + "\" does not exist! Please try again"); } else { /** @param list a list to store any matching PastMeetings; will be returned empty if no matches */ List<PastMeeting> list = new ArrayList<PastMeeting>(); for (PastMeeting pm : pastMeetings) { if (pm.getContacts().contains(contact)) { list.add(pm); } } /** call custom comparator in MeetingImpl to chronologically sort */ Collections.sort(list, MeetingImpl.MeetingComparator); return list; } } public void addNewPastMeeting(Set<Contact> contacts, Calendar date, String text) { if (contacts.isEmpty() || !contactSet.containsAll(contacts)) { throw new IllegalArgumentException("One or more Contacts do not exist OR set is empty"); } else if (contacts == null || date == null || text == null) { throw new NullPointerException("One or more arguments are null"); } else { PastMeeting pastMeeting = new PastMeetingImpl(contacts, date); meetingSet.add(pastMeeting); // add to main meeting set pastMeetings.add(pastMeeting); // add to list of past meetings /** use method addMeetingNotes to add notes to avoid unnecessary code duplication */ addMeetingNotes(pastMeeting.getId(), text); } } /** This method is used when a future meeting takes place, and is * then converted to a past meeting (with notes). * It can be also used to add notes to a past meeting at a later date. */ public void addMeetingNotes(int id, String text) { Meeting meeting = getMeeting(id); Calendar presentDate = GregorianCalendar.getInstance(); if (meeting == null) { throw new IllegalArgumentException("Specified meeting does not exist!"); } else if (text == null) { throw new NullPointerException("Cannot add null string of notes"); } else if (meeting.getDate().after(presentDate)) { throw new IllegalStateException("Meeting set for date in the future - not eligible for conversion!"); } else if (meeting instanceof FutureMeeting) // we know it's a future meeting needing conversion { for (FutureMeeting fm : futureMeetings) { /** @param convertedMeeting name to indicate the original FutureMeeting type is now a PastMeeting */ if (fm.getId() == id) { futureMeetings.remove(fm); // take it out of the future meetings list PastMeeting convertedMeeting = (PastMeeting) fm; // cast into a PastMeeting (the conversion) addMeetingNotes(convertedMeeting.getId(), text); // add the notes } } } else if (meeting instanceof PastMeeting) // this will catch cases where we just want to add notes to a PastMeeting (including the convertedMeeting) { /** @param updatedMeeting name to indicate the updated PastMeeting object which will now have notes */ Meeting updatedMeeting = meeting; ((PastMeetingImpl)updatedMeeting).addNotes(text); // add notes to updatedMeeting meetingSet.remove(meeting); // remove old. note-less meeting from meeting set meetingSet.add((PastMeeting) updatedMeeting); // add the updated meeting back to meeting set pastMeetings.remove(meeting); // remove the old meeting from list of past meetings pastMeetings.add((PastMeeting) updatedMeeting); // add our new PastMeeting to the past meetings list } } public void addNewContact(String name, String notes) { /** @param uniqueId a unique Id constructed by adding 1 * to the current size of the HashSet */ int uniqueId = (this.contactSet.size() + 1); Contact tmp = new ContactImpl(name, notes, uniqueId); // construct a Contact object by calling ContactImpl constructor contactSet.add(tmp); // add to set of contacts } public Set<Contact> getContacts(int... ids) { boolean isRealId = false; /** @param isRealId stores whether or not we found a contact with the id */ int offendingId = 0; /** @param offendingId stores the id that does not correspond to a real contact */ Set<Contact> setToReturn = new HashSet<Contact>(); if (contactSet.isEmpty()) { throw new NullPointerException("No Contacts in set!"); } else { for (int id : ids) { for (Contact contact : contactSet) { if (id == contact.getId()) { isRealId = true; setToReturn.add(contact); break; } else isRealId = false; offendingId = id; } if (!isRealId) { throw new IllegalArgumentException("Contact with id " + offendingId + " does not exist"); } } return setToReturn; } } public Set<Contact> getContacts(String name) { /** @param lowerCaseContactName, @param lowerCaseInput - I convert both strings into lower case before the string * comparison, so it does not matter if user gives this method "ann" when they want to find "Ann Smith" */ String lowerCaseContactName; String lowerCaseInput = name.toLowerCase(); Set<Contact> setToReturn = new HashSet<Contact>(); if (name == null) { throw new NullPointerException("Cannot compare contact names against a null string"); } else { for (Contact contact : contactSet) { lowerCaseContactName = contact.getName().toLowerCase(); if (lowerCaseContactName.contains(lowerCaseInput)) // we have a match! setToReturn.add(contact); } } return setToReturn; } public void flush() { try { /** clear data from file so we write the most up-to-date, canonical data structures, * not merely appending which would result in duplicated or old data being read in */ dataOnDisk.delete(); ObjectOutputStream objectOut = new ObjectOutputStream( // written over several lines new BufferedOutputStream( // for extra clarity new FileOutputStream(dataOnDisk))); objectOut.writeObject(this.contactSet); // writes the HashSet containing contacts to disk objectOut.writeObject(this.meetingSet); // writes the HashSet containing meetings to disk objectOut.writeObject(this.pastMeetings); objectOut.writeObject(this.futureMeetings); objectOut.close(); } catch (FileNotFoundException fnfex) { System.err.println("Contacts.txt file not found. Please make sure directory is writeable and try again"); } catch (IOException ioex) { System.err.println("Problem writing to disk. See stack trace for details and/or please try again"); ioex.printStackTrace(); } } private void load() { - if (firstRun) + if (firstRun || !dataOnDisk.exists()) // temporarily added hack to fix serialization until i solve main issue { /** make new empty sets and call the other constructor; for when dataOnDisk doesn't exist * not due to error, but because program is being run for the first time */ this.contactSet = new HashSet<Contact>(); this.meetingSet = new HashSet<Meeting>(); this.pastMeetings = new ArrayList<PastMeeting>(); this.futureMeetings = new ArrayList<FutureMeeting>(); this.flush(); // immediately flush to create contacts.txt firstRun = false; // set firstRun to false now that we have created new data structures and flushed } else { try { ObjectInputStream objectIn = new ObjectInputStream( // written over several lines new BufferedInputStream( // for extra clarity new FileInputStream(dataOnDisk))); this.contactSet = (HashSet<Contact>) objectIn.readObject(); // read the HashSet containing contacts from disk this.meetingSet = (HashSet<Meeting>) objectIn.readObject(); // read the HashSet containing meetings from disk this.pastMeetings = (ArrayList<PastMeeting>) objectIn.readObject(); this.futureMeetings = (ArrayList<FutureMeeting>) objectIn.readObject(); objectIn.close(); + dataOnDisk.delete(); // temporarily added hack to fix serialization until i solve main issue } catch (FileNotFoundException fnfex) { System.err.println("Contacts.txt file not found. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again. If this is your first " + "\nrun of the program, please run again with flag '-n' or '--new'"); } catch (ClassNotFoundException cnfex) { System.err.println("Could not load a required class. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again." + "\n If you are working in a different directory, make sure your CLASSPATH includes the required class:\n\n"); System.out.print(cnfex.getCause().toString()); // will hopefully print the class(es) that caused the exception } catch (IOException ioex) { System.err.println("Problem writing to disk. See stack trace for details and/or please try again"); ioex.printStackTrace(); } } } }
false
true
private void load() { if (firstRun) { /** make new empty sets and call the other constructor; for when dataOnDisk doesn't exist * not due to error, but because program is being run for the first time */ this.contactSet = new HashSet<Contact>(); this.meetingSet = new HashSet<Meeting>(); this.pastMeetings = new ArrayList<PastMeeting>(); this.futureMeetings = new ArrayList<FutureMeeting>(); this.flush(); // immediately flush to create contacts.txt firstRun = false; // set firstRun to false now that we have created new data structures and flushed } else { try { ObjectInputStream objectIn = new ObjectInputStream( // written over several lines new BufferedInputStream( // for extra clarity new FileInputStream(dataOnDisk))); this.contactSet = (HashSet<Contact>) objectIn.readObject(); // read the HashSet containing contacts from disk this.meetingSet = (HashSet<Meeting>) objectIn.readObject(); // read the HashSet containing meetings from disk this.pastMeetings = (ArrayList<PastMeeting>) objectIn.readObject(); this.futureMeetings = (ArrayList<FutureMeeting>) objectIn.readObject(); objectIn.close(); } catch (FileNotFoundException fnfex) { System.err.println("Contacts.txt file not found. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again. If this is your first " + "\nrun of the program, please run again with flag '-n' or '--new'"); } catch (ClassNotFoundException cnfex) { System.err.println("Could not load a required class. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again." + "\n If you are working in a different directory, make sure your CLASSPATH includes the required class:\n\n"); System.out.print(cnfex.getCause().toString()); // will hopefully print the class(es) that caused the exception } catch (IOException ioex) { System.err.println("Problem writing to disk. See stack trace for details and/or please try again"); ioex.printStackTrace(); } } }
private void load() { if (firstRun || !dataOnDisk.exists()) // temporarily added hack to fix serialization until i solve main issue { /** make new empty sets and call the other constructor; for when dataOnDisk doesn't exist * not due to error, but because program is being run for the first time */ this.contactSet = new HashSet<Contact>(); this.meetingSet = new HashSet<Meeting>(); this.pastMeetings = new ArrayList<PastMeeting>(); this.futureMeetings = new ArrayList<FutureMeeting>(); this.flush(); // immediately flush to create contacts.txt firstRun = false; // set firstRun to false now that we have created new data structures and flushed } else { try { ObjectInputStream objectIn = new ObjectInputStream( // written over several lines new BufferedInputStream( // for extra clarity new FileInputStream(dataOnDisk))); this.contactSet = (HashSet<Contact>) objectIn.readObject(); // read the HashSet containing contacts from disk this.meetingSet = (HashSet<Meeting>) objectIn.readObject(); // read the HashSet containing meetings from disk this.pastMeetings = (ArrayList<PastMeeting>) objectIn.readObject(); this.futureMeetings = (ArrayList<FutureMeeting>) objectIn.readObject(); objectIn.close(); dataOnDisk.delete(); // temporarily added hack to fix serialization until i solve main issue } catch (FileNotFoundException fnfex) { System.err.println("Contacts.txt file not found. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again. If this is your first " + "\nrun of the program, please run again with flag '-n' or '--new'"); } catch (ClassNotFoundException cnfex) { System.err.println("Could not load a required class. Please make sure directory is readable and/or " + "\nthat you have flushed at least once previously, and then try again." + "\n If you are working in a different directory, make sure your CLASSPATH includes the required class:\n\n"); System.out.print(cnfex.getCause().toString()); // will hopefully print the class(es) that caused the exception } catch (IOException ioex) { System.err.println("Problem writing to disk. See stack trace for details and/or please try again"); ioex.printStackTrace(); } } }
diff --git a/src/net/colar/netbeans/fan/wizard/FanTalesProjectWizardIterator.java b/src/net/colar/netbeans/fan/wizard/FanTalesProjectWizardIterator.java index 74ce715..0484051 100644 --- a/src/net/colar/netbeans/fan/wizard/FanTalesProjectWizardIterator.java +++ b/src/net/colar/netbeans/fan/wizard/FanTalesProjectWizardIterator.java @@ -1,175 +1,174 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.wizard; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedHashSet; import java.util.NoSuchElementException; import java.util.Set; import javax.swing.event.ChangeListener; import net.colar.netbeans.fan.actions.FanExecution; import net.colar.netbeans.fan.platform.FanPlatform; import net.colar.netbeans.fan.project.FanProject; import net.colar.netbeans.fan.project.FanProjectProperties; import org.netbeans.spi.project.ui.support.ProjectChooser; import org.openide.WizardDescriptor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; /** * Generated by NB "New wizard" * Iterator for new fan project/pod wizard * @author tcolar */ public final class FanTalesProjectWizardIterator implements WizardDescriptor.InstantiatingIterator { private int index; private WizardDescriptor wizard; private WizardDescriptor.Panel[] panels; private WizardDescriptor.Panel[] getPanels() { if (panels == null) { panels = new WizardDescriptor.Panel[] { new FanTalesProjectWizardPanel1(System.getProperty("user.dir")), }; } return panels; } public FanTalesProjectWizardPanel1 getPanel() { return (FanTalesProjectWizardPanel1) panels[0]; } /** * Called when "finish" is pressed * @return * @throws IOException */ public Set instantiate() throws IOException { FanTalesProjectWizardPanel1 panel = getPanel(); String location = panel.getProjectLocation(); String projectName = panel.getProjectName(); // Call "tales new" to create the project FanExecution fanExec = new FanExecution(); fanExec.setDisplayName("Tales " + projectName); fanExec.setWorkingDirectory(location); FanPlatform.getInstance().buildFanCall(null, fanExec, false, ""); fanExec.addCommandArg(FanPlatform.FAN_CLASS); fanExec.addCommandArg(FanPlatform.FAN_TALES_POD_NAME); - fanExec.addCommandArg(location); fanExec.addCommandArg(FanPlatform.FAN_TALES_CREATE_CMD); fanExec.addCommandArg(projectName); fanExec.runAndWaitFor(); // Return the prj so that it's open in IDE File pf = FileUtil.normalizeFile(new File(location + File.separator + projectName + File.separator)); FileObject pfFo = FileUtil.toFileObject(pf); File fan = FileUtil.normalizeFile(new File(pf, "fan")); fan.mkdirs(); File test = FileUtil.normalizeFile(new File(pf, "test")); test.mkdirs(); //build.fan FileObject fanFo = FileUtil.toFileObject(fan); FileObject testFo = FileUtil.toFileObject(test); LinkedHashSet<FileObject> resultSet = new LinkedHashSet<FileObject>(); resultSet.add(pfFo); resultSet.add(fanFo); resultSet.add(testFo); File parent = pf.getParentFile(); // Always open top dir as a project: if (parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } FileUtil.refreshFor(pf); File prjDir = FileUtil.normalizeFile(new File(pf, "nbproject")); File prjFile = FileUtil.normalizeFile(new File(prjDir, "project.properties")); prjDir.mkdirs(); FileWriter writer = new FileWriter(prjFile); writer.append(FanProjectProperties.IS_TALES_PRJ+"=true\n"); writer.close(); return resultSet; } public static FanTalesProjectWizardIterator instance() { return new FanTalesProjectWizardIterator(); } public void initialize(WizardDescriptor wizard) { this.wizard = wizard; } public void uninitialize(WizardDescriptor wizard) { panels = null; } public WizardDescriptor.Panel current() { return getPanels()[index]; } public String name() { return index + 1 + ". from " + getPanels().length; } public boolean hasNext() { return index < getPanels().length - 1; } public boolean hasPrevious() { return index > 0; } public void nextPanel() { if (!hasNext()) { throw new NoSuchElementException(); } index++; } public void previousPanel() { if (!hasPrevious()) { throw new NoSuchElementException(); } index--; } // If nothing unusual changes in the middle of the wizard, simply: public void addChangeListener(ChangeListener l) { } public void removeChangeListener(ChangeListener l) { } }
true
true
public Set instantiate() throws IOException { FanTalesProjectWizardPanel1 panel = getPanel(); String location = panel.getProjectLocation(); String projectName = panel.getProjectName(); // Call "tales new" to create the project FanExecution fanExec = new FanExecution(); fanExec.setDisplayName("Tales " + projectName); fanExec.setWorkingDirectory(location); FanPlatform.getInstance().buildFanCall(null, fanExec, false, ""); fanExec.addCommandArg(FanPlatform.FAN_CLASS); fanExec.addCommandArg(FanPlatform.FAN_TALES_POD_NAME); fanExec.addCommandArg(location); fanExec.addCommandArg(FanPlatform.FAN_TALES_CREATE_CMD); fanExec.addCommandArg(projectName); fanExec.runAndWaitFor(); // Return the prj so that it's open in IDE File pf = FileUtil.normalizeFile(new File(location + File.separator + projectName + File.separator)); FileObject pfFo = FileUtil.toFileObject(pf); File fan = FileUtil.normalizeFile(new File(pf, "fan")); fan.mkdirs(); File test = FileUtil.normalizeFile(new File(pf, "test")); test.mkdirs(); //build.fan FileObject fanFo = FileUtil.toFileObject(fan); FileObject testFo = FileUtil.toFileObject(test); LinkedHashSet<FileObject> resultSet = new LinkedHashSet<FileObject>(); resultSet.add(pfFo); resultSet.add(fanFo); resultSet.add(testFo); File parent = pf.getParentFile(); // Always open top dir as a project: if (parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } FileUtil.refreshFor(pf); File prjDir = FileUtil.normalizeFile(new File(pf, "nbproject")); File prjFile = FileUtil.normalizeFile(new File(prjDir, "project.properties")); prjDir.mkdirs(); FileWriter writer = new FileWriter(prjFile); writer.append(FanProjectProperties.IS_TALES_PRJ+"=true\n"); writer.close(); return resultSet; }
public Set instantiate() throws IOException { FanTalesProjectWizardPanel1 panel = getPanel(); String location = panel.getProjectLocation(); String projectName = panel.getProjectName(); // Call "tales new" to create the project FanExecution fanExec = new FanExecution(); fanExec.setDisplayName("Tales " + projectName); fanExec.setWorkingDirectory(location); FanPlatform.getInstance().buildFanCall(null, fanExec, false, ""); fanExec.addCommandArg(FanPlatform.FAN_CLASS); fanExec.addCommandArg(FanPlatform.FAN_TALES_POD_NAME); fanExec.addCommandArg(FanPlatform.FAN_TALES_CREATE_CMD); fanExec.addCommandArg(projectName); fanExec.runAndWaitFor(); // Return the prj so that it's open in IDE File pf = FileUtil.normalizeFile(new File(location + File.separator + projectName + File.separator)); FileObject pfFo = FileUtil.toFileObject(pf); File fan = FileUtil.normalizeFile(new File(pf, "fan")); fan.mkdirs(); File test = FileUtil.normalizeFile(new File(pf, "test")); test.mkdirs(); //build.fan FileObject fanFo = FileUtil.toFileObject(fan); FileObject testFo = FileUtil.toFileObject(test); LinkedHashSet<FileObject> resultSet = new LinkedHashSet<FileObject>(); resultSet.add(pfFo); resultSet.add(fanFo); resultSet.add(testFo); File parent = pf.getParentFile(); // Always open top dir as a project: if (parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } FileUtil.refreshFor(pf); File prjDir = FileUtil.normalizeFile(new File(pf, "nbproject")); File prjFile = FileUtil.normalizeFile(new File(prjDir, "project.properties")); prjDir.mkdirs(); FileWriter writer = new FileWriter(prjFile); writer.append(FanProjectProperties.IS_TALES_PRJ+"=true\n"); writer.close(); return resultSet; }
diff --git a/MessageSearch/src/com/github/searchbadger/util/ContactSMS.java b/MessageSearch/src/com/github/searchbadger/util/ContactSMS.java index 0cc08f6..8636dbc 100644 --- a/MessageSearch/src/com/github/searchbadger/util/ContactSMS.java +++ b/MessageSearch/src/com/github/searchbadger/util/ContactSMS.java @@ -1,83 +1,87 @@ package com.github.searchbadger.util; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; public class ContactSMS extends Contact implements Parcelable { protected List<String> addresses; public ContactSMS(String id, MessageSource source, String name, Bitmap picture, List<String> addresses) { super(id, source, name, picture); this.addresses = addresses; } public ContactSMS(Parcel in){ super(in); addresses = new LinkedList<String>(); in.readStringList(addresses); } public List<String> getAddresses() { return addresses; } @Override public String toString() { StringBuilder str = new StringBuilder(); str.append(name + " | " + id + " | " + source + " | "); for(int i = 0; i < addresses.size(); i++) { str.append(addresses.get(i) + ", "); } return str.toString(); } @Override public int describeContents() { Log.d("Contact","describeContents()"); return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id); dest.writeString(source.name()); dest.writeString(name); dest.writeParcelable(picture, flags); dest.writeStringList(addresses); } public static final Parcelable.Creator<ContactSMS> CREATOR = new Parcelable.Creator<ContactSMS>() { public ContactSMS createFromParcel(Parcel in) { return new ContactSMS(in); } public ContactSMS[] newArray(int size) { return new ContactSMS[size]; } }; @Override public boolean contains(String address) { + address = address.replace(" ", ""); + address = address.replace("-", ""); if(addresses == null) return false; Iterator<String> itr = addresses.iterator(); while(itr.hasNext()) { String contactAddress = itr.next(); + contactAddress = contactAddress.replace(" ", ""); + contactAddress = contactAddress.replace("-", ""); if(contactAddress.equals(address)) return true; } if(id.equals(address)) return true; return false; } }
false
true
public boolean contains(String address) { if(addresses == null) return false; Iterator<String> itr = addresses.iterator(); while(itr.hasNext()) { String contactAddress = itr.next(); if(contactAddress.equals(address)) return true; } if(id.equals(address)) return true; return false; }
public boolean contains(String address) { address = address.replace(" ", ""); address = address.replace("-", ""); if(addresses == null) return false; Iterator<String> itr = addresses.iterator(); while(itr.hasNext()) { String contactAddress = itr.next(); contactAddress = contactAddress.replace(" ", ""); contactAddress = contactAddress.replace("-", ""); if(contactAddress.equals(address)) return true; } if(id.equals(address)) return true; return false; }
diff --git a/src/org/jruby/RubyFile.java b/src/org/jruby/RubyFile.java index 1983906d8..d07411779 100644 --- a/src/org/jruby/RubyFile.java +++ b/src/org/jruby/RubyFile.java @@ -1,1059 +1,1063 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.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.eclipse.org/legal/cpl-v10.html * * 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. * * Copyright (C) 2002 Benoit Cerrina <[email protected]> * Copyright (C) 2002-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2003 Joey Gibson <[email protected]> * Copyright (C) 2004 Thomas E Enebo <[email protected]> * Copyright (C) 2004-2006 Charles O Nutter <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2006 Miguel Covarrubias <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.CallbackFactory; import org.jruby.runtime.MethodIndex; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; import org.jruby.util.Chmod; import org.jruby.util.IOHandler; import org.jruby.util.IOHandlerNull; import org.jruby.util.IOHandlerSeekable; import org.jruby.util.IOHandlerUnseekable; import org.jruby.util.IOModes; import org.jruby.util.JRubyFile; import org.jruby.util.ShellLauncher; import org.jruby.util.Sprintf; import org.jruby.util.IOHandler.InvalidValueException; /** * Ruby File class equivalent in java. * * @author jpetersen **/ public class RubyFile extends RubyIO { public static final int LOCK_SH = 1; public static final int LOCK_EX = 2; public static final int LOCK_NB = 4; public static final int LOCK_UN = 8; private static final int FNM_NOESCAPE = 1; private static final int FNM_PATHNAME = 2; private static final int FNM_DOTMATCH = 4; private static final int FNM_CASEFOLD = 8; protected String path; private FileLock currentLock; public RubyFile(Ruby runtime, RubyClass type) { super(runtime, type); } public RubyFile(Ruby runtime, String path) { this(runtime, path, open(runtime, path)); } // use static function because constructor call must be first statement in above constructor private static InputStream open(Ruby runtime, String path) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw runtime.newIOError(e.getMessage()); } } // XXX This constructor is a hack to implement the __END__ syntax. // Converting a reader back into an InputStream doesn't generally work. public RubyFile(Ruby runtime, String path, final Reader reader) { this(runtime, path, new InputStream() { public int read() throws IOException { return reader.read(); } }); } private RubyFile(Ruby runtime, String path, InputStream in) { super(runtime, runtime.getClass("File")); this.path = path; try { this.handler = new IOHandlerUnseekable(runtime, in, null); } catch (IOException e) { throw runtime.newIOError(e.getMessage()); } this.modes = handler.getModes(); registerIOHandler(handler); } private static ObjectAllocator FILE_ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { RubyFile instance = new RubyFile(runtime, klass); instance.setMetaClass(klass); return instance; } }; public static RubyClass createFileClass(Ruby runtime) { RubyClass fileClass = runtime.defineClass("File", runtime.getClass("IO"), FILE_ALLOCATOR); CallbackFactory callbackFactory = runtime.callbackFactory(RubyFile.class); RubyClass fileMetaClass = fileClass.getMetaClass(); RubyString separator = runtime.newString("/"); separator.freeze(); fileClass.defineConstant("SEPARATOR", separator); fileClass.defineConstant("Separator", separator); - RubyString altSeparator = runtime.newString(File.separatorChar == '/' ? "\\" : "/"); - altSeparator.freeze(); - fileClass.defineConstant("ALT_SEPARATOR", altSeparator); + if (File.separatorChar == '\\') { + RubyString altSeparator = runtime.newString("\\"); + altSeparator.freeze(); + fileClass.defineConstant("ALT_SEPARATOR", altSeparator); + } else { + fileClass.defineConstant("ALT_SEPARATOR", runtime.getNil()); + } RubyString pathSeparator = runtime.newString(File.pathSeparator); pathSeparator.freeze(); fileClass.defineConstant("PATH_SEPARATOR", pathSeparator); // TODO: These were missing, so we're not handling them elsewhere? // FIXME: The old value, 32786, didn't match what IOModes expected, so I reference // the constant here. THIS MAY NOT BE THE CORRECT VALUE. fileClass.setConstant("BINARY", runtime.newFixnum(IOModes.BINARY)); fileClass.setConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE)); fileClass.setConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD)); fileClass.setConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH)); fileClass.setConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME)); // Create constants for open flags fileClass.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); fileClass.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); fileClass.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); fileClass.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); fileClass.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); fileClass.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); fileClass.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); fileClass.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); fileClass.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock fileClass.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); fileClass.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); fileClass.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); fileClass.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // Create Constants class RubyModule constants = fileClass.defineModuleUnder("Constants"); // TODO: These were missing, so we're not handling them elsewhere? constants.setConstant("BINARY", runtime.newFixnum(32768)); constants.setConstant("FNM_NOESCAPE", runtime.newFixnum(1)); constants.setConstant("FNM_CASEFOLD", runtime.newFixnum(8)); constants.setConstant("FNM_DOTMATCH", runtime.newFixnum(4)); constants.setConstant("FNM_PATHNAME", runtime.newFixnum(2)); // Create constants for open flags constants.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); constants.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); constants.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); constants.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); constants.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); constants.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); constants.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); constants.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); constants.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock constants.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); constants.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); constants.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); constants.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // TODO Singleton methods: blockdev?, chardev?, directory? // TODO Singleton methods: executable?, executable_real?, // TODO Singleton methods: ftype, grpowned?, lchmod, lchown, link, owned? // TODO Singleton methods: pipe?, readlink, setgid?, setuid?, socket?, // TODO Singleton methods: stat, sticky?, symlink?, umask runtime.getModule("FileTest").extend_object(fileClass); fileMetaClass.defineFastMethod("basename", callbackFactory.getFastOptSingletonMethod("basename")); fileMetaClass.defineFastMethod("chmod", callbackFactory.getFastOptSingletonMethod("chmod")); fileMetaClass.defineFastMethod("chown", callbackFactory.getFastOptSingletonMethod("chown")); fileMetaClass.defineFastMethod("delete", callbackFactory.getFastOptSingletonMethod("unlink")); fileMetaClass.defineFastMethod("dirname", callbackFactory.getFastSingletonMethod("dirname", IRubyObject.class)); fileMetaClass.defineFastMethod("expand_path", callbackFactory.getFastOptSingletonMethod("expand_path")); fileMetaClass.defineFastMethod("extname", callbackFactory.getFastSingletonMethod("extname", IRubyObject.class)); fileMetaClass.defineFastMethod("fnmatch", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("fnmatch?", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("join", callbackFactory.getFastOptSingletonMethod("join")); fileMetaClass.defineFastMethod("lstat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileMetaClass.defineFastMethod("atime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("mtime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("ctime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineMethod("open", callbackFactory.getOptSingletonMethod("open")); fileMetaClass.defineFastMethod("rename", callbackFactory.getFastSingletonMethod("rename", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("size?", callbackFactory.getFastSingletonMethod("size_p", IRubyObject.class)); fileMetaClass.defineFastMethod("split", callbackFactory.getFastSingletonMethod("split", IRubyObject.class)); fileMetaClass.defineFastMethod("stat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); fileMetaClass.defineFastMethod("symlink", callbackFactory.getFastSingletonMethod("symlink", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("symlink?", callbackFactory.getFastSingletonMethod("symlink_p", IRubyObject.class)); fileMetaClass.defineFastMethod("truncate", callbackFactory.getFastSingletonMethod("truncate", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("utime", callbackFactory.getFastOptSingletonMethod("utime")); fileMetaClass.defineFastMethod("unlink", callbackFactory.getFastOptSingletonMethod("unlink")); // TODO: Define instance methods: lchmod, lchown, lstat fileClass.defineFastMethod("chmod", callbackFactory.getFastMethod("chmod", IRubyObject.class)); fileClass.defineFastMethod("chown", callbackFactory.getFastMethod("chown", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileClass.defineFastMethod("atime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("ctime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("mtime", callbackFactory.getFastMethod("mtime")); fileClass.defineMethod("initialize", callbackFactory.getOptMethod("initialize")); fileClass.defineFastMethod("path", callbackFactory.getFastMethod("path")); fileClass.defineFastMethod("stat", callbackFactory.getFastMethod("stat")); fileClass.defineFastMethod("truncate", callbackFactory.getFastMethod("truncate", IRubyObject.class)); fileClass.defineFastMethod("flock", callbackFactory.getFastMethod("flock", IRubyObject.class)); RubyFileStat.createFileStatClass(runtime); return fileClass; } public void openInternal(String newPath, IOModes newModes) { this.path = newPath; this.modes = newModes; try { if (newPath.equals("/dev/null")) { handler = new IOHandlerNull(getRuntime(), newModes); } else { handler = new IOHandlerSeekable(getRuntime(), newPath, newModes); } registerIOHandler(handler); } catch (InvalidValueException e) { throw getRuntime().newErrnoEINVALError(); } catch (FileNotFoundException e) { throw getRuntime().newErrnoENOENTError(); } catch (IOException e) { throw getRuntime().newIOError(e.getMessage()); } } public IRubyObject close() { // Make sure any existing lock is released before we try and close the file if (currentLock != null) { try { currentLock.release(); } catch (IOException e) { throw getRuntime().newIOError(e.getMessage()); } } return super.close(); } public IRubyObject flock(IRubyObject lockingConstant) { FileChannel fileChannel = handler.getFileChannel(); int lockMode = (int) ((RubyFixnum) lockingConstant.convertToType(getRuntime().getFixnum(), MethodIndex.TO_INT, "to_int", true)).getLongValue(); try { switch(lockMode) { case LOCK_UN: if (currentLock != null) { currentLock.release(); currentLock = null; return getRuntime().newFixnum(0); } break; case LOCK_EX: if (currentLock != null) { currentLock.release(); currentLock = null; } currentLock = fileChannel.lock(); if (currentLock != null) { return getRuntime().newFixnum(0); } break; case LOCK_EX | LOCK_NB: if (currentLock != null) { currentLock.release(); currentLock = null; } currentLock = fileChannel.tryLock(); if (currentLock != null) { return getRuntime().newFixnum(0); } break; case LOCK_SH: if (currentLock != null) { currentLock.release(); currentLock = null; } currentLock = fileChannel.lock(0L, Long.MAX_VALUE, true); if (currentLock != null) { return getRuntime().newFixnum(0); } break; case LOCK_SH | LOCK_NB: if (currentLock != null) { currentLock.release(); currentLock = null; } currentLock = fileChannel.tryLock(0L, Long.MAX_VALUE, true); if (currentLock != null) { return getRuntime().newFixnum(0); } break; default: } } catch (IOException ioe) { if(getRuntime().getDebug().isTrue()) { ioe.printStackTrace(System.err); } // Return false here } catch (java.nio.channels.OverlappingFileLockException ioe) { if(getRuntime().getDebug().isTrue()) { ioe.printStackTrace(System.err); } // Return false here } return getRuntime().getFalse(); } public IRubyObject initialize(IRubyObject[] args, Block block) { if (args.length == 0) { throw getRuntime().newArgumentError(0, 1); } getRuntime().checkSafeString(args[0]); path = args[0].toString(); modes = args.length > 1 ? getModes(getRuntime(), args[1]) : new IOModes(getRuntime(), IOModes.RDONLY); // One of the few places where handler may be null. // If handler is not null, it indicates that this object // is being reused. if (handler != null) { close(); } openInternal(path, modes); if (block.isGiven()) { // getRuby().getRuntime().warn("File::new does not take block; use File::open instead"); } return this; } public IRubyObject chmod(IRubyObject arg) { RubyInteger mode = arg.convertToInteger(); File file = new File(path); if (!file.exists()) { throw getRuntime().newErrnoENOENTError("No such file or directory - " + path); } String modeString = Sprintf.sprintf(getRuntime(), "%o", mode.getLongValue()).toString(); Chmod.chmod(file, modeString); return getRuntime().newFixnum(0); } public IRubyObject chown(IRubyObject arg) { RubyInteger owner = arg.convertToInteger(); if (!new File(path).exists()) { throw getRuntime().newErrnoENOENTError("No such file or directory - " + path); } try { Process chown = Runtime.getRuntime().exec("chown " + owner + " " + path); chown.waitFor(); } catch (IOException ioe) { // FIXME: ignore? } catch (InterruptedException ie) { // FIXME: ignore? } return getRuntime().newFixnum(0); } public IRubyObject mtime() { return getRuntime().newTime(JRubyFile.create(getRuntime().getCurrentDirectory(),this.path).getParentFile().lastModified()); } public RubyString path() { return getRuntime().newString(path); } public IRubyObject stat() { return getRuntime().newRubyFileStat(path); } public IRubyObject truncate(IRubyObject arg) { RubyFixnum newLength = (RubyFixnum) arg.convertToType(getRuntime().getFixnum(), MethodIndex.TO_INT, "to_int", true); try { handler.truncate(newLength.getLongValue()); } catch (IOHandler.PipeException e) { throw getRuntime().newErrnoESPIPEError(); } catch (IOException e) { // Should we do anything? } return RubyFixnum.zero(getRuntime()); } public String toString() { return "RubyFile(" + path + ", " + modes + ", " + fileno + ")"; } // TODO: This is also defined in the MetaClass too...Consolidate somewhere. private static IOModes getModes(Ruby runtime, IRubyObject object) { if (object instanceof RubyString) { return new IOModes(runtime, ((RubyString)object).toString()); } else if (object instanceof RubyFixnum) { return new IOModes(runtime, ((RubyFixnum)object).getLongValue()); } throw runtime.newTypeError("Invalid type for modes"); } public IRubyObject inspect() { StringBuffer val = new StringBuffer(); val.append("#<File:").append(path); if(!isOpen()) { val.append(" (closed)"); } val.append(">"); return getRuntime().newString(val.toString()); } /* File class methods */ public static IRubyObject basename(IRubyObject recv, IRubyObject[] args) { Arity.checkArgumentCount(recv.getRuntime(), args, 1, 2); String name = RubyString.stringValue(args[0]).toString(); while (name.length() > 1 && name.charAt(name.length() - 1) == '/') { name = name.substring(0, name.length() - 1); } // Paths which end in "/" or "\\" must be stripped off. int slashCount = 0; int length = name.length(); for (int i = length - 1; i >= 0; i--) { char c = name.charAt(i); if (c != '/' && c != '\\') { break; } slashCount++; } if (slashCount > 0 && length > 1) { name = name.substring(0, name.length() - slashCount); } int index = name.lastIndexOf('/'); if (index == -1) { // XXX actually only on windows... index = name.lastIndexOf('\\'); } if (!name.equals("/") && index != -1) { name = name.substring(index + 1); } if (args.length == 2) { String ext = RubyString.stringValue(args[1]).toString(); if (".*".equals(ext)) { index = name.lastIndexOf('.'); if (index > 0) { // -1 no match; 0 it is dot file not extension name = name.substring(0, index); } } else if (name.endsWith(ext)) { name = name.substring(0, name.length() - ext.length()); } } return recv.getRuntime().newString(name).infectBy(args[0]); } public static IRubyObject chmod(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 2, -1); int count = 0; RubyInteger mode = args[0].convertToInteger(); for (int i = 1; i < args.length; i++) { IRubyObject filename = args[i]; if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) { throw runtime.newErrnoENOENTError("No such file or directory - " + filename); } String modeString = Sprintf.sprintf(runtime, "%o", mode.getLongValue()).toString(); boolean result = Chmod.chmod(JRubyFile.create(runtime.getCurrentDirectory(), filename.toString()), modeString); if (result) { count++; } } return runtime.newFixnum(count); } public static IRubyObject chown(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 2, -1); int count = 0; RubyInteger owner = args[0].convertToInteger(); for (int i = 1; i < args.length; i++) { IRubyObject filename = args[i]; if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) { throw runtime.newErrnoENOENTError("No such file or directory - " + filename); } try { Process chown = Runtime.getRuntime().exec("chown " + owner + " " + filename); chown.waitFor(); int result = chown.exitValue(); if (result == 0) { count++; } } catch (IOException ioe) { // FIXME: ignore? } catch (InterruptedException ie) { // FIXME: ignore? } } return runtime.newFixnum(count); } public static IRubyObject dirname(IRubyObject recv, IRubyObject arg) { RubyString filename = RubyString.stringValue(arg); String name = filename.toString().replace('\\', '/'); while (name.length() > 1 && name.charAt(name.length() - 1) == '/') { name = name.substring(0, name.length() - 1); } //TODO deal with drive letters A: and UNC names int index = name.lastIndexOf('/'); if (index == -1) return recv.getRuntime().newString("."); if (index == 0) return recv.getRuntime().newString("/"); return recv.getRuntime().newString(name.substring(0, index)).infectBy(filename); } /** * Returns the extension name of the file. An empty string is returned if * the filename (not the entire path) starts or ends with a dot. * @param recv * @param arg Path to get extension name of * @return Extension, including the dot, or an empty string */ public static IRubyObject extname(IRubyObject recv, IRubyObject arg) { IRubyObject baseFilename = basename(recv, new IRubyObject[] { arg }); String filename = RubyString.stringValue(baseFilename).toString(); String result = ""; int dotIndex = filename.lastIndexOf("."); if (dotIndex > 0 && dotIndex != (filename.length() - 1)) { // Dot is not at beginning and not at end of filename. result = filename.substring(dotIndex); } return recv.getRuntime().newString(result); } /** * Converts a pathname to an absolute pathname. Relative paths are * referenced from the current working directory of the process unless * a second argument is given, in which case it will be used as the * starting point. If the second argument is also relative, it will * first be converted to an absolute pathname. * @param recv * @param args * @return Resulting absolute path as a String */ public static IRubyObject expand_path(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 1, 2); String relativePath = RubyString.stringValue(args[0]).toString(); String cwd = null; // Handle ~user paths relativePath = expandUserPath(recv, relativePath); // If there's a second argument, it's the path to which the first // argument is relative. if (args.length == 2 && !args[1].isNil()) { String cwdArg = RubyString.stringValue(args[1]).toString(); // Handle ~user paths. cwd = expandUserPath(recv, cwdArg); // If the path isn't absolute, then prepend the current working // directory to the path. if ( cwd.charAt(0) != '/' ) { cwd = JRubyFile.create(runtime.getCurrentDirectory(), cwd) .getAbsolutePath(); } } else { // If there's no second argument, simply use the working directory // of the runtime. cwd = runtime.getCurrentDirectory(); } // Something wrong we don't know the cwd... // TODO: Is this behavior really desirable? /mov if (cwd == null) return runtime.getNil(); /* The counting of slashes that follows is simply a way to adhere to * Ruby's UNC (or something) compatibility. When Ruby's expand_path is * called with "//foo//bar" it will return "//foo/bar". JRuby uses * java.io.File, and hence returns "/foo/bar". In order to retain * java.io.File in the lower layers and provide full Ruby * compatibility, the number of extra slashes must be counted and * prepended to the result. */ // Find out which string to check. String padSlashes = ""; if (relativePath.length() > 0 && relativePath.charAt(0) == '/') { padSlashes = countSlashes(relativePath); } else if (cwd.length() > 0 && cwd.charAt(0) == '/') { padSlashes = countSlashes(cwd); } JRubyFile path = JRubyFile.create(cwd, relativePath); return runtime.newString(padSlashes + canonicalize(path.getAbsolutePath())); } /** * This method checks a path, and if it starts with ~, then it expands * the path to the absolute path of the user's home directory. If the * string does not begin with ~, then the string is simply retuned * unaltered. * @param recv * @param path Path to check * @return Expanded path */ private static String expandUserPath( IRubyObject recv, String path ) { int pathLength = path.length(); if (pathLength >= 1 && path.charAt(0) == '~') { // Enebo : Should ~frogger\\foo work (it doesnt in linux ruby)? int userEnd = path.indexOf('/'); if (userEnd == -1) { if (pathLength == 1) { // Single '~' as whole path to expand path = RubyDir.getHomeDirectoryPath(recv).toString(); } else { // No directory delimeter. Rest of string is username userEnd = pathLength; } } if (userEnd == 1) { // '~/...' as path to expand path = RubyDir.getHomeDirectoryPath(recv).toString() + path.substring(1); } else if (userEnd > 1){ // '~user/...' as path to expand String user = path.substring(1, userEnd); IRubyObject dir = RubyDir.getHomeDirectoryPath(recv, user); if (dir.isNil()) { Ruby runtime = recv.getRuntime(); throw runtime.newArgumentError("user " + user + " does not exist"); } path = "" + dir + (pathLength == userEnd ? "" : path.substring(userEnd)); } } return path; } /** * Returns a string consisting of <code>n-1</code> slashes, where * <code>n</code> is the number of slashes at the beginning of the input * string. * @param stringToCheck * @return */ private static String countSlashes( String stringToCheck ) { // Count number of extra slashes in the beginning of the string. int slashCount = 0; for (int i = 0; i < stringToCheck.length(); i++) { if (stringToCheck.charAt(i) == '/') { slashCount++; } else { break; } } // If there are N slashes, then we want N-1. if (slashCount > 0) { slashCount--; } // Prepare a string with the same number of redundant slashes so that // we easily can prepend it to the result. byte[] slashes = new byte[slashCount]; for (int i = 0; i < slashCount; i++) { slashes[i] = '/'; } return new String(slashes); } private static String canonicalize(String path) { return canonicalize(null, path); } private static String canonicalize(String canonicalPath, String remaining) { if (remaining == null) return canonicalPath; String child; int slash = remaining.indexOf('/'); if (slash == -1) { child = remaining; remaining = null; } else { child = remaining.substring(0, slash); remaining = remaining.substring(slash + 1); } if (child.equals(".")) { // skip it if (canonicalPath != null && canonicalPath.length() == 0 ) canonicalPath += "/"; } else if (child.equals("..")) { if (canonicalPath == null) throw new IllegalArgumentException("Cannot have .. at the start of an absolute path"); int lastDir = canonicalPath.lastIndexOf('/'); if (lastDir == -1) { canonicalPath = ""; } else { canonicalPath = canonicalPath.substring(0, lastDir); } } else if (canonicalPath == null) { canonicalPath = child; } else { canonicalPath += "/" + child; } return canonicalize(canonicalPath, remaining); } /** * Returns true if path matches against pattern The pattern is not a regular expression; * instead it follows rules similar to shell filename globbing. It may contain the following * metacharacters: * *: Glob - match any sequence chars (re: .*). If like begins with '.' then it doesn't. * ?: Matches a single char (re: .). * [set]: Matches a single char in a set (re: [...]). * */ public static IRubyObject fnmatch(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); int flags; if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) { flags = RubyNumeric.num2int(args[2]); } else { flags = 0; } ByteList pattern = args[0].convertToString().getByteList(); ByteList path = args[1].convertToString().getByteList(); if (org.jruby.util.Dir.fnmatch(pattern.bytes, 0, pattern.realSize , path.bytes, 0, path.realSize, flags) == 0) { return runtime.getTrue(); } return runtime.getFalse(); } /* * Fixme: This does not have exact same semantics as RubyArray.join, but they * probably could be consolidated (perhaps as join(args[], sep, doChomp)). */ public static RubyString join(IRubyObject recv, IRubyObject[] args) { boolean isTainted = false; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < args.length; i++) { if (args[i].isTaint()) { isTainted = true; } String element; if (args[i] instanceof RubyString) { element = args[i].toString(); } else if (args[i] instanceof RubyArray) { // Fixme: Need infinite recursion check to put [...] and not go into a loop element = join(recv, ((RubyArray) args[i]).toJavaArray()).toString(); } else { element = args[i].convertToString().toString(); } chomp(buffer); if (i > 0 && !element.startsWith("/") && !element.startsWith("\\")) { buffer.append("/"); } buffer.append(element); } RubyString fixedStr = RubyString.newString(recv.getRuntime(), buffer.toString()); fixedStr.setTaint(isTainted); return fixedStr; } private static void chomp(StringBuffer buffer) { int lastIndex = buffer.length() - 1; while (lastIndex >= 0 && (buffer.lastIndexOf("/") == lastIndex || buffer.lastIndexOf("\\") == lastIndex)) { buffer.setLength(lastIndex); lastIndex--; } } public static IRubyObject lstat(IRubyObject recv, IRubyObject filename) { RubyString name = RubyString.stringValue(filename); return recv.getRuntime().newRubyFileStat(name.toString()); } public static IRubyObject mtime(IRubyObject recv, IRubyObject filename) { Ruby runtime = recv.getRuntime(); RubyString name = RubyString.stringValue(filename); return runtime.newTime(JRubyFile.create(runtime.getCurrentDirectory(), name.toString()).lastModified()); } public static IRubyObject open(IRubyObject recv, IRubyObject[] args, Block block) { return open(recv, args, true, block); } public static IRubyObject open(IRubyObject recv, IRubyObject[] args, boolean tryToYield, Block block) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 1, -1); ThreadContext tc = runtime.getCurrentContext(); RubyString pathString = RubyString.stringValue(args[0]); runtime.checkSafeString(pathString); String path = pathString.toString(); IOModes modes = args.length >= 2 ? getModes(runtime, args[1]) : new IOModes(runtime, IOModes.RDONLY); RubyFile file = new RubyFile(runtime, (RubyClass) recv); RubyInteger fileMode = args.length >= 3 ? args[2].convertToInteger() : null; file.openInternal(path, modes); if (fileMode != null) { chmod(recv, new IRubyObject[] {fileMode, pathString}); } if (tryToYield && block.isGiven()) { try { return block.yield(tc, file); } finally { file.close(); } } return file; } public static IRubyObject rename(IRubyObject recv, IRubyObject oldName, IRubyObject newName) { Ruby runtime = recv.getRuntime(); RubyString oldNameString = RubyString.stringValue(oldName); RubyString newNameString = RubyString.stringValue(newName); runtime.checkSafeString(oldNameString); runtime.checkSafeString(newNameString); JRubyFile oldFile = JRubyFile.create(runtime.getCurrentDirectory(), oldNameString.toString()); JRubyFile newFile = JRubyFile.create(runtime.getCurrentDirectory(), newNameString.toString()); if (!oldFile.exists() || !newFile.getParentFile().exists()) { throw runtime.newErrnoENOENTError("No such file or directory - " + oldNameString + " or " + newNameString); } oldFile.renameTo(JRubyFile.create(runtime.getCurrentDirectory(), newNameString.toString())); return RubyFixnum.zero(runtime); } public static IRubyObject size_p(IRubyObject recv, IRubyObject filename) { long size = 0; try { FileInputStream fis = new FileInputStream(new File(filename.toString())); FileChannel chan = fis.getChannel(); size = chan.size(); chan.close(); fis.close(); } catch (IOException ioe) { // missing files or inability to open should just return nil } if (size == 0) return recv.getRuntime().getNil(); return recv.getRuntime().newFixnum(size); } public static RubyArray split(IRubyObject recv, IRubyObject arg) { RubyString filename = RubyString.stringValue(arg); return filename.getRuntime().newArray(dirname(recv, filename), basename(recv, new IRubyObject[] { filename })); } public static IRubyObject symlink(IRubyObject recv, IRubyObject from, IRubyObject to) { Ruby runtime = recv.getRuntime(); try { int result = new ShellLauncher(runtime).runAndWait(new IRubyObject[] { runtime.newString("ln"), runtime.newString("-s"), from, to }); return runtime.newFixnum(result); } catch (Exception e) { throw runtime.newNotImplementedError("symlinks"); } } public static IRubyObject symlink_p(IRubyObject recv, IRubyObject arg1) { Ruby runtime = recv.getRuntime(); RubyString filename = RubyString.stringValue(arg1); JRubyFile file = JRubyFile.create(runtime.getCurrentDirectory(), filename.toString()); try { // Only way to determine symlink is to compare canonical and absolute files // However symlinks in containing path must not produce false positives, so we check that first File absoluteParent = file.getAbsoluteFile().getParentFile(); File canonicalParent = file.getAbsoluteFile().getParentFile().getCanonicalFile(); if (canonicalParent.getAbsolutePath().equals(absoluteParent.getAbsolutePath())) { // parent doesn't change when canonicalized, compare absolute and canonical file directly return file.getAbsolutePath().equals(file.getCanonicalPath()) ? runtime.getFalse() : runtime.getTrue(); } // directory itself has symlinks (canonical != absolute), so build new path with canonical parent and compare file = JRubyFile.create(runtime.getCurrentDirectory(), canonicalParent.getAbsolutePath() + "/" + file.getName()); return file.getAbsolutePath().equals(file.getCanonicalPath()) ? runtime.getFalse() : runtime.getTrue(); } catch (IOException ioe) { // problem canonicalizing the file; nothing we can do but return false return runtime.getFalse(); } } // Can we produce IOError which bypasses a close? public static IRubyObject truncate(IRubyObject recv, IRubyObject arg1, IRubyObject arg2) { Ruby runtime = recv.getRuntime(); RubyString filename = RubyString.stringValue(arg1); RubyFixnum newLength = (RubyFixnum) arg2.convertToType(runtime.getFixnum(), MethodIndex.TO_INT, "to_int", true); IRubyObject[] args = new IRubyObject[] { filename, runtime.newString("w+") }; RubyFile file = (RubyFile) open(recv, args, false, null); file.truncate(newLength); file.close(); return RubyFixnum.zero(runtime); } /** * This method does NOT set atime, only mtime, since Java doesn't support anything else. */ public static IRubyObject utime(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); Arity.checkArgumentCount(runtime, args, 2, -1); // Ignore access_time argument since Java does not support it. long mtime; if (args[1] instanceof RubyTime) { mtime = ((RubyTime) args[1]).getJavaDate().getTime(); } else if (args[1] instanceof RubyNumeric) { mtime = RubyNumeric.num2long(args[1]); } else { mtime = 0; } for (int i = 2, j = args.length; i < j; i++) { RubyString filename = RubyString.stringValue(args[i]); runtime.checkSafeString(filename); JRubyFile fileToTouch = JRubyFile.create(runtime.getCurrentDirectory(),filename.toString()); if (!fileToTouch.exists()) { throw runtime.newErrnoENOENTError(" No such file or directory - \"" + filename + "\""); } fileToTouch.setLastModified(mtime); } return runtime.newFixnum(args.length - 2); } public static IRubyObject unlink(IRubyObject recv, IRubyObject[] args) { Ruby runtime = recv.getRuntime(); for (int i = 0; i < args.length; i++) { RubyString filename = RubyString.stringValue(args[i]); runtime.checkSafeString(filename); JRubyFile lToDelete = JRubyFile.create(runtime.getCurrentDirectory(),filename.toString()); if (!lToDelete.exists()) { throw runtime.newErrnoENOENTError(" No such file or directory - \"" + filename + "\""); } if (!lToDelete.delete()) return runtime.getFalse(); } return runtime.newFixnum(args.length); } }
true
true
public static RubyClass createFileClass(Ruby runtime) { RubyClass fileClass = runtime.defineClass("File", runtime.getClass("IO"), FILE_ALLOCATOR); CallbackFactory callbackFactory = runtime.callbackFactory(RubyFile.class); RubyClass fileMetaClass = fileClass.getMetaClass(); RubyString separator = runtime.newString("/"); separator.freeze(); fileClass.defineConstant("SEPARATOR", separator); fileClass.defineConstant("Separator", separator); RubyString altSeparator = runtime.newString(File.separatorChar == '/' ? "\\" : "/"); altSeparator.freeze(); fileClass.defineConstant("ALT_SEPARATOR", altSeparator); RubyString pathSeparator = runtime.newString(File.pathSeparator); pathSeparator.freeze(); fileClass.defineConstant("PATH_SEPARATOR", pathSeparator); // TODO: These were missing, so we're not handling them elsewhere? // FIXME: The old value, 32786, didn't match what IOModes expected, so I reference // the constant here. THIS MAY NOT BE THE CORRECT VALUE. fileClass.setConstant("BINARY", runtime.newFixnum(IOModes.BINARY)); fileClass.setConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE)); fileClass.setConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD)); fileClass.setConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH)); fileClass.setConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME)); // Create constants for open flags fileClass.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); fileClass.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); fileClass.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); fileClass.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); fileClass.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); fileClass.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); fileClass.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); fileClass.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); fileClass.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock fileClass.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); fileClass.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); fileClass.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); fileClass.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // Create Constants class RubyModule constants = fileClass.defineModuleUnder("Constants"); // TODO: These were missing, so we're not handling them elsewhere? constants.setConstant("BINARY", runtime.newFixnum(32768)); constants.setConstant("FNM_NOESCAPE", runtime.newFixnum(1)); constants.setConstant("FNM_CASEFOLD", runtime.newFixnum(8)); constants.setConstant("FNM_DOTMATCH", runtime.newFixnum(4)); constants.setConstant("FNM_PATHNAME", runtime.newFixnum(2)); // Create constants for open flags constants.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); constants.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); constants.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); constants.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); constants.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); constants.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); constants.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); constants.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); constants.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock constants.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); constants.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); constants.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); constants.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // TODO Singleton methods: blockdev?, chardev?, directory? // TODO Singleton methods: executable?, executable_real?, // TODO Singleton methods: ftype, grpowned?, lchmod, lchown, link, owned? // TODO Singleton methods: pipe?, readlink, setgid?, setuid?, socket?, // TODO Singleton methods: stat, sticky?, symlink?, umask runtime.getModule("FileTest").extend_object(fileClass); fileMetaClass.defineFastMethod("basename", callbackFactory.getFastOptSingletonMethod("basename")); fileMetaClass.defineFastMethod("chmod", callbackFactory.getFastOptSingletonMethod("chmod")); fileMetaClass.defineFastMethod("chown", callbackFactory.getFastOptSingletonMethod("chown")); fileMetaClass.defineFastMethod("delete", callbackFactory.getFastOptSingletonMethod("unlink")); fileMetaClass.defineFastMethod("dirname", callbackFactory.getFastSingletonMethod("dirname", IRubyObject.class)); fileMetaClass.defineFastMethod("expand_path", callbackFactory.getFastOptSingletonMethod("expand_path")); fileMetaClass.defineFastMethod("extname", callbackFactory.getFastSingletonMethod("extname", IRubyObject.class)); fileMetaClass.defineFastMethod("fnmatch", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("fnmatch?", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("join", callbackFactory.getFastOptSingletonMethod("join")); fileMetaClass.defineFastMethod("lstat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileMetaClass.defineFastMethod("atime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("mtime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("ctime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineMethod("open", callbackFactory.getOptSingletonMethod("open")); fileMetaClass.defineFastMethod("rename", callbackFactory.getFastSingletonMethod("rename", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("size?", callbackFactory.getFastSingletonMethod("size_p", IRubyObject.class)); fileMetaClass.defineFastMethod("split", callbackFactory.getFastSingletonMethod("split", IRubyObject.class)); fileMetaClass.defineFastMethod("stat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); fileMetaClass.defineFastMethod("symlink", callbackFactory.getFastSingletonMethod("symlink", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("symlink?", callbackFactory.getFastSingletonMethod("symlink_p", IRubyObject.class)); fileMetaClass.defineFastMethod("truncate", callbackFactory.getFastSingletonMethod("truncate", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("utime", callbackFactory.getFastOptSingletonMethod("utime")); fileMetaClass.defineFastMethod("unlink", callbackFactory.getFastOptSingletonMethod("unlink")); // TODO: Define instance methods: lchmod, lchown, lstat fileClass.defineFastMethod("chmod", callbackFactory.getFastMethod("chmod", IRubyObject.class)); fileClass.defineFastMethod("chown", callbackFactory.getFastMethod("chown", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileClass.defineFastMethod("atime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("ctime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("mtime", callbackFactory.getFastMethod("mtime")); fileClass.defineMethod("initialize", callbackFactory.getOptMethod("initialize")); fileClass.defineFastMethod("path", callbackFactory.getFastMethod("path")); fileClass.defineFastMethod("stat", callbackFactory.getFastMethod("stat")); fileClass.defineFastMethod("truncate", callbackFactory.getFastMethod("truncate", IRubyObject.class)); fileClass.defineFastMethod("flock", callbackFactory.getFastMethod("flock", IRubyObject.class)); RubyFileStat.createFileStatClass(runtime); return fileClass; }
public static RubyClass createFileClass(Ruby runtime) { RubyClass fileClass = runtime.defineClass("File", runtime.getClass("IO"), FILE_ALLOCATOR); CallbackFactory callbackFactory = runtime.callbackFactory(RubyFile.class); RubyClass fileMetaClass = fileClass.getMetaClass(); RubyString separator = runtime.newString("/"); separator.freeze(); fileClass.defineConstant("SEPARATOR", separator); fileClass.defineConstant("Separator", separator); if (File.separatorChar == '\\') { RubyString altSeparator = runtime.newString("\\"); altSeparator.freeze(); fileClass.defineConstant("ALT_SEPARATOR", altSeparator); } else { fileClass.defineConstant("ALT_SEPARATOR", runtime.getNil()); } RubyString pathSeparator = runtime.newString(File.pathSeparator); pathSeparator.freeze(); fileClass.defineConstant("PATH_SEPARATOR", pathSeparator); // TODO: These were missing, so we're not handling them elsewhere? // FIXME: The old value, 32786, didn't match what IOModes expected, so I reference // the constant here. THIS MAY NOT BE THE CORRECT VALUE. fileClass.setConstant("BINARY", runtime.newFixnum(IOModes.BINARY)); fileClass.setConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE)); fileClass.setConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD)); fileClass.setConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH)); fileClass.setConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME)); // Create constants for open flags fileClass.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); fileClass.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); fileClass.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); fileClass.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); fileClass.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); fileClass.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); fileClass.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); fileClass.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); fileClass.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock fileClass.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); fileClass.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); fileClass.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); fileClass.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // Create Constants class RubyModule constants = fileClass.defineModuleUnder("Constants"); // TODO: These were missing, so we're not handling them elsewhere? constants.setConstant("BINARY", runtime.newFixnum(32768)); constants.setConstant("FNM_NOESCAPE", runtime.newFixnum(1)); constants.setConstant("FNM_CASEFOLD", runtime.newFixnum(8)); constants.setConstant("FNM_DOTMATCH", runtime.newFixnum(4)); constants.setConstant("FNM_PATHNAME", runtime.newFixnum(2)); // Create constants for open flags constants.setConstant("RDONLY", runtime.newFixnum(IOModes.RDONLY)); constants.setConstant("WRONLY", runtime.newFixnum(IOModes.WRONLY)); constants.setConstant("RDWR", runtime.newFixnum(IOModes.RDWR)); constants.setConstant("CREAT", runtime.newFixnum(IOModes.CREAT)); constants.setConstant("EXCL", runtime.newFixnum(IOModes.EXCL)); constants.setConstant("NOCTTY", runtime.newFixnum(IOModes.NOCTTY)); constants.setConstant("TRUNC", runtime.newFixnum(IOModes.TRUNC)); constants.setConstant("APPEND", runtime.newFixnum(IOModes.APPEND)); constants.setConstant("NONBLOCK", runtime.newFixnum(IOModes.NONBLOCK)); // Create constants for flock constants.setConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH)); constants.setConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX)); constants.setConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB)); constants.setConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN)); // TODO Singleton methods: blockdev?, chardev?, directory? // TODO Singleton methods: executable?, executable_real?, // TODO Singleton methods: ftype, grpowned?, lchmod, lchown, link, owned? // TODO Singleton methods: pipe?, readlink, setgid?, setuid?, socket?, // TODO Singleton methods: stat, sticky?, symlink?, umask runtime.getModule("FileTest").extend_object(fileClass); fileMetaClass.defineFastMethod("basename", callbackFactory.getFastOptSingletonMethod("basename")); fileMetaClass.defineFastMethod("chmod", callbackFactory.getFastOptSingletonMethod("chmod")); fileMetaClass.defineFastMethod("chown", callbackFactory.getFastOptSingletonMethod("chown")); fileMetaClass.defineFastMethod("delete", callbackFactory.getFastOptSingletonMethod("unlink")); fileMetaClass.defineFastMethod("dirname", callbackFactory.getFastSingletonMethod("dirname", IRubyObject.class)); fileMetaClass.defineFastMethod("expand_path", callbackFactory.getFastOptSingletonMethod("expand_path")); fileMetaClass.defineFastMethod("extname", callbackFactory.getFastSingletonMethod("extname", IRubyObject.class)); fileMetaClass.defineFastMethod("fnmatch", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("fnmatch?", callbackFactory.getFastOptSingletonMethod("fnmatch")); fileMetaClass.defineFastMethod("join", callbackFactory.getFastOptSingletonMethod("join")); fileMetaClass.defineFastMethod("lstat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileMetaClass.defineFastMethod("atime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("mtime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineFastMethod("ctime", callbackFactory.getFastSingletonMethod("mtime", IRubyObject.class)); fileMetaClass.defineMethod("open", callbackFactory.getOptSingletonMethod("open")); fileMetaClass.defineFastMethod("rename", callbackFactory.getFastSingletonMethod("rename", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("size?", callbackFactory.getFastSingletonMethod("size_p", IRubyObject.class)); fileMetaClass.defineFastMethod("split", callbackFactory.getFastSingletonMethod("split", IRubyObject.class)); fileMetaClass.defineFastMethod("stat", callbackFactory.getFastSingletonMethod("lstat", IRubyObject.class)); fileMetaClass.defineFastMethod("symlink", callbackFactory.getFastSingletonMethod("symlink", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("symlink?", callbackFactory.getFastSingletonMethod("symlink_p", IRubyObject.class)); fileMetaClass.defineFastMethod("truncate", callbackFactory.getFastSingletonMethod("truncate", IRubyObject.class, IRubyObject.class)); fileMetaClass.defineFastMethod("utime", callbackFactory.getFastOptSingletonMethod("utime")); fileMetaClass.defineFastMethod("unlink", callbackFactory.getFastOptSingletonMethod("unlink")); // TODO: Define instance methods: lchmod, lchown, lstat fileClass.defineFastMethod("chmod", callbackFactory.getFastMethod("chmod", IRubyObject.class)); fileClass.defineFastMethod("chown", callbackFactory.getFastMethod("chown", IRubyObject.class)); // atime and ctime are implemented like mtime, since we don't have an atime API in Java fileClass.defineFastMethod("atime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("ctime", callbackFactory.getFastMethod("mtime")); fileClass.defineFastMethod("mtime", callbackFactory.getFastMethod("mtime")); fileClass.defineMethod("initialize", callbackFactory.getOptMethod("initialize")); fileClass.defineFastMethod("path", callbackFactory.getFastMethod("path")); fileClass.defineFastMethod("stat", callbackFactory.getFastMethod("stat")); fileClass.defineFastMethod("truncate", callbackFactory.getFastMethod("truncate", IRubyObject.class)); fileClass.defineFastMethod("flock", callbackFactory.getFastMethod("flock", IRubyObject.class)); RubyFileStat.createFileStatClass(runtime); return fileClass; }