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/compass2/web/src/main/java/no/ovitas/compass2/webapp/action/KBModelExportAction.java b/compass2/web/src/main/java/no/ovitas/compass2/webapp/action/KBModelExportAction.java index a7c3ad2..b56621f 100644 --- a/compass2/web/src/main/java/no/ovitas/compass2/webapp/action/KBModelExportAction.java +++ b/compass2/web/src/main/java/no/ovitas/compass2/webapp/action/KBModelExportAction.java @@ -1,88 +1,89 @@ /** * */ package no.ovitas.compass2.webapp.action; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.servlet.ServletOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import no.ovitas.compass2.Constants; import no.ovitas.compass2.dao.xml.KBBuilderXtmDaoXml; import no.ovitas.compass2.model.KnowledgeBaseHolder; import no.ovitas.compass2.service.ConfigurationManager; import no.ovitas.compass2.service.ExportDomainModelManager; import no.ovitas.compass2.service.factory.KBFactory; import no.ovitas.compass2.service.impl.ExportDomainModel2PlainTextManagerImpl; import com.opensymphony.xwork2.Preparable; /** * @author magyar * */ public class KBModelExportAction extends BaseAction implements Preparable { private static final Log log = LogFactory.getLog(KBModelExportAction.class); protected ExportDomainModelManager exportDomainModelManager; public void setExportDomainModelManager( ExportDomainModelManager exportDomainModelManager) { this.exportDomainModelManager = exportDomainModelManager; } /** * */ public KBModelExportAction() { // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.opensymphony.xwork2.Preparable#prepare() */ @Override public void prepare() throws Exception { // TODO Auto-generated method stub } public String execute(){ log.info("KBModelExportAction.execute()"); String fileName = null; try { fileName = this.exportDomainModelManager.exportModel(); File f = new File(fileName); FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bi = new BufferedInputStream(fis); f.length(); byte[] b = new byte[(int) f.length()]; bi.read(b); bi.close(); getResponse().setContentType("application/plain"); getResponse().setContentLength(b.length); getResponse().setHeader("Expires", "0"); getResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); getResponse().setHeader("Content-Disposition", "attachment; filename=\"model.txt\""); getResponse().setHeader("Pragma", "public"); getResponse().getOutputStream().write(b); + getResponse().getOutputStream().close(); } catch (FileNotFoundException fnfe) { log.error("File not found: " + fileName + ", " + fnfe.getMessage()); } catch (Exception e) { log.error("Error occured: " + e.getMessage()); } return NONE; } }
true
true
public String execute(){ log.info("KBModelExportAction.execute()"); String fileName = null; try { fileName = this.exportDomainModelManager.exportModel(); File f = new File(fileName); FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bi = new BufferedInputStream(fis); f.length(); byte[] b = new byte[(int) f.length()]; bi.read(b); bi.close(); getResponse().setContentType("application/plain"); getResponse().setContentLength(b.length); getResponse().setHeader("Expires", "0"); getResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); getResponse().setHeader("Content-Disposition", "attachment; filename=\"model.txt\""); getResponse().setHeader("Pragma", "public"); getResponse().getOutputStream().write(b); } catch (FileNotFoundException fnfe) { log.error("File not found: " + fileName + ", " + fnfe.getMessage()); } catch (Exception e) { log.error("Error occured: " + e.getMessage()); } return NONE; }
public String execute(){ log.info("KBModelExportAction.execute()"); String fileName = null; try { fileName = this.exportDomainModelManager.exportModel(); File f = new File(fileName); FileInputStream fis = new FileInputStream(fileName); BufferedInputStream bi = new BufferedInputStream(fis); f.length(); byte[] b = new byte[(int) f.length()]; bi.read(b); bi.close(); getResponse().setContentType("application/plain"); getResponse().setContentLength(b.length); getResponse().setHeader("Expires", "0"); getResponse().setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); getResponse().setHeader("Content-Disposition", "attachment; filename=\"model.txt\""); getResponse().setHeader("Pragma", "public"); getResponse().getOutputStream().write(b); getResponse().getOutputStream().close(); } catch (FileNotFoundException fnfe) { log.error("File not found: " + fileName + ", " + fnfe.getMessage()); } catch (Exception e) { log.error("Error occured: " + e.getMessage()); } return NONE; }
diff --git a/rat/rat-core/src/test/java/org/apache/rat/ReportTest.java b/rat/rat-core/src/test/java/org/apache/rat/ReportTest.java index 52f66355..0212e24c 100644 --- a/rat/rat-core/src/test/java/org/apache/rat/ReportTest.java +++ b/rat/rat-core/src/test/java/org/apache/rat/ReportTest.java @@ -1,109 +1,109 @@ /* * 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.rat; import java.io.File; import java.io.StringWriter; import junit.framework.TestCase; import org.apache.rat.analysis.util.HeaderMatcherMultiplexer; import org.apache.rat.test.utils.Resources; public class ReportTest extends TestCase { private static String getElementsReports(String pElementsPath) { return "\n" + "*****************************************************\n" + "Summary\n" + "-------\n" + "Notes: 2\n" + "Binaries: 1\n" + "Archives: 1\n" + "Standards: 4\n" + "\n" + "Apache Licensed: 2\n" + "Generated Documents: 0\n" + "\n" + "JavaDocs are generated and so license header is optional\n" + "Generated files do not required license headers\n" + "\n" + "2 Unknown Licenses\n" + "\n" + "*******************************\n" + "\n" + "Archives (+ indicates readable, $ unreadable): \n" + "\n" + " + " + pElementsPath + "/dummy.jar\n" + " \n" + "*****************************************************\n" + " Files with AL headers will be marked L\n" + " Binary files (which do not require AL headers) will be marked B\n" + " Compressed archives will be marked A\n" + " Notices, licenses etc will be marked N\n" + " B " + pElementsPath + "/Image.png\n" + " N " + pElementsPath + "/LICENSE\n" + " N " + pElementsPath + "/NOTICE\n" + " !????? " + pElementsPath + "/Source.java\n" + " AL " + pElementsPath + "/Text.txt\n" + " AL " + pElementsPath + "/Xml.xml\n" + " A " + pElementsPath + "/dummy.jar\n" + " !????? " + pElementsPath + "/sub/Empty.txt\n" + " \n" + " *****************************************************\n" + " Printing headers for files without AL header...\n" + " \n" + " \n" + " =======================================================================\n" + " ==" + pElementsPath + "/Source.java\n" + " =======================================================================\n" + - " package elements;\n" + + "package elements;\n" + "\n" + "public class Source {\n" + "\n" + "}\n" + "\n" + " =======================================================================\n" + " ==" + pElementsPath + "/sub/Empty.txt\n" + " =======================================================================\n" + - " "; + ""; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testPlainReport() throws Exception { StringWriter out = new StringWriter(); HeaderMatcherMultiplexer matcherMultiplexer = new HeaderMatcherMultiplexer(Defaults.DEFAULT_MATCHERS); final String elementsPath = Resources.getResourceDirectory("elements/Source.java"); Report.report(out, new DirectoryWalker(new File(elementsPath)), Defaults.getPlainStyleSheet(), matcherMultiplexer, null); String result = out.getBuffer().toString(); final String elementsReports = getElementsReports(elementsPath); assertEquals("Report created", elementsReports.replaceAll("\n", System.getProperty("line.separator")), result); } }
false
true
private static String getElementsReports(String pElementsPath) { return "\n" + "*****************************************************\n" + "Summary\n" + "-------\n" + "Notes: 2\n" + "Binaries: 1\n" + "Archives: 1\n" + "Standards: 4\n" + "\n" + "Apache Licensed: 2\n" + "Generated Documents: 0\n" + "\n" + "JavaDocs are generated and so license header is optional\n" + "Generated files do not required license headers\n" + "\n" + "2 Unknown Licenses\n" + "\n" + "*******************************\n" + "\n" + "Archives (+ indicates readable, $ unreadable): \n" + "\n" + " + " + pElementsPath + "/dummy.jar\n" + " \n" + "*****************************************************\n" + " Files with AL headers will be marked L\n" + " Binary files (which do not require AL headers) will be marked B\n" + " Compressed archives will be marked A\n" + " Notices, licenses etc will be marked N\n" + " B " + pElementsPath + "/Image.png\n" + " N " + pElementsPath + "/LICENSE\n" + " N " + pElementsPath + "/NOTICE\n" + " !????? " + pElementsPath + "/Source.java\n" + " AL " + pElementsPath + "/Text.txt\n" + " AL " + pElementsPath + "/Xml.xml\n" + " A " + pElementsPath + "/dummy.jar\n" + " !????? " + pElementsPath + "/sub/Empty.txt\n" + " \n" + " *****************************************************\n" + " Printing headers for files without AL header...\n" + " \n" + " \n" + " =======================================================================\n" + " ==" + pElementsPath + "/Source.java\n" + " =======================================================================\n" + " package elements;\n" + "\n" + "public class Source {\n" + "\n" + "}\n" + "\n" + " =======================================================================\n" + " ==" + pElementsPath + "/sub/Empty.txt\n" + " =======================================================================\n" + " "; }
private static String getElementsReports(String pElementsPath) { return "\n" + "*****************************************************\n" + "Summary\n" + "-------\n" + "Notes: 2\n" + "Binaries: 1\n" + "Archives: 1\n" + "Standards: 4\n" + "\n" + "Apache Licensed: 2\n" + "Generated Documents: 0\n" + "\n" + "JavaDocs are generated and so license header is optional\n" + "Generated files do not required license headers\n" + "\n" + "2 Unknown Licenses\n" + "\n" + "*******************************\n" + "\n" + "Archives (+ indicates readable, $ unreadable): \n" + "\n" + " + " + pElementsPath + "/dummy.jar\n" + " \n" + "*****************************************************\n" + " Files with AL headers will be marked L\n" + " Binary files (which do not require AL headers) will be marked B\n" + " Compressed archives will be marked A\n" + " Notices, licenses etc will be marked N\n" + " B " + pElementsPath + "/Image.png\n" + " N " + pElementsPath + "/LICENSE\n" + " N " + pElementsPath + "/NOTICE\n" + " !????? " + pElementsPath + "/Source.java\n" + " AL " + pElementsPath + "/Text.txt\n" + " AL " + pElementsPath + "/Xml.xml\n" + " A " + pElementsPath + "/dummy.jar\n" + " !????? " + pElementsPath + "/sub/Empty.txt\n" + " \n" + " *****************************************************\n" + " Printing headers for files without AL header...\n" + " \n" + " \n" + " =======================================================================\n" + " ==" + pElementsPath + "/Source.java\n" + " =======================================================================\n" + "package elements;\n" + "\n" + "public class Source {\n" + "\n" + "}\n" + "\n" + " =======================================================================\n" + " ==" + pElementsPath + "/sub/Empty.txt\n" + " =======================================================================\n" + ""; }
diff --git a/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java b/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java index aa439a570..6c12c939c 100644 --- a/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java +++ b/swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeMenus.java @@ -1,122 +1,121 @@ /* File: CytoscapeMenus.java Copyright (c) 2006, 2010, The Cytoscape Consortium (www.cytoscape.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or 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. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package org.cytoscape.internal.view; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JToolBar; import org.cytoscape.application.swing.CyAction; public class CytoscapeMenus { final private CytoscapeMenuBar menuBar; final private CytoscapeToolBar toolBar; public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) { this.menuBar = menuBar; this.toolBar = toolBar; menuBar.addMenu("File", 0.0); menuBar.addMenu("File.New", 0.0); menuBar.addMenu("File.New.Network", 0.0); menuBar.addMenu("File.Import", 5.0); menuBar.addMenu("File.Export", 5.1); menuBar.addMenu("Edit", 0.0); menuBar.addMenu("View", 0.0); menuBar.addMenu("Select", 0.0); menuBar.addMenu("Select.Nodes", 1.0); menuBar.addMenu("Select.Edges", 1.1); menuBar.addMenu("Layout", 0.0); menuBar.addMenu("Plugins", 0.0); menuBar.addMenu("Tools", 0.0); menuBar.addMenu("Help", 0.0); menuBar.addSeparator("File", 2.0); menuBar.addSeparator("File", 4.0); menuBar.addSeparator("File", 6.0); menuBar.addSeparator("File", 8.0); menuBar.addSeparator("Edit", 2.0); menuBar.addSeparator("Edit", 4.0); menuBar.addSeparator("Edit", 6.0); menuBar.addMenu("Edit.Preferences", 10.0); menuBar.addSeparator("View", 2.0); - menuBar.addSeparator("View", 4.0); menuBar.addSeparator("View", 6.0); menuBar.addSeparator("Select", 2.0); menuBar.addSeparator("Select", 4.0); menuBar.addSeparator("Select", 6.0); menuBar.addSeparator("Layout", 2.0); menuBar.addSeparator("Layout", 4.0); menuBar.addSeparator("Layout", 6.0); menuBar.addSeparator("Plugins", 2.0); menuBar.addSeparator("Help", 2.0); toolBar.addSeparator(2.0f); toolBar.addSeparator(4.0f); toolBar.addSeparator(6.0f); toolBar.addSeparator(8.0f); } public JMenu getJMenu(String s) { return menuBar.getMenu(s); } public JMenuBar getJMenuBar() { return menuBar; } public JToolBar getJToolBar() { return toolBar; } public void removeAction(CyAction action) { if (action.isInMenuBar()) menuBar.removeAction(action); if (action.isInToolBar()) toolBar.removeAction(action); } public void addAction(CyAction action) { if (action.isInMenuBar()) menuBar.addAction(action); if (action.isInToolBar()) toolBar.addAction(action); } }
true
true
public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) { this.menuBar = menuBar; this.toolBar = toolBar; menuBar.addMenu("File", 0.0); menuBar.addMenu("File.New", 0.0); menuBar.addMenu("File.New.Network", 0.0); menuBar.addMenu("File.Import", 5.0); menuBar.addMenu("File.Export", 5.1); menuBar.addMenu("Edit", 0.0); menuBar.addMenu("View", 0.0); menuBar.addMenu("Select", 0.0); menuBar.addMenu("Select.Nodes", 1.0); menuBar.addMenu("Select.Edges", 1.1); menuBar.addMenu("Layout", 0.0); menuBar.addMenu("Plugins", 0.0); menuBar.addMenu("Tools", 0.0); menuBar.addMenu("Help", 0.0); menuBar.addSeparator("File", 2.0); menuBar.addSeparator("File", 4.0); menuBar.addSeparator("File", 6.0); menuBar.addSeparator("File", 8.0); menuBar.addSeparator("Edit", 2.0); menuBar.addSeparator("Edit", 4.0); menuBar.addSeparator("Edit", 6.0); menuBar.addMenu("Edit.Preferences", 10.0); menuBar.addSeparator("View", 2.0); menuBar.addSeparator("View", 4.0); menuBar.addSeparator("View", 6.0); menuBar.addSeparator("Select", 2.0); menuBar.addSeparator("Select", 4.0); menuBar.addSeparator("Select", 6.0); menuBar.addSeparator("Layout", 2.0); menuBar.addSeparator("Layout", 4.0); menuBar.addSeparator("Layout", 6.0); menuBar.addSeparator("Plugins", 2.0); menuBar.addSeparator("Help", 2.0); toolBar.addSeparator(2.0f); toolBar.addSeparator(4.0f); toolBar.addSeparator(6.0f); toolBar.addSeparator(8.0f); }
public CytoscapeMenus(CytoscapeMenuBar menuBar, CytoscapeToolBar toolBar) { this.menuBar = menuBar; this.toolBar = toolBar; menuBar.addMenu("File", 0.0); menuBar.addMenu("File.New", 0.0); menuBar.addMenu("File.New.Network", 0.0); menuBar.addMenu("File.Import", 5.0); menuBar.addMenu("File.Export", 5.1); menuBar.addMenu("Edit", 0.0); menuBar.addMenu("View", 0.0); menuBar.addMenu("Select", 0.0); menuBar.addMenu("Select.Nodes", 1.0); menuBar.addMenu("Select.Edges", 1.1); menuBar.addMenu("Layout", 0.0); menuBar.addMenu("Plugins", 0.0); menuBar.addMenu("Tools", 0.0); menuBar.addMenu("Help", 0.0); menuBar.addSeparator("File", 2.0); menuBar.addSeparator("File", 4.0); menuBar.addSeparator("File", 6.0); menuBar.addSeparator("File", 8.0); menuBar.addSeparator("Edit", 2.0); menuBar.addSeparator("Edit", 4.0); menuBar.addSeparator("Edit", 6.0); menuBar.addMenu("Edit.Preferences", 10.0); menuBar.addSeparator("View", 2.0); menuBar.addSeparator("View", 6.0); menuBar.addSeparator("Select", 2.0); menuBar.addSeparator("Select", 4.0); menuBar.addSeparator("Select", 6.0); menuBar.addSeparator("Layout", 2.0); menuBar.addSeparator("Layout", 4.0); menuBar.addSeparator("Layout", 6.0); menuBar.addSeparator("Plugins", 2.0); menuBar.addSeparator("Help", 2.0); toolBar.addSeparator(2.0f); toolBar.addSeparator(4.0f); toolBar.addSeparator(6.0f); toolBar.addSeparator(8.0f); }
diff --git a/src/com/android/browser/BrowserActivity.java b/src/com/android/browser/BrowserActivity.java index b2a1cbc7..438b3868 100644 --- a/src/com/android/browser/BrowserActivity.java +++ b/src/com/android/browser/BrowserActivity.java @@ -1,3734 +1,3732 @@ /* * Copyright (C) 2006 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.browser; import com.google.android.googleapps.IGoogleLoginService; import com.google.android.googlelogin.GoogleLoginServiceConstants; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Picture; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.WebAddress; import android.net.http.SslCertificate; import android.net.http.SslError; import android.os.AsyncTask; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.provider.Browser; import android.provider.ContactsContract; import android.provider.ContactsContract.Intents.Insert; import android.provider.Downloads; import android.provider.MediaStore; import android.text.IClipboard; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.util.Regex; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem.OnMenuItemClickListener; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.DownloadListener; import android.webkit.HttpAuthHandler; import android.webkit.PluginManager; import android.webkit.SslErrorHandler; import android.webkit.URLUtil; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebHistoryItem; import android.webkit.WebIconDatabase; import android.webkit.WebView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class BrowserActivity extends Activity implements View.OnCreateContextMenuListener, DownloadListener { /* Define some aliases to make these debugging flags easier to refer to. * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG". */ private final static boolean DEBUG = com.android.browser.Browser.DEBUG; private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED; private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; private IGoogleLoginService mGls = null; private ServiceConnection mGlsConnection = null; // These are single-character shortcuts for searching popular sources. private static final int SHORTCUT_INVALID = 0; private static final int SHORTCUT_GOOGLE_SEARCH = 1; private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2; private static final int SHORTCUT_DICTIONARY_SEARCH = 3; private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4; private void setupHomePage() { final Runnable getAccount = new Runnable() { public void run() { // Lower priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // get the default home page String homepage = mSettings.getHomePage(); try { if (mGls == null) return; if (!homepage.startsWith("http://www.google.")) return; if (homepage.indexOf('?') == -1) return; String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED); String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE); // three cases: // // hostedUser == googleUser // The device has only a google account // // hostedUser != googleUser // The device has a hosted account and a google account // // hostedUser != null, googleUser == null // The device has only a hosted account (so far) // developers might have no accounts at all if (hostedUser == null) return; if (googleUser == null || !hostedUser.equals(googleUser)) { String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1); homepage = homepage.replace("?", "/a/" + domain + "?"); } } catch (RemoteException ignore) { // Login service died; carry on } catch (RuntimeException ignore) { // Login service died; carry on } finally { finish(homepage); } } private void finish(final String homepage) { mHandler.post(new Runnable() { public void run() { mSettings.setHomePage(BrowserActivity.this, homepage); resumeAfterCredentials(); // as this is running in a separate thread, // BrowserActivity's onDestroy() may have been called, // which also calls unbindService(). if (mGlsConnection != null) { // we no longer need to keep GLS open unbindService(mGlsConnection); mGlsConnection = null; } } }); } }; final boolean[] done = { false }; // Open a connection to the Google Login Service. The first // time the connection is established, set up the homepage depending on // the account in a background thread. mGlsConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mGls = IGoogleLoginService.Stub.asInterface(service); if (done[0] == false) { done[0] = true; Thread account = new Thread(getAccount); account.setName("GLSAccount"); account.start(); } } public void onServiceDisconnected(ComponentName className) { mGls = null; } }; bindService(GoogleLoginServiceConstants.SERVICE_INTENT, mGlsConnection, Context.BIND_AUTO_CREATE); } private static class ClearThumbnails extends AsyncTask<File, Void, Void> { @Override public Void doInBackground(File... files) { if (files != null) { for (File f : files) { if (!f.delete()) { Log.e(LOGTAG, f.getPath() + " was not deleted"); } } } return null; } } /** * This layout holds everything you see below the status bar, including the * error console, the custom view container, and the webviews. */ private FrameLayout mBrowserFrameLayout; @Override public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); mFakeTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { - NetworkInfo info = - (NetworkInfo) intent.getParcelableExtra( - ConnectivityManager.EXTRA_NETWORK_INFO); - onNetworkToggle( - (info != null) ? info.isConnected() : false); + boolean noConnectivity = intent.getBooleanExtra( + ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + onNetworkToggle(!noConnectivity); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } } @Override protected void onNewIntent(Intent intent) { Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mTabControl.setCurrentTab(current); attachTabToContentView(current); resetTitleAndIcon(current.getWebView()); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } urlData.setPostData(intent .getByteArrayExtra(Browser.EXTRA_POST_DATA)); final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (Intent.ACTION_VIEW.equals(action) && !getPackageName().equals(appId) && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { Tab appTab = mTabControl.getTabFromId(appId); if (appTab != null) { Log.i(LOGTAG, "Reusing tab for " + appId); // Dismiss the subwindow if applicable. dismissSubWindow(appTab); // Since we might kill the WebView, remove it from the // content view first. removeTabFromContentView(appTab); // Recreate the main WebView after destroying the old one. // If the WebView has the same original url and is on that // page, it can be reused. boolean needsLoad = mTabControl.recreateWebView(appTab, urlData.mUrl); if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } else { // If the tab was the current tab, we have to attach // it to the view system again. attachTabToContentView(appTab); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } return; } else { // No matching application tab, try to find a regular tab // with a matching url. appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl); if (appTab != null) { if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. openTabAndShow(urlData, true, appId); } } } else { if ("about:debug".equals(urlData.mUrl)) { mSettings.toggleDebugSettings(); return; } // Get rid of the subwindow if it exists dismissSubWindow(current); urlData.loadIn(current.getWebView()); } } } private int parseUrlShortcut(String url) { if (url == null) return SHORTCUT_INVALID; // FIXME: quick search, need to be customized by setting if (url.length() > 2 && url.charAt(1) == ' ') { switch (url.charAt(0)) { case 'g': return SHORTCUT_GOOGLE_SEARCH; case 'w': return SHORTCUT_WIKIPEDIA_SEARCH; case 'd': return SHORTCUT_DICTIONARY_SEARCH; case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH; } } return SHORTCUT_INVALID; } /** * Launches the default web search activity with the query parameters if the given intent's data * are identified as plain search terms and not URLs/shortcuts. * @return true if the intent was handled and web search activity was launched, false if not. */ private boolean handleWebSearchIntent(Intent intent) { if (intent == null) return false; String url = null; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { Uri data = intent.getData(); if (data != null) url = data.toString(); } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); } return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA), intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } /** * Launches the default web search activity with the query parameters if the given url string * was identified as plain search terms and not URL/shortcut. * @return true if the request was handled and web search activity was launched, false if not. */ private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) { if (inUrl == null) return false; // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. String url = fixUrl(inUrl).trim(); // URLs and site specific search shortcuts are handled by the regular flow of control, so // return early. if (Regex.WEB_URL_PATTERN.matcher(url).matches() || ACCEPTED_URI_SCHEMA.matcher(url).matches() || parseUrlShortcut(url) != SHORTCUT_INVALID) { return false; } Browser.updateVisitedHistory(mResolver, url, false); Browser.addSearchUrl(mResolver, url); Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(SearchManager.QUERY, url); if (appData != null) { intent.putExtra(SearchManager.APP_DATA, appData); } if (extraData != null) { intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName()); startActivity(intent); return true; } private UrlData getUrlDataFromIntent(Intent intent) { String url = null; if (intent != null) { final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { url = smartUrlFilter(intent.getData()); if (url != null && url.startsWith("content:")) { /* Append mimetype so webview knows how to display */ String mimeType = intent.resolveType(getContentResolver()); if (mimeType != null) { url += "?" + mimeType; } } if ("inline:".equals(url)) { return new InlinedUrlData( intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT), intent.getType(), intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING), intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL)); } } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); if (url != null) { mLastEnteredUrl = url; // Don't add Urls, just search terms. // Urls will get added when the page is loaded. if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) { Browser.updateVisitedHistory(mResolver, url, false); } // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. url = fixUrl(url); url = smartUrlFilter(url); String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; if (url.contains(searchSource)) { String source = null; final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { source = appData.getString(SearchManager.SOURCE); } if (TextUtils.isEmpty(source)) { source = GOOGLE_SEARCH_SOURCE_UNKNOWN; } url = url.replace(searchSource, "&source=android-"+source+"&"); } } } } return new UrlData(url); } /* package */ static String fixUrl(String inUrl) { // FIXME: Converting the url to lower case // duplicates functionality in smartUrlFilter(). // However, changing all current callers of fixUrl to // call smartUrlFilter in addition may have unwanted // consequences, and is deferred for now. int colon = inUrl.indexOf(':'); boolean allLower = true; for (int index = 0; index < colon; index++) { char ch = inUrl.charAt(index); if (!Character.isLetter(ch)) { break; } allLower &= Character.isLowerCase(ch); if (index == colon - 1 && !allLower) { inUrl = inUrl.substring(0, colon).toLowerCase() + inUrl.substring(colon); } } if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) return inUrl; if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) { if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { inUrl = inUrl.replaceFirst("/", "//"); } else inUrl = inUrl.replaceFirst(":", "://"); } return inUrl; } @Override protected void onResume() { super.onResume(); if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this); } if (!mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already resumed."); return; } mTabControl.resumeCurrentTab(); mActivityInPause = false; resumeWebViewTimers(); if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } if (mCredsDlg != null) { if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) { // In case credential request never comes back mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000); } } registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter); WebView.enablePlatformNotifications(); } /** * Since the actual title bar is embedded in the WebView, and removing it * would change its appearance, use a different TitleBar to show overlayed * at the top of the screen, when the menu is open or the page is loading. */ private TitleBar mFakeTitleBar; /** * Holder for the fake title bar. It will have a foreground shadow, as well * as a white background, so the fake title bar looks like the real one. */ private ViewGroup mFakeTitleBarHolder; /** * Layout parameters for the fake title bar within mFakeTitleBarHolder */ private FrameLayout.LayoutParams mFakeTitleBarParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); /** * Keeps track of whether the options menu is open. This is important in * determining whether to show or hide the title bar overlay. */ private boolean mOptionsMenuOpen; /** * Only meaningful when mOptionsMenuOpen is true. This variable keeps track * of whether the configuration has changed. The first onMenuOpened call * after a configuration change is simply a reopening of the same menu * (i.e. mIconView did not change). */ private boolean mConfigChanged; /** * Whether or not the options menu is in its smaller, icon menu form. When * true, we want the title bar overlay to be up. When false, we do not. * Only meaningful if mOptionsMenuOpen is true. */ private boolean mIconView; @Override public boolean onMenuOpened(int featureId, Menu menu) { if (Window.FEATURE_OPTIONS_PANEL == featureId) { if (mOptionsMenuOpen) { if (mConfigChanged) { // We do not need to make any changes to the state of the // title bar, since the only thing that happened was a // change in orientation mConfigChanged = false; } else { if (mIconView) { // Switching the menu to expanded view, so hide the // title bar. hideFakeTitleBar(); mIconView = false; } else { // Switching the menu back to icon view, so show the // title bar once again. showFakeTitleBar(); mIconView = true; } } } else { // The options menu is closed, so open it, and show the title showFakeTitleBar(); mOptionsMenuOpen = true; mConfigChanged = false; mIconView = true; } } return true; } /** * Special class used exclusively for the shadow drawn underneath the fake * title bar. The shadow does not need to be drawn if the WebView * underneath is scrolled to the top, because it will draw directly on top * of the embedded shadow. */ private static class Shadow extends View { private WebView mWebView; public Shadow(Context context, AttributeSet attrs) { super(context, attrs); } public void setWebView(WebView view) { mWebView = view; } @Override public void draw(Canvas canvas) { // In general onDraw is the method to override, but we care about // whether or not the background gets drawn, which happens in draw() if (mWebView == null || mWebView.getScrollY() > getHeight()) { super.draw(canvas); } // Need to invalidate so that if the scroll position changes, we // still draw as appropriate. invalidate(); } } private void showFakeTitleBar() { final View decor = getWindow().peekDecorView(); if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null && !mActivityInPause && decor != null && decor.getWindowToken() != null) { Rect visRect = new Rect(); if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) { if (LOGD_ENABLED) { Log.d(LOGTAG, "showFakeTitleBar visRect failed"); } return; } WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); // Add the title bar to the window manager so it can receive touches // while the menu is up WindowManager.LayoutParams params = new WindowManager.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP; WebView mainView = mTabControl.getCurrentWebView(); boolean atTop = mainView != null && mainView.getScrollY() == 0; params.windowAnimations = atTop ? 0 : R.style.TitleBar; // XXX : Without providing an offset, the fake title bar will be // placed underneath the status bar. Use the global visible rect // of mBrowserFrameLayout to determine the bottom of the status bar params.y = visRect.top; // Add a holder for the title bar. It also holds a shadow to show // below the title bar. if (mFakeTitleBarHolder == null) { mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this) .inflate(R.layout.title_bar_bg, null); } Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById( R.id.shadow); shadow.setWebView(mainView); mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams); manager.addView(mFakeTitleBarHolder, params); } } @Override public void onOptionsMenuClosed(Menu menu) { mOptionsMenuOpen = false; if (!mInLoad) { hideFakeTitleBar(); } else if (!mIconView) { // The page is currently loading, and we are in expanded mode, so // we were not showing the menu. Show it once again. It will be // removed when the page finishes. showFakeTitleBar(); } } private void hideFakeTitleBar() { if (mFakeTitleBar.getParent() == null) return; WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFakeTitleBarHolder.getLayoutParams(); WebView mainView = mTabControl.getCurrentWebView(); // Although we decided whether or not to animate based on the current // scroll position, the scroll position may have changed since the // fake title bar was displayed. Make sure it has the appropriate // animation/lack thereof before removing. params.windowAnimations = mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar; WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); manager.updateViewLayout(mFakeTitleBarHolder, params); mFakeTitleBarHolder.removeView(mFakeTitleBar); manager.removeView(mFakeTitleBarHolder); } /** * Special method for the fake title bar to call when displaying its context * menu, since it is in its own Window, and its parent does not show a * context menu. */ /* package */ void showTitleBarContextMenu() { if (null == mTitleBar.getParent()) { return; } openContextMenu(mTitleBar); } @Override public void onContextMenuClosed(Menu menu) { super.onContextMenuClosed(menu); if (mInLoad) { showFakeTitleBar(); } } /** * onSaveInstanceState(Bundle map) * onSaveInstanceState is called right before onStop(). The map contains * the saved state. */ @Override protected void onSaveInstanceState(Bundle outState) { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this); } // the default implementation requires each view to have an id. As the // browser handles the state itself and it doesn't use id for the views, // don't call the default implementation. Otherwise it will trigger the // warning like this, "couldn't save which view has focus because the // focused view XXX has no id". // Save all the tabs mTabControl.saveState(outState); } @Override protected void onPause() { super.onPause(); if (mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already paused."); return; } mTabControl.pauseCurrentTab(); mActivityInPause = true; if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) { mWakeLock.acquire(); mHandler.sendMessageDelayed(mHandler .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); } // Clear the credentials toast if it is up if (mCredsDlg != null && mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // FIXME: This removes the active tabs page and resets the menu to // MAIN_MENU. A better solution might be to do this work in onNewIntent // but then we would need to save it in onSaveInstanceState and restore // it in onCreate/onRestoreInstanceState if (mActiveTabsPage != null) { removeActiveTabPage(true); } cancelStopToast(); // unregister network state listener unregisterReceiver(mNetworkStateIntentReceiver); WebView.disablePlatformNotifications(); } @Override protected void onDestroy() { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this); } super.onDestroy(); if (mUploadMessage != null) { mUploadMessage.onReceiveValue(null); mUploadMessage = null; } if (mTabControl == null) return; // Remove the fake title bar if it is there hideFakeTitleBar(); // Remove the current tab and sub window Tab t = mTabControl.getCurrentTab(); if (t != null) { dismissSubWindow(t); removeTabFromContentView(t); } // Destroy all the tabs mTabControl.destroy(); WebIconDatabase.getInstance().close(); if (mGlsConnection != null) { unbindService(mGlsConnection); mGlsConnection = null; } unregisterReceiver(mPackageInstallationReceiver); } @Override public void onConfigurationChanged(Configuration newConfig) { mConfigChanged = true; super.onConfigurationChanged(newConfig); if (mPageInfoDialog != null) { mPageInfoDialog.dismiss(); showPageInfo( mPageInfoView, mPageInfoFromShowSSLCertificateOnError.booleanValue()); } if (mSSLCertificateDialog != null) { mSSLCertificateDialog.dismiss(); showSSLCertificate( mSSLCertificateView); } if (mSSLCertificateOnErrorDialog != null) { mSSLCertificateOnErrorDialog.dismiss(); showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } if (mHttpAuthenticationDialog != null) { String title = ((TextView) mHttpAuthenticationDialog .findViewById(com.android.internal.R.id.alertTitle)).getText() .toString(); String name = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.username_edit)).getText().toString(); String password = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.password_edit)).getText().toString(); int focusId = mHttpAuthenticationDialog.getCurrentFocus() .getId(); mHttpAuthenticationDialog.dismiss(); showHttpAuthentication(mHttpAuthHandler, null, null, title, name, password, focusId); } if (mFindDialog != null && mFindDialog.isShowing()) { mFindDialog.onConfigurationChanged(newConfig); } } @Override public void onLowMemory() { super.onLowMemory(); mTabControl.freeMemory(); } private boolean resumeWebViewTimers() { Tab tab = mTabControl.getCurrentTab(); boolean inLoad = tab.inLoad(); if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) { CookieSyncManager.getInstance().startSync(); WebView w = tab.getWebView(); if (w != null) { w.resumeTimers(); } return true; } else { return false; } } private boolean pauseWebViewTimers() { Tab tab = mTabControl.getCurrentTab(); boolean inLoad = tab.inLoad(); if (mActivityInPause && !inLoad) { CookieSyncManager.getInstance().stopSync(); WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.pauseTimers(); } return true; } else { return false; } } // FIXME: Do we want to call this when loading google for the first time? /* * This function is called when we are launching for the first time. We * are waiting for the login credentials before loading Google home * pages. This way the user will be logged in straight away. */ private void waitForCredentials() { // Show a toast mCredsDlg = new ProgressDialog(this); mCredsDlg.setIndeterminate(true); mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg)); // If the user cancels the operation, then cancel the Google // Credentials request. mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST)); mCredsDlg.show(); // We set a timeout for the retrieval of credentials in onResume() // as that is when we have freed up some CPU time to get // the login credentials. } /* * If we have received the credentials or we have timed out and we are * showing the credentials dialog, then it is time to move on. */ private void resumeAfterCredentials() { if (mCredsDlg == null) { return; } // Clear the toast if (mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // Clear any pending timeout mHandler.removeMessages(CANCEL_CREDS_REQUEST); // Load the page WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.loadUrl(mSettings.getHomePage()); } // Update the settings, need to do this last as it can take a moment // to persist the settings. In the mean time we could be loading // content. mSettings.setLoginInitialized(this); } // Open the icon database and retain all the icons for visited sites. private void retainIconsOnStartup() { final WebIconDatabase db = WebIconDatabase.getInstance(); db.open(getDir("icons", 0).getPath()); try { Cursor c = Browser.getAllBookmarks(mResolver); if (!c.moveToFirst()) { c.deactivate(); return; } int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); do { String url = c.getString(urlIndex); db.retainIconForPageUrl(url); } while (c.moveToNext()); c.deactivate(); } catch (IllegalStateException e) { Log.e(LOGTAG, "retainIconsOnStartup", e); } } // Helper method for getting the top window. WebView getTopWindow() { return mTabControl.getCurrentTopWebView(); } TabControl getTabControl() { return mTabControl; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browser, menu); mMenu = menu; updateInLoadMenuItems(); return true; } /** * As the menu can be open when loading state changes * we must manually update the state of the stop/reload menu * item */ private void updateInLoadMenuItems() { if (mMenu == null) { return; } MenuItem src = mInLoad ? mMenu.findItem(R.id.stop_menu_id): mMenu.findItem(R.id.reload_menu_id); MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id); dest.setIcon(src.getIcon()); dest.setTitle(src.getTitle()); } @Override public boolean onContextItemSelected(MenuItem item) { // chording is not an issue with context menus, but we use the same // options selector, so set mCanChord to true so we can access them. mCanChord = true; int id = item.getItemId(); switch (id) { // For the context menu from the title bar case R.id.title_bar_share_page_url: case R.id.title_bar_copy_page_url: WebView mainView = mTabControl.getCurrentWebView(); if (null == mainView) { return false; } if (id == R.id.title_bar_share_page_url) { Browser.sendString(this, mainView.getUrl()); } else { copy(mainView.getUrl()); } break; // -- Browser context menu case R.id.open_context_menu_id: case R.id.open_newtab_context_menu_id: case R.id.bookmark_context_menu_id: case R.id.save_link_context_menu_id: case R.id.share_link_context_menu_id: case R.id.copy_link_context_menu_id: final WebView webView = getTopWindow(); if (null == webView) { return false; } final HashMap hrefMap = new HashMap(); hrefMap.put("webview", webView); final Message msg = mHandler.obtainMessage( FOCUS_NODE_HREF, id, 0, hrefMap); webView.requestFocusNodeHref(msg); break; default: // For other context menus return onOptionsItemSelected(item); } mCanChord = false; return true; } private Bundle createGoogleSearchSourceBundle(String source) { Bundle bundle = new Bundle(); bundle.putString(SearchManager.SOURCE, source); return bundle; } /** * Overriding this to insert a local information bundle */ @Override public boolean onSearchRequested() { if (mOptionsMenuOpen) closeOptionsMenu(); String url = (getTopWindow() == null) ? null : getTopWindow().getUrl(); startSearch(mSettings.getHomePage().equals(url) ? null : url, true, createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false); return true; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (appSearchData == null) { appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE); } super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } /** * Switch tabs. Called by the TitleBarSet when sliding the title bar * results in changing tabs. * @param index Index of the tab to change to, as defined by * mTabControl.getTabIndex(Tab t). * @return boolean True if we successfully switched to a different tab. If * the indexth tab is null, or if that tab is the same as * the current one, return false. */ /* package */ boolean switchToTab(int index) { Tab tab = mTabControl.getTab(index); Tab currentTab = mTabControl.getCurrentTab(); if (tab == null || tab == currentTab) { return false; } if (currentTab != null) { // currentTab may be null if it was just removed. In that case, // we do not need to remove it removeTabFromContentView(currentTab); } mTabControl.setCurrentTab(tab); attachTabToContentView(tab); resetTitleIconAndProgress(); updateLockIconToLatest(); return true; } /* package */ Tab openTabToHomePage() { return openTabAndShow(mSettings.getHomePage(), false, null); } /* package */ void closeCurrentWindow() { final Tab current = mTabControl.getCurrentTab(); if (mTabControl.getTabCount() == 1) { // This is the last tab. Open a new one, with the home // page and close the current one. openTabToHomePage(); closeTab(current); return; } final Tab parent = current.getParentTab(); int indexToShow = -1; if (parent != null) { indexToShow = mTabControl.getTabIndex(parent); } else { final int currentIndex = mTabControl.getCurrentIndex(); // Try to move to the tab to the right indexToShow = currentIndex + 1; if (indexToShow > mTabControl.getTabCount() - 1) { // Try to move to the tab to the left indexToShow = currentIndex - 1; } } if (switchToTab(indexToShow)) { // Close window closeTab(current); } } private ActiveTabsPage mActiveTabsPage; /** * Remove the active tabs page. * @param needToAttach If true, the active tabs page did not attach a tab * to the content view, so we need to do that here. */ /* package */ void removeActiveTabPage(boolean needToAttach) { mContentView.removeView(mActiveTabsPage); mActiveTabsPage = null; mMenuState = R.id.MAIN_MENU; if (needToAttach) { attachTabToContentView(mTabControl.getCurrentTab()); } getTopWindow().requestFocus(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!mCanChord) { // The user has already fired a shortcut with this hold down of the // menu key. return false; } if (null == getTopWindow()) { return false; } if (mMenuIsDown) { // The shortcut action consumes the MENU. Even if it is still down, // it won't trigger the next shortcut action. In the case of the // shortcut action triggering a new activity, like Bookmarks, we // won't get onKeyUp for MENU. So it is important to reset it here. mMenuIsDown = false; } switch (item.getItemId()) { // -- Main menu case R.id.new_tab_menu_id: openTabToHomePage(); break; case R.id.goto_menu_id: onSearchRequested(); break; case R.id.bookmarks_menu_id: bookmarksOrHistoryPicker(false); break; case R.id.active_tabs_menu_id: mActiveTabsPage = new ActiveTabsPage(this, mTabControl); removeTabFromContentView(mTabControl.getCurrentTab()); hideFakeTitleBar(); mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS); mActiveTabsPage.requestFocus(); mMenuState = EMPTY_MENU; break; case R.id.add_bookmark_menu_id: Intent i = new Intent(BrowserActivity.this, AddBookmarkPage.class); WebView w = getTopWindow(); i.putExtra("url", w.getUrl()); i.putExtra("title", w.getTitle()); i.putExtra("touch_icon_url", w.getTouchIconUrl()); i.putExtra("thumbnail", createScreenshot(w)); startActivity(i); break; case R.id.stop_reload_menu_id: if (mInLoad) { stopLoading(); } else { getTopWindow().reload(); } break; case R.id.back_menu_id: getTopWindow().goBack(); break; case R.id.forward_menu_id: getTopWindow().goForward(); break; case R.id.close_menu_id: // Close the subwindow if it exists. if (mTabControl.getCurrentSubWindow() != null) { dismissSubWindow(mTabControl.getCurrentTab()); break; } closeCurrentWindow(); break; case R.id.homepage_menu_id: Tab current = mTabControl.getCurrentTab(); if (current != null) { dismissSubWindow(current); current.getWebView().loadUrl(mSettings.getHomePage()); } break; case R.id.preferences_menu_id: Intent intent = new Intent(this, BrowserPreferencesPage.class); startActivityForResult(intent, PREFERENCES_PAGE); break; case R.id.find_menu_id: if (null == mFindDialog) { mFindDialog = new FindDialog(this); } mFindDialog.setWebView(getTopWindow()); mFindDialog.show(); mMenuState = EMPTY_MENU; break; case R.id.select_text_id: getTopWindow().emulateShiftHeld(); break; case R.id.page_info_menu_id: showPageInfo(mTabControl.getCurrentTab(), false); break; case R.id.classic_history_menu_id: bookmarksOrHistoryPicker(true); break; case R.id.share_page_menu_id: Browser.sendString(this, getTopWindow().getUrl(), getText(R.string.choosertitle_sharevia).toString()); break; case R.id.dump_nav_menu_id: getTopWindow().debugDump(); break; case R.id.zoom_in_menu_id: getTopWindow().zoomIn(); break; case R.id.zoom_out_menu_id: getTopWindow().zoomOut(); break; case R.id.view_downloads_menu_id: viewDownloads(null); break; case R.id.window_one_menu_id: case R.id.window_two_menu_id: case R.id.window_three_menu_id: case R.id.window_four_menu_id: case R.id.window_five_menu_id: case R.id.window_six_menu_id: case R.id.window_seven_menu_id: case R.id.window_eight_menu_id: { int menuid = item.getItemId(); for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { Tab desiredTab = mTabControl.getTab(id); if (desiredTab != null && desiredTab != mTabControl.getCurrentTab()) { switchToTab(id); } break; } } } break; default: if (!super.onOptionsItemSelected(item)) { return false; } // Otherwise fall through. } mCanChord = false; return true; } public void closeFind() { mMenuState = R.id.MAIN_MENU; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // This happens when the user begins to hold down the menu key, so // allow them to chord to get a shortcut. mCanChord = true; // Note: setVisible will decide whether an item is visible; while // setEnabled() will decide whether an item is enabled, which also means // whether the matching shortcut key will function. super.onPrepareOptionsMenu(menu); switch (mMenuState) { case EMPTY_MENU: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); } break; default: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); } final WebView w = getTopWindow(); boolean canGoBack = false; boolean canGoForward = false; boolean isHome = false; if (w != null) { canGoBack = w.canGoBack(); canGoForward = w.canGoForward(); isHome = mSettings.getHomePage().equals(w.getUrl()); } final MenuItem back = menu.findItem(R.id.back_menu_id); back.setEnabled(canGoBack); final MenuItem home = menu.findItem(R.id.homepage_menu_id); home.setEnabled(!isHome); menu.findItem(R.id.forward_menu_id) .setEnabled(canGoForward); menu.findItem(R.id.new_tab_menu_id).setEnabled( mTabControl.canCreateNewTab()); // decide whether to show the share link option PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); boolean isNavDump = mSettings.isNavDump(); final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); nav.setVisible(isNavDump); nav.setEnabled(isNavDump); break; } mCurrentMenuState = mMenuState; return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { WebView webview = (WebView) v; WebView.HitTestResult result = webview.getHitTestResult(); if (result == null) { return; } int type = result.getType(); if (type == WebView.HitTestResult.UNKNOWN_TYPE) { Log.w(LOGTAG, "We should not show context menu when nothing is touched"); return; } if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { // let TextView handles context menu return; } // Note, http://b/issue?id=1106666 is requesting that // an inflated menu can be used again. This is not available // yet, so inflate each time (yuk!) MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browsercontext, menu); // Show the correct menu group String extra = result.getExtra(); menu.setGroupVisible(R.id.PHONE_MENU, type == WebView.HitTestResult.PHONE_TYPE); menu.setGroupVisible(R.id.EMAIL_MENU, type == WebView.HitTestResult.EMAIL_TYPE); menu.setGroupVisible(R.id.GEO_MENU, type == WebView.HitTestResult.GEO_TYPE); menu.setGroupVisible(R.id.IMAGE_MENU, type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); menu.setGroupVisible(R.id.ANCHOR_MENU, type == WebView.HitTestResult.SRC_ANCHOR_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); // Setup custom handling depending on the type switch (type) { case WebView.HitTestResult.PHONE_TYPE: menu.setHeaderTitle(Uri.decode(extra)); menu.findItem(R.id.dial_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_TEL + extra))); Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); menu.findItem(R.id.add_contact_context_menu_id).setIntent( addIntent); menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.EMAIL_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.email_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_MAILTO + extra))); menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.GEO_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.map_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_GEO + URLEncoder.encode(extra)))); menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.SRC_ANCHOR_TYPE: case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: TextView titleView = (TextView) LayoutInflater.from(this) .inflate(android.R.layout.browser_link_context_header, null); titleView.setText(extra); menu.setHeaderView(titleView); // decide whether to show the open link in new tab option menu.findItem(R.id.open_newtab_context_menu_id).setVisible( mTabControl.canCreateNewTab()); menu.findItem(R.id.bookmark_context_menu_id).setVisible( Bookmarks.urlHasAcceptableScheme(extra)); PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null); if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { break; } // otherwise fall through to handle image part case WebView.HitTestResult.IMAGE_TYPE: if (type == WebView.HitTestResult.IMAGE_TYPE) { menu.setHeaderTitle(extra); } menu.findItem(R.id.view_image_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); menu.findItem(R.id.download_context_menu_id). setOnMenuItemClickListener(new Download(extra)); break; default: Log.w(LOGTAG, "We should not get here."); break; } hideFakeTitleBar(); } // Attach the given tab to the content view. // this should only be called for the current tab. private void attachTabToContentView(Tab t) { // Attach the container that contains the main WebView and any other UI // associated with the tab. t.attachTabToContentView(mContentView); if (mShouldShowErrorConsole) { ErrorConsoleView errorConsole = t.getErrorConsole(true); if (errorConsole.numberOfErrors() == 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } WebView view = t.getWebView(); view.setEmbeddedTitleBar(mTitleBar); // Request focus on the top window. t.getTopWindow().requestFocus(); } // Attach a sub window to the main WebView of the given tab. void attachSubWindow(Tab t) { t.attachSubWindow(mContentView); getTopWindow().requestFocus(); } // Remove the given tab from the content view. private void removeTabFromContentView(Tab t) { // Remove the container that contains the main WebView. t.removeTabFromContentView(mContentView); ErrorConsoleView errorConsole = t.getErrorConsole(false); if (errorConsole != null) { mErrorConsoleContainer.removeView(errorConsole); } WebView view = t.getWebView(); if (view != null) { view.setEmbeddedTitleBar(null); } } // Remove the sub window if it exists. Also called by TabControl when the // user clicks the 'X' to dismiss a sub window. /* package */ void dismissSubWindow(Tab t) { t.removeSubWindow(mContentView); // dismiss the subwindow. This will destroy the WebView. t.dismissSubWindow(); getTopWindow().requestFocus(); } // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)} // that accepts url as string. private Tab openTabAndShow(String url, boolean closeOnExit, String appId) { return openTabAndShow(new UrlData(url), closeOnExit, appId); } // This method does a ton of stuff. It will attempt to create a new tab // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If // url isn't null, it will load the given url. /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit, String appId) { final Tab currentTab = mTabControl.getCurrentTab(); if (mTabControl.canCreateNewTab()) { final Tab tab = mTabControl.createNewTab(closeOnExit, appId, urlData.mUrl); WebView webview = tab.getWebView(); // If the last tab was removed from the active tabs page, currentTab // will be null. if (currentTab != null) { removeTabFromContentView(currentTab); } // We must set the new tab as the current tab to reflect the old // animation behavior. mTabControl.setCurrentTab(tab); attachTabToContentView(tab); if (!urlData.isEmpty()) { urlData.loadIn(webview); } return tab; } else { // Get rid of the subwindow if it exists dismissSubWindow(currentTab); if (!urlData.isEmpty()) { // Load the given url. urlData.loadIn(currentTab.getWebView()); } } return currentTab; } private Tab openTab(String url) { if (mSettings.openInBackground()) { Tab t = mTabControl.createNewTab(); if (t != null) { WebView view = t.getWebView(); view.loadUrl(url); } return t; } else { return openTabAndShow(url, false, null); } } private class Copy implements OnMenuItemClickListener { private CharSequence mText; public boolean onMenuItemClick(MenuItem item) { copy(mText); return true; } public Copy(CharSequence toCopy) { mText = toCopy; } } private class Download implements OnMenuItemClickListener { private String mText; public boolean onMenuItemClick(MenuItem item) { onDownloadStartNoStream(mText, null, null, null, -1); return true; } public Download(String toDownload) { mText = toDownload; } } private void copy(CharSequence text) { try { IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard")); if (clip != null) { clip.setClipboardText(text); } } catch (android.os.RemoteException e) { Log.e(LOGTAG, "Copy failed", e); } } /** * Resets the browser title-view to whatever it must be * (for example, if we had a loading error) * When we have a new page, we call resetTitle, when we * have to reset the titlebar to whatever it used to be * (for example, if the user chose to stop loading), we * call resetTitleAndRevertLockIcon. */ /* package */ void resetTitleAndRevertLockIcon() { mTabControl.getCurrentTab().revertLockIcon(); updateLockIconToLatest(); resetTitleIconAndProgress(); } /** * Reset the title, favicon, and progress. */ private void resetTitleIconAndProgress() { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } resetTitleAndIcon(current); int progress = current.getProgress(); current.getWebChromeClient().onProgressChanged(current, progress); } // Reset the title and the icon based on the given item. private void resetTitleAndIcon(WebView view) { WebHistoryItem item = view.copyBackForwardList().getCurrentItem(); if (item != null) { setUrlTitle(item.getUrl(), item.getTitle()); setFavicon(item.getFavicon()); } else { setUrlTitle(null, null); setFavicon(null); } } /** * Sets a title composed of the URL and the title string. * @param url The URL of the site being loaded. * @param title The title of the site being loaded. */ void setUrlTitle(String url, String title) { mUrl = url; mTitle = title; mTitleBar.setTitleAndUrl(title, url); mFakeTitleBar.setTitleAndUrl(title, url); } /** * @param url The URL to build a title version of the URL from. * @return The title version of the URL or null if fails. * The title version of the URL can be either the URL hostname, * or the hostname with an "https://" prefix (for secure URLs), * or an empty string if, for example, the URL in question is a * file:// URL with no hostname. */ /* package */ static String buildTitleUrl(String url) { String titleUrl = null; if (url != null) { try { // parse the url string URL urlObj = new URL(url); if (urlObj != null) { titleUrl = ""; String protocol = urlObj.getProtocol(); String host = urlObj.getHost(); if (host != null && 0 < host.length()) { titleUrl = host; if (protocol != null) { // if a secure site, add an "https://" prefix! if (protocol.equalsIgnoreCase("https")) { titleUrl = protocol + "://" + host; } } } } } catch (MalformedURLException e) {} } return titleUrl; } // Set the favicon in the title bar. void setFavicon(Bitmap icon) { mTitleBar.setFavicon(icon); mFakeTitleBar.setFavicon(icon); } /** * Close the tab, remove its associated title bar, and adjust mTabControl's * current tab to a valid value. */ /* package */ void closeTab(Tab t) { int currentIndex = mTabControl.getCurrentIndex(); int removeIndex = mTabControl.getTabIndex(t); mTabControl.removeTab(t); if (currentIndex >= removeIndex && currentIndex != 0) { currentIndex--; } mTabControl.setCurrentTab(mTabControl.getTab(currentIndex)); resetTitleIconAndProgress(); } private void goBackOnePageOrQuit() { Tab current = mTabControl.getCurrentTab(); if (current == null) { /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); return; } WebView w = current.getWebView(); if (w.canGoBack()) { w.goBack(); } else { // Check to see if we are closing a window that was created by // another window. If so, we switch back to that window. Tab parent = current.getParentTab(); if (parent != null) { switchToTab(mTabControl.getTabIndex(parent)); // Now we close the other tab closeTab(current); } else { if (current.closeOnExit()) { // force the tab's inLoad() to be false as we are going to // either finish the activity or remove the tab. This will // ensure pauseWebViewTimers() taking action. mTabControl.getCurrentTab().clearInLoad(); if (mTabControl.getTabCount() == 1) { finish(); return; } // call pauseWebViewTimers() now, we won't be able to call // it in onPause() as the WebView won't be valid. // Temporarily change mActivityInPause to be true as // pauseWebViewTimers() will do nothing if mActivityInPause // is false. boolean savedState = mActivityInPause; if (savedState) { Log.e(LOGTAG, "BrowserActivity is already paused " + "while handing goBackOnePageOrQuit."); } mActivityInPause = true; pauseWebViewTimers(); mActivityInPause = savedState; removeTabFromContentView(current); mTabControl.removeTab(current); } /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); } } } boolean isMenuDown() { return mMenuIsDown; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is // still down, we don't want to trigger the search. Pretend to consume // the key and do nothing. if (mMenuIsDown) return true; switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = true; break; case KeyEvent.KEYCODE_SPACE: // WebView/WebTextView handle the keys in the KeyDown. As // the Activity's shortcut keys are only handled when WebView // doesn't, have to do it in onKeyDown instead of onKeyUp. if (event.isShiftPressed()) { getTopWindow().pageUp(false); } else { getTopWindow().pageDown(false); } return true; case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { event.startTracking(); return true; } else if (mCustomView == null && mActiveTabsPage == null && event.isLongPress()) { bookmarksOrHistoryPicker(true); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = false; break; case KeyEvent.KEYCODE_BACK: if (event.isTracking() && !event.isCanceled()) { if (mCustomView != null) { // if a custom view is showing, hide it mTabControl.getCurrentWebView().getWebChromeClient() .onHideCustomView(); } else if (mActiveTabsPage != null) { // if tab page is showing, hide it removeActiveTabPage(true); } else { WebView subwindow = mTabControl.getCurrentSubWindow(); if (subwindow != null) { if (subwindow.canGoBack()) { subwindow.goBack(); } else { dismissSubWindow(mTabControl.getCurrentTab()); } } else { goBackOnePageOrQuit(); } } return true; } break; } return super.onKeyUp(keyCode, event); } /* package */ void stopLoading() { mDidStopLoad = true; resetTitleAndRevertLockIcon(); WebView w = getTopWindow(); w.stopLoading(); // FIXME: before refactor, it is using mWebViewClient. So I keep the // same logic here. But for subwindow case, should we call into the main // WebView's onPageFinished as we never call its onPageStarted and if // the page finishes itself, we don't call onPageFinished. mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w, w.getUrl()); cancelStopToast(); mStopToast = Toast .makeText(this, R.string.stopping, Toast.LENGTH_SHORT); mStopToast.show(); } boolean didUserStopLoading() { return mDidStopLoad; } private void cancelStopToast() { if (mStopToast != null) { mStopToast.cancel(); mStopToast = null; } } // called by a UI or non-UI thread to post the message public void postMessage(int what, int arg1, int arg2, Object obj, long delayMillis) { mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2, obj), delayMillis); } // called by a UI or non-UI thread to remove the message void removeMessages(int what, Object object) { mHandler.removeMessages(what, object); } // public message ids public final static int LOAD_URL = 1001; public final static int STOP_LOAD = 1002; // Message Ids private static final int FOCUS_NODE_HREF = 102; private static final int CANCEL_CREDS_REQUEST = 103; private static final int RELEASE_WAKELOCK = 107; static final int UPDATE_BOOKMARK_THUMBNAIL = 108; // Private handler for handling javascript and saving passwords private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case FOCUS_NODE_HREF: { String url = (String) msg.getData().get("url"); if (url == null || url.length() == 0) { break; } HashMap focusNodeMap = (HashMap) msg.obj; WebView view = (WebView) focusNodeMap.get("webview"); // Only apply the action if the top window did not change. if (getTopWindow() != view) { break; } switch (msg.arg1) { case R.id.open_context_menu_id: case R.id.view_image_context_menu_id: loadURL(getTopWindow(), url); break; case R.id.open_newtab_context_menu_id: final Tab parent = mTabControl.getCurrentTab(); final Tab newTab = openTab(url); if (newTab != parent) { parent.addChildTab(newTab); } break; case R.id.bookmark_context_menu_id: Intent intent = new Intent(BrowserActivity.this, AddBookmarkPage.class); intent.putExtra("url", url); startActivity(intent); break; case R.id.share_link_context_menu_id: Browser.sendString(BrowserActivity.this, url, getText(R.string.choosertitle_sharevia).toString()); break; case R.id.copy_link_context_menu_id: copy(url); break; case R.id.save_link_context_menu_id: case R.id.download_context_menu_id: onDownloadStartNoStream(url, null, null, null, -1); break; } break; } case LOAD_URL: loadURL(getTopWindow(), (String) msg.obj); break; case STOP_LOAD: stopLoading(); break; case CANCEL_CREDS_REQUEST: resumeAfterCredentials(); break; case RELEASE_WAKELOCK: if (mWakeLock.isHeld()) { mWakeLock.release(); // if we reach here, Browser should be still in the // background loading after WAKELOCK_TIMEOUT (5-min). // To avoid burning the battery, stop loading. mTabControl.stopAllLoading(); } break; case UPDATE_BOOKMARK_THUMBNAIL: WebView view = (WebView) msg.obj; if (view != null) { updateScreenshot(view); } break; } } }; private void updateScreenshot(WebView view) { // If this is a bookmarked site, add a screenshot to the database. // FIXME: When should we update? Every time? // FIXME: Would like to make sure there is actually something to // draw, but the API for that (WebViewCore.pictureReady()) is not // currently accessible here. ContentResolver cr = getContentResolver(); final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl( cr, view.getOriginalUrl(), view.getUrl(), true); if (c != null) { boolean succeed = c.moveToFirst(); ContentValues values = null; while (succeed) { if (values == null) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); Bitmap bm = createScreenshot(view); if (bm == null) { c.close(); return; } bm.compress(Bitmap.CompressFormat.PNG, 100, os); values = new ContentValues(); values.put(Browser.BookmarkColumns.THUMBNAIL, os.toByteArray()); } cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, c.getInt(0)), values, null, null); succeed = c.moveToNext(); } c.close(); } } /** * Values for the size of the thumbnail created when taking a screenshot. * Lazily initialized. Instead of using these directly, use * getDesiredThumbnailWidth() or getDesiredThumbnailHeight(). */ private static int THUMBNAIL_WIDTH = 0; private static int THUMBNAIL_HEIGHT = 0; /** * Return the desired width for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired width for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailWidth(Context context) { if (THUMBNAIL_WIDTH == 0) { float density = context.getResources().getDisplayMetrics().density; THUMBNAIL_WIDTH = (int) (90 * density); THUMBNAIL_HEIGHT = (int) (80 * density); } return THUMBNAIL_WIDTH; } /** * Return the desired height for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired height for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailHeight(Context context) { // To ensure that they are both initialized. getDesiredThumbnailWidth(context); return THUMBNAIL_HEIGHT; } private Bitmap createScreenshot(WebView view) { Picture thumbnail = view.capturePicture(); if (thumbnail == null) { return null; } Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this), getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); // May need to tweak these values to determine what is the // best scale factor int thumbnailWidth = thumbnail.getWidth(); if (thumbnailWidth > 0) { float scaleFactor = (float) getDesiredThumbnailWidth(this) / (float)thumbnailWidth; canvas.scale(scaleFactor, scaleFactor); } thumbnail.draw(canvas); return bm; } // ------------------------------------------------------------------------- // Helper function for WebViewClient. //------------------------------------------------------------------------- // Use in overrideUrlLoading /* package */ final static String SCHEME_WTAI = "wtai://wp/"; /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;"; /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;"; /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;"; void onPageStarted(WebView view, String url, Bitmap favicon) { // when BrowserActivity just starts, onPageStarted may be called before // onResume as it is triggered from onCreate. Call resumeWebViewTimers // to start the timer. As we won't switch tabs while an activity is in // pause state, we can ensure calling resume and pause in pair. if (mActivityInPause) resumeWebViewTimers(); resetLockIcon(url); setUrlTitle(url, null); setFavicon(favicon); mInLoad = true; mDidStopLoad = false; showFakeTitleBar(); updateInLoadMenuItems(); if (!mIsNetworkUp) createAndShowNetworkDialog(); if (mSettings.isTracing()) { String host; try { WebAddress uri = new WebAddress(url); host = uri.mHost; } catch (android.net.ParseException ex) { host = "browser"; } host = host.replace('.', '_'); host += ".trace"; mInTrace = true; Debug.startMethodTracing(host, 20 * 1024 * 1024); } // Performance probe if (false) { mStart = SystemClock.uptimeMillis(); mProcessStart = Process.getElapsedCpuTime(); long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { mUserStart = sysCpu[0] + sysCpu[1]; mSystemStart = sysCpu[2]; mIdleStart = sysCpu[3]; mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6]; } mUiStart = SystemClock.currentThreadTimeMillis(); } } void onPageFinished(WebView view, String url) { // Reset the title and icon in case we stopped a provisional load. resetTitleAndIcon(view); // Update the lock icon image only once we are done loading updateLockIconToLatest(); // pause the WebView timer and release the wake lock if it is finished // while BrowserActivity is in pause state. if (mActivityInPause && pauseWebViewTimers()) { if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } } // Performance probe if (false) { long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { String uiInfo = "UI thread used " + (SystemClock.currentThreadTimeMillis() - mUiStart) + " ms"; if (LOGD_ENABLED) { Log.d(LOGTAG, uiInfo); } //The string that gets written to the log String performanceString = "It took total " + (SystemClock.uptimeMillis() - mStart) + " ms clock time to load the page." + "\nbrowser process used " + (Process.getElapsedCpuTime() - mProcessStart) + " ms, user processes used " + (sysCpu[0] + sysCpu[1] - mUserStart) * 10 + " ms, kernel used " + (sysCpu[2] - mSystemStart) * 10 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10 + " ms and irq took " + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart) * 10 + " ms, " + uiInfo; if (LOGD_ENABLED) { Log.d(LOGTAG, performanceString + "\nWebpage: " + url); } if (url != null) { // strip the url to maintain consistency String newUrl = new String(url); if (newUrl.startsWith("http://www.")) { newUrl = newUrl.substring(11); } else if (newUrl.startsWith("http://")) { newUrl = newUrl.substring(7); } else if (newUrl.startsWith("https://www.")) { newUrl = newUrl.substring(12); } else if (newUrl.startsWith("https://")) { newUrl = newUrl.substring(8); } if (LOGD_ENABLED) { Log.d(LOGTAG, newUrl + " loaded"); } } } } if (mInTrace) { mInTrace = false; Debug.stopMethodTracing(); } } boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith(SCHEME_WTAI)) { // wtai://wp/mc;number // number=string(phone-number) if (url.startsWith(SCHEME_WTAI_MC)) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + url.substring(SCHEME_WTAI_MC.length()))); startActivity(intent); return true; } // wtai://wp/sd;dtmf // dtmf=string(dialstring) if (url.startsWith(SCHEME_WTAI_SD)) { // TODO: only send when there is active voice connection return false; } // wtai://wp/ap;number;name // number=string(phone-number) // name=string if (url.startsWith(SCHEME_WTAI_AP)) { // TODO return false; } } // The "about:" schemes are internal to the browser; don't want these to // be dispatched to other apps. if (url.startsWith("about:")) { return false; } Intent intent; // perform generic parsing of the URI to turn it into an Intent. try { intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException ex) { Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage()); return false; } // check whether the intent can be resolved. If not, we will see // whether we can download it from the Market. if (getPackageManager().resolveActivity(intent, 0) == null) { String packagename = intent.getPackage(); if (packagename != null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + packagename)); intent.addCategory(Intent.CATEGORY_BROWSABLE); startActivity(intent); return true; } else { return false; } } // sanitize the Intent, ensuring web pages can not bypass browser // security (only access to BROWSABLE activities). intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setComponent(null); try { if (startActivityIfNeeded(intent, -1)) { return true; } } catch (ActivityNotFoundException ex) { // ignore the error. If no application can handle the URL, // eg about:blank, assume the browser can handle it. } if (mMenuIsDown) { openTab(url); closeOptionsMenu(); return true; } return false; } // ------------------------------------------------------------------------- // Helper function for WebChromeClient // ------------------------------------------------------------------------- void onProgressChanged(WebView view, int newProgress) { mTitleBar.setProgress(newProgress); mFakeTitleBar.setProgress(newProgress); if (newProgress == 100) { // onProgressChanged() may continue to be called after the main // frame has finished loading, as any remaining sub frames continue // to load. We'll only get called once though with newProgress as // 100 when everything is loaded. (onPageFinished is called once // when the main frame completes loading regardless of the state of // any sub frames so calls to onProgressChanges may continue after // onPageFinished has executed) if (mInLoad) { mInLoad = false; updateInLoadMenuItems(); // If the options menu is open, leave the title bar if (!mOptionsMenuOpen || !mIconView) { hideFakeTitleBar(); } } } else if (!mInLoad) { // onPageFinished may have already been called but a subframe is // still loading and updating the progress. Reset mInLoad and update // the menu items. mInLoad = true; updateInLoadMenuItems(); if (!mOptionsMenuOpen || mIconView) { // This page has begun to load, so show the title bar showFakeTitleBar(); } } } void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (mCustomView != null) return; // Add the custom view to its container. mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); mCustomView = view; mCustomViewCallback = callback; // Save the menu state and set it to empty while the custom // view is showing. mOldMenuState = mMenuState; mMenuState = EMPTY_MENU; // Hide the content view. mContentView.setVisibility(View.GONE); // Finally show the custom view container. setStatusBarVisibility(false); mCustomViewContainer.setVisibility(View.VISIBLE); mCustomViewContainer.bringToFront(); } void onHideCustomView() { if (mCustomView == null) return; // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. mCustomViewContainer.removeView(mCustomView); mCustomView = null; // Reset the old menu state. mMenuState = mOldMenuState; mOldMenuState = EMPTY_MENU; mCustomViewContainer.setVisibility(View.GONE); mCustomViewCallback.onCustomViewHidden(); // Show the content view. setStatusBarVisibility(true); mContentView.setVisibility(View.VISIBLE); } Bitmap getDefaultVideoPoster() { if (mDefaultVideoPoster == null) { mDefaultVideoPoster = BitmapFactory.decodeResource( getResources(), R.drawable.default_video_poster); } return mDefaultVideoPoster; } View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this); mVideoProgressView = inflater.inflate( R.layout.video_loading_progress, null); } return mVideoProgressView; } /* * The Object used to inform the WebView of the file to upload. */ private ValueCallback<Uri> mUploadMessage; void openFileChooser(ValueCallback<Uri> uploadMsg) { if (mUploadMessage != null) return; mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); BrowserActivity.this.startActivityForResult(Intent.createChooser(i, getString(R.string.choose_upload)), FILE_SELECTED); } // ------------------------------------------------------------------------- // Implement functions for DownloadListener // ------------------------------------------------------------------------- /** * Notify the host application a download should be done, or that * the data should be streamed if a streaming viewer is available. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // if we're dealing wih A/V content that's not explicitly marked // for download, check if it's streamable. if (contentDisposition == null || !contentDisposition.regionMatches( true, 0, "attachment", 0, 10)) { // query the package manager to see if there's a registered handler // that matches. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), mimetype); ResolveInfo info = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { ComponentName myName = getComponentName(); // If we resolved to ourselves, we don't want to attempt to // load the url only to try and download it again. if (!myName.getPackageName().equals( info.activityInfo.packageName) || !myName.getClassName().equals( info.activityInfo.name)) { // someone (other than us) knows how to handle this mime // type with this scheme, don't download. try { startActivity(intent); return; } catch (ActivityNotFoundException ex) { if (LOGD_ENABLED) { Log.d(LOGTAG, "activity not found for " + mimetype + " over " + Uri.parse(url).getScheme(), ex); } // Best behavior is to fall back to a download in this // case } } } } onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength); } /** * Notify the host application a download should be done, even if there * is a streaming viewer available for thise type. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ /*package */ void onDownloadStartNoStream(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(this) .setTitle(title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to undo // KURL's percent-encoding and redo the encoding using java.net.URI. URI uri = null; try { // Undo the percent-encoding that KURL may have done. String newUrl = new String(URLUtil.decode(url.getBytes())); // Parse the url into pieces WebAddress w = new WebAddress(newUrl); String frag = null; String query = null; String path = w.mPath; // Break the path into path, query, and fragment if (path.length() > 0) { // Strip the fragment int idx = path.lastIndexOf('#'); if (idx != -1) { frag = path.substring(idx + 1); path = path.substring(0, idx); } idx = path.lastIndexOf('?'); if (idx != -1) { query = path.substring(idx + 1); path = path.substring(0, idx); } } uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path, query, frag); } catch (Exception e) { Log.e(LOGTAG, "Could not parse url for download: " + url, e); return; } // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url); ContentValues values = new ContentValues(); values.put(Downloads.COLUMN_URI, uri.toString()); values.put(Downloads.COLUMN_COOKIE_DATA, cookies); values.put(Downloads.COLUMN_USER_AGENT, userAgent); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, getPackageName()); values.put(Downloads.COLUMN_NOTIFICATION_CLASS, BrowserDownloadPage.class.getCanonicalName()); values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); values.put(Downloads.COLUMN_MIME_TYPE, mimetype); values.put(Downloads.COLUMN_FILE_NAME_HINT, filename); values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost()); if (contentLength > 0) { values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength); } if (mimetype == null) { // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(this).execute(values); } else { final Uri contentUri = getContentResolver().insert(Downloads.CONTENT_URI, values); viewDownloads(contentUri); } } // ------------------------------------------------------------------------- /** * Resets the lock icon. This method is called when we start a new load and * know the url to be loaded. */ private void resetLockIcon(String url) { // Save the lock-icon state (we revert to it if the load gets cancelled) mTabControl.getCurrentTab().resetLockIcon(url); updateLockIconImage(LOCK_ICON_UNSECURE); } /** * Update the lock icon to correspond to our latest state. */ private void updateLockIconToLatest() { updateLockIconImage(mTabControl.getCurrentTab().getLockIconType()); } /** * Updates the lock-icon image in the title-bar. */ private void updateLockIconImage(int lockIconType) { Drawable d = null; if (lockIconType == LOCK_ICON_SECURE) { d = mSecLockIcon; } else if (lockIconType == LOCK_ICON_MIXED) { d = mMixLockIcon; } mTitleBar.setLock(d); mFakeTitleBar.setLock(d); } /** * Displays a page-info dialog. * @param tab The tab to show info about * @param fromShowSSLCertificateOnError The flag that indicates whether * this dialog was opened from the SSL-certificate-on-error dialog or * not. This is important, since we need to know whether to return to * the parent dialog or simply dismiss. */ private void showPageInfo(final Tab tab, final boolean fromShowSSLCertificateOnError) { final LayoutInflater factory = LayoutInflater .from(this); final View pageInfoView = factory.inflate(R.layout.page_info, null); final WebView view = tab.getWebView(); String url = null; String title = null; if (view == null) { url = tab.getUrl(); title = tab.getTitle(); } else if (view == mTabControl.getCurrentWebView()) { // Use the cached title and url if this is the current WebView url = mUrl; title = mTitle; } else { url = view.getUrl(); title = view.getTitle(); } if (url == null) { url = ""; } if (title == null) { title = ""; } ((TextView) pageInfoView.findViewById(R.id.address)).setText(url); ((TextView) pageInfoView.findViewById(R.id.title)).setText(title); mPageInfoView = tab; mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this) .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info) .setView(pageInfoView) .setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }); // if we have a main top-level page SSL certificate set or a certificate // error if (fromShowSSLCertificateOnError || (view != null && view.getCertificate() != null)) { // add a 'View Certificate' button alertDialogBuilder.setNeutralButton( R.string.view_certificate, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } else { // otherwise, display the top-most certificate from // the chain if (view.getCertificate() != null) { showSSLCertificate(tab); } } } }); } mPageInfoDialog = alertDialogBuilder.show(); } /** * Displays the main top-level page SSL certificate dialog * (accessible from the Page-Info dialog). * @param tab The tab to show certificate for. */ private void showSSLCertificate(final Tab tab) { final View certificateView = inflateCertificateView(tab.getWebView().getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); LinearLayout ll = (LinearLayout) factory.inflate( R.layout.ssl_success, placeholder); ((TextView)ll.findViewById(R.id.success)) .setText(R.string.ssl_certificate_is_valid); mSSLCertificateView = tab; mSSLCertificateDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .show(); } /** * Displays the SSL error certificate dialog. * @param view The target web-view. * @param handler The SSL error handler responsible for cancelling the * connection that resulted in an SSL error or proceeding per user request. * @param error The SSL error object. */ void showSSLCertificateOnError( final WebView view, final SslErrorHandler handler, final SslError error) { final View certificateView = inflateCertificateView(error.getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); if (error.hasError(SslError.SSL_UNTRUSTED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_untrusted); } if (error.hasError(SslError.SSL_IDMISMATCH)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_mismatch); } if (error.hasError(SslError.SSL_EXPIRED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_expired); } if (error.hasError(SslError.SSL_NOTYETVALID)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_not_yet_valid); } mSSLCertificateOnErrorHandler = handler; mSSLCertificateOnErrorView = view; mSSLCertificateOnErrorError = error; mSSLCertificateOnErrorDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_partially_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; view.getWebViewClient().onReceivedSslError( view, handler, error); } }) .setNeutralButton(R.string.page_info_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; // do not clear the dialog state: we will // need to show the dialog again once the // user is done exploring the page-info details showPageInfo(mTabControl.getTabFromView(view), true); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; view.getWebViewClient().onReceivedSslError( view, handler, error); } }) .show(); } /** * Inflates the SSL certificate view (helper method). * @param certificate The SSL certificate. * @return The resultant certificate view with issued-to, issued-by, * issued-on, expires-on, and possibly other fields set. * If the input certificate is null, returns null. */ private View inflateCertificateView(SslCertificate certificate) { if (certificate == null) { return null; } LayoutInflater factory = LayoutInflater.from(this); View certificateView = factory.inflate( R.layout.ssl_certificate, null); // issued to: SslCertificate.DName issuedTo = certificate.getIssuedTo(); if (issuedTo != null) { ((TextView) certificateView.findViewById(R.id.to_common)) .setText(issuedTo.getCName()); ((TextView) certificateView.findViewById(R.id.to_org)) .setText(issuedTo.getOName()); ((TextView) certificateView.findViewById(R.id.to_org_unit)) .setText(issuedTo.getUName()); } // issued by: SslCertificate.DName issuedBy = certificate.getIssuedBy(); if (issuedBy != null) { ((TextView) certificateView.findViewById(R.id.by_common)) .setText(issuedBy.getCName()); ((TextView) certificateView.findViewById(R.id.by_org)) .setText(issuedBy.getOName()); ((TextView) certificateView.findViewById(R.id.by_org_unit)) .setText(issuedBy.getUName()); } // issued on: String issuedOn = reformatCertificateDate( certificate.getValidNotBefore()); ((TextView) certificateView.findViewById(R.id.issued_on)) .setText(issuedOn); // expires on: String expiresOn = reformatCertificateDate( certificate.getValidNotAfter()); ((TextView) certificateView.findViewById(R.id.expires_on)) .setText(expiresOn); return certificateView; } /** * Re-formats the certificate date (Date.toString()) string to * a properly localized date string. * @return Properly localized version of the certificate date string and * the original certificate date string if fails to localize. * If the original string is null, returns an empty string "". */ private String reformatCertificateDate(String certificateDate) { String reformattedDate = null; if (certificateDate != null) { Date date = null; try { date = java.text.DateFormat.getInstance().parse(certificateDate); } catch (ParseException e) { date = null; } if (date != null) { reformattedDate = DateFormat.getDateFormat(this).format(date); } } return reformattedDate != null ? reformattedDate : (certificateDate != null ? certificateDate : ""); } /** * Displays an http-authentication dialog. */ void showHttpAuthentication(final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password, int focusId) { LayoutInflater factory = LayoutInflater.from(this); final View v = factory .inflate(R.layout.http_authentication, null); if (name != null) { ((EditText) v.findViewById(R.id.username_edit)).setText(name); } if (password != null) { ((EditText) v.findViewById(R.id.password_edit)).setText(password); } String titleText = title; if (titleText == null) { titleText = getText(R.string.sign_in_to).toString().replace( "%s1", host).replace("%s2", realm); } mHttpAuthHandler = handler; AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(titleText) .setIcon(android.R.drawable.ic_dialog_alert) .setView(v) .setPositiveButton(R.string.action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String nm = ((EditText) v .findViewById(R.id.username_edit)) .getText().toString(); String pw = ((EditText) v .findViewById(R.id.password_edit)) .getText().toString(); BrowserActivity.this.setHttpAuthUsernamePassword (host, realm, nm, pw); handler.proceed(nm, pw); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .create(); // Make the IME appear when the dialog is displayed if applicable. dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); if (focusId != 0) { dialog.findViewById(focusId).requestFocus(); } else { v.findViewById(R.id.username_edit).requestFocus(); } mHttpAuthenticationDialog = dialog; } public int getProgress() { WebView w = mTabControl.getCurrentWebView(); if (w != null) { return w.getProgress(); } else { return 100; } } /** * Set HTTP authentication password. * * @param host The host for the password * @param realm The realm for the password * @param username The username for the password. If it is null, it means * password can't be saved. * @param password The password */ public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setHttpAuthUsernamePassword(host, realm, username, password); } } /** * connectivity manager says net has come or gone... inform the user * @param up true if net has come up, false if net has gone down */ public void onNetworkToggle(boolean up) { if (up == mIsNetworkUp) { return; } else if (up) { mIsNetworkUp = true; if (mAlertDialog != null) { mAlertDialog.cancel(); mAlertDialog = null; } } else { mIsNetworkUp = false; if (mInLoad) { createAndShowNetworkDialog(); } } WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setNetworkAvailable(up); } } boolean isNetworkUp() { return mIsNetworkUp; } // This method shows the network dialog alerting the user that the net is // down. It will only show the dialog if mAlertDialog is null. private void createAndShowNetworkDialog() { if (mAlertDialog == null) { mAlertDialog = new AlertDialog.Builder(this) .setTitle(R.string.loadSuspendedTitle) .setMessage(R.string.loadSuspended) .setPositiveButton(R.string.ok, null) .show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case COMBO_PAGE: if (resultCode == RESULT_OK && intent != null) { String data = intent.getAction(); Bundle extras = intent.getExtras(); if (extras != null && extras.getBoolean("new_window", false)) { openTab(data); } else { final Tab currentTab = mTabControl.getCurrentTab(); dismissSubWindow(currentTab); if (data != null && data.length() != 0) { getTopWindow().loadUrl(data); } } } break; // Choose a file from the file picker. case FILE_SELECTED: if (null == mUploadMessage) break; Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; break; default: break; } getTopWindow().requestFocus(); } /* * This method is called as a result of the user selecting the options * menu to see the download window, or when a download changes state. It * shows the download window ontop of the current window. */ /* package */ void viewDownloads(Uri downloadRecord) { Intent intent = new Intent(this, BrowserDownloadPage.class); intent.setData(downloadRecord); startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE); } /** * Open the Go page. * @param startWithHistory If true, open starting on the history tab. * Otherwise, start with the bookmarks tab. */ /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } Intent intent = new Intent(this, CombinedBookmarkHistoryActivity.class); String title = current.getTitle(); String url = current.getUrl(); Bitmap thumbnail = createScreenshot(current); // Just in case the user opens bookmarks before a page finishes loading // so the current history item, and therefore the page, is null. if (null == url) { url = mLastEnteredUrl; // This can happen. if (null == url) { url = mSettings.getHomePage(); } } // In case the web page has not yet received its associated title. if (title == null) { title = url; } intent.putExtra("title", title); intent.putExtra("url", url); intent.putExtra("thumbnail", thumbnail); // Disable opening in a new window if we have maxed out the windows intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab()); intent.putExtra("touch_icon_url", current.getTouchIconUrl()); if (startWithHistory) { intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB, CombinedBookmarkHistoryActivity.HISTORY_TAB); } startActivityForResult(intent, COMBO_PAGE); } // Called when loading from context menu or LOAD_URL message private void loadURL(WebView view, String url) { // In case the user enters nothing. if (url != null && url.length() != 0 && view != null) { url = smartUrlFilter(url); if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) { view.loadUrl(url); } } } private String smartUrlFilter(Uri inUri) { if (inUri != null) { return smartUrlFilter(inUri.toString()); } return null; } protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( "(?i)" + // switch on case insensitive matching "(" + // begin group for schema "(?:http|https|file):\\/\\/" + "|(?:inline|data|about|content|javascript):" + ")" + "(.*)" ); /** * Attempts to determine whether user input is a URL or search * terms. Anything with a space is passed to search. * * Converts to lowercase any mistakenly uppercased schema (i.e., * "Http://" converts to "http://" * * @return Original or modified URL * */ String smartUrlFilter(String url) { String inUrl = url.trim(); boolean hasSpace = inUrl.indexOf(' ') != -1; Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); if (matcher.matches()) { // force scheme to lowercase String scheme = matcher.group(1); String lcScheme = scheme.toLowerCase(); if (!lcScheme.equals(scheme)) { inUrl = lcScheme + matcher.group(2); } if (hasSpace) { inUrl = inUrl.replace(" ", "%20"); } return inUrl; } if (hasSpace) { // FIXME: Is this the correct place to add to searches? // what if someone else calls this function? int shortcut = parseUrlShortcut(inUrl); if (shortcut != SHORTCUT_INVALID) { Browser.addSearchUrl(mResolver, inUrl); String query = inUrl.substring(2); switch (shortcut) { case SHORTCUT_GOOGLE_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER); case SHORTCUT_WIKIPEDIA_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER); case SHORTCUT_DICTIONARY_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER); case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH: // FIXME: we need location in this case return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER); } } } else { if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) { return URLUtil.guessUrl(inUrl); } } Browser.addSearchUrl(mResolver, inUrl); return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER); } /* package */ void setShouldShowErrorConsole(boolean flag) { if (flag == mShouldShowErrorConsole) { // Nothing to do. return; } mShouldShowErrorConsole = flag; ErrorConsoleView errorConsole = mTabControl.getCurrentTab() .getErrorConsole(true); if (flag) { // Setting the show state of the console will cause it's the layout to be inflated. if (errorConsole.numberOfErrors() > 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } // Now we can add it to the main view. mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { mErrorConsoleContainer.removeView(errorConsole); } } boolean shouldShowErrorConsole() { return mShouldShowErrorConsole; } private void setStatusBarVisibility(boolean visible) { int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN; getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN); } final static int LOCK_ICON_UNSECURE = 0; final static int LOCK_ICON_SECURE = 1; final static int LOCK_ICON_MIXED = 2; private BrowserSettings mSettings; private TabControl mTabControl; private ContentResolver mResolver; private FrameLayout mContentView; private View mCustomView; private FrameLayout mCustomViewContainer; private WebChromeClient.CustomViewCallback mCustomViewCallback; // FIXME, temp address onPrepareMenu performance problem. When we move everything out of // view, we should rewrite this. private int mCurrentMenuState = 0; private int mMenuState = R.id.MAIN_MENU; private int mOldMenuState = EMPTY_MENU; private static final int EMPTY_MENU = -1; private Menu mMenu; private FindDialog mFindDialog; // Used to prevent chording to result in firing two shortcuts immediately // one after another. Fixes bug 1211714. boolean mCanChord; private boolean mInLoad; private boolean mIsNetworkUp; private boolean mDidStopLoad; private boolean mActivityInPause = true; private boolean mMenuIsDown; private static boolean mInTrace; // Performance probe private static final int[] SYSTEM_CPU_FORMAT = new int[] { Process.PROC_SPACE_TERM | Process.PROC_COMBINE, Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time }; private long mStart; private long mProcessStart; private long mUserStart; private long mSystemStart; private long mIdleStart; private long mIrqStart; private long mUiStart; private Drawable mMixLockIcon; private Drawable mSecLockIcon; /* hold a ref so we can auto-cancel if necessary */ private AlertDialog mAlertDialog; // Wait for credentials before loading google.com private ProgressDialog mCredsDlg; // The up-to-date URL and title (these can be different from those stored // in WebView, since it takes some time for the information in WebView to // get updated) private String mUrl; private String mTitle; // As PageInfo has different style for landscape / portrait, we have // to re-open it when configuration changed private AlertDialog mPageInfoDialog; private Tab mPageInfoView; // If the Page-Info dialog is launched from the SSL-certificate-on-error // dialog, we should not just dismiss it, but should get back to the // SSL-certificate-on-error dialog. This flag is used to store this state private Boolean mPageInfoFromShowSSLCertificateOnError; // as SSLCertificateOnError has different style for landscape / portrait, // we have to re-open it when configuration changed private AlertDialog mSSLCertificateOnErrorDialog; private WebView mSSLCertificateOnErrorView; private SslErrorHandler mSSLCertificateOnErrorHandler; private SslError mSSLCertificateOnErrorError; // as SSLCertificate has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mSSLCertificateDialog; private Tab mSSLCertificateView; // as HttpAuthentication has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mHttpAuthenticationDialog; private HttpAuthHandler mHttpAuthHandler; /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER); // Google search final static String QuickSearch_G = "http://www.google.com/m?q=%s"; // Wikipedia search final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; // Dictionary search final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s"; // Google Mobile Local search final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view"; final static String QUERY_PLACE_HOLDER = "%s"; // "source" parameter for Google search through search key final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; // "source" parameter for Google search through goto menu final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto"; // "source" parameter for Google search through simplily type final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; // "source" parameter for Google search suggested by the browser final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; // "source" parameter for Google search from unknown source final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; private final static String LOGTAG = "browser"; private String mLastEnteredUrl; private PowerManager.WakeLock mWakeLock; private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes private Toast mStopToast; private TitleBar mTitleBar; private LinearLayout mErrorConsoleContainer = null; private boolean mShouldShowErrorConsole = false; // As the ids are dynamically created, we can't guarantee that they will // be in sequence, so this static array maps ids to a window number. final static private int[] WINDOW_SHORTCUT_ID_ARRAY = { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id, R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id, R.id.window_seven_menu_id, R.id.window_eight_menu_id }; // monitor platform changes private IntentFilter mNetworkStateChangedFilter; private BroadcastReceiver mNetworkStateIntentReceiver; private BroadcastReceiver mPackageInstallationReceiver; // activity requestCode final static int COMBO_PAGE = 1; final static int DOWNLOAD_PAGE = 2; final static int PREFERENCES_PAGE = 3; final static int FILE_SELECTED = 4; // the default <video> poster private Bitmap mDefaultVideoPoster; // the video progress view private View mVideoProgressView; /** * A UrlData class to abstract how the content will be set to WebView. * This base class uses loadUrl to show the content. */ private static class UrlData { String mUrl; byte[] mPostData; UrlData(String url) { this.mUrl = url; } void setPostData(byte[] postData) { mPostData = postData; } boolean isEmpty() { return mUrl == null || mUrl.length() == 0; } public void loadIn(WebView webView) { if (mPostData != null) { webView.postUrl(mUrl, mPostData); } else { webView.loadUrl(mUrl); } } }; /** * A subclass of UrlData class that can display inlined content using * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}. */ private static class InlinedUrlData extends UrlData { InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) { super(failUrl); mInlined = inlined; mMimeType = mimeType; mEncoding = encoding; } String mMimeType; String mInlined; String mEncoding; @Override boolean isEmpty() { return mInlined == null || mInlined.length() == 0 || super.isEmpty(); } @Override public void loadIn(WebView webView) { webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl); } } /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null); }
true
true
public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); mFakeTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( ConnectivityManager.EXTRA_NETWORK_INFO); onNetworkToggle( (info != null) ? info.isConnected() : false); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } }
public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); mFakeTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); onNetworkToggle(!noConnectivity); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } }
diff --git a/zendserver-webapi-java/org.zend.webapi.core/src/org/zend/webapi/internal/core/connection/exception/UnexpectedResponseCode.java b/zendserver-webapi-java/org.zend.webapi.core/src/org/zend/webapi/internal/core/connection/exception/UnexpectedResponseCode.java index d761316b..f61d95d9 100644 --- a/zendserver-webapi-java/org.zend.webapi.core/src/org/zend/webapi/internal/core/connection/exception/UnexpectedResponseCode.java +++ b/zendserver-webapi-java/org.zend.webapi.core/src/org/zend/webapi/internal/core/connection/exception/UnexpectedResponseCode.java @@ -1,47 +1,47 @@ /******************************************************************************* * Copyright (c) Feb 28, 2011 Zend Technologies Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.zend.webapi.internal.core.connection.exception; import org.restlet.ext.xml.DomRepresentation; import org.restlet.representation.Representation; import org.w3c.dom.Node; import org.zend.webapi.core.WebApiException; import org.zend.webapi.core.connection.response.ResponseCode; /** * Unexpected response code * * @author Roy, 2011 * */ public class UnexpectedResponseCode extends WebApiException { private static final long serialVersionUID = -2095471259882902506L; final private int code; final private String message; public UnexpectedResponseCode(int responseCode, Representation handle) { this.code = responseCode; final DomRepresentation domRepresentation = new DomRepresentation( handle); final Node node = domRepresentation .getNode("/zendServerAPIResponse/errorData/errorMessage"); - this.message = node == null ? null : node.getTextContent(); + this.message = node == null ? null : node.getTextContent().trim(); } @Override public String getMessage() { return message != null ? message : getResponseCode().getDescription(); } @Override public ResponseCode getResponseCode() { return ResponseCode.byCode(code); } }
true
true
public UnexpectedResponseCode(int responseCode, Representation handle) { this.code = responseCode; final DomRepresentation domRepresentation = new DomRepresentation( handle); final Node node = domRepresentation .getNode("/zendServerAPIResponse/errorData/errorMessage"); this.message = node == null ? null : node.getTextContent(); }
public UnexpectedResponseCode(int responseCode, Representation handle) { this.code = responseCode; final DomRepresentation domRepresentation = new DomRepresentation( handle); final Node node = domRepresentation .getNode("/zendServerAPIResponse/errorData/errorMessage"); this.message = node == null ? null : node.getTextContent().trim(); }
diff --git a/src/edu/sc/seis/sod/database/waveform/JDBCVelocityContext.java b/src/edu/sc/seis/sod/database/waveform/JDBCVelocityContext.java index 949b11af8..0fd09c053 100644 --- a/src/edu/sc/seis/sod/database/waveform/JDBCVelocityContext.java +++ b/src/edu/sc/seis/sod/database/waveform/JDBCVelocityContext.java @@ -1,92 +1,92 @@ /** * JDBCVelocityContext.java * * @author Created by Omnicore CodeGuide */ package edu.sc.seis.sod.database.waveform; import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler; import edu.sc.seis.sod.CookieJarResult; import edu.sc.seis.sod.EventChannelPair; import java.io.Serializable; import java.sql.SQLException; import org.apache.velocity.context.AbstractContext; import org.apache.velocity.context.Context; public class JDBCVelocityContext extends AbstractContext { public JDBCVelocityContext(EventChannelPair ecp, JDBCEventChannelCookieJar jdbcCookieJar, Context context) { super(context); this.pairId = ecp.getPairId(); this.jdbcCookieJar = jdbcCookieJar; } public Object internalGet(String name) { try { CookieJarResult cookie = jdbcCookieJar.get(pairId, name); if (cookie == null) { return null; } if (cookie.getValueString() != null) {return cookie.getValueString();} if (cookie.getValueObject() != null) {return cookie.getValueObject();} return new Double(cookie.getValueDouble()); } catch (SQLException e) { GlobalExceptionHandler.handle("Problem getting value for name="+name, e); return null; } } /** The interface requires Object value, but we really want it to be * limited to String Double and Serializable. */ public Object internalPut(String name, Object value) { try { if (value instanceof String) { jdbcCookieJar.put(pairId, name, (String)value); } else if (value instanceof Double) { jdbcCookieJar.put(pairId, name, ((Double)value).doubleValue()); } else if (value instanceof Serializable) { jdbcCookieJar.put(pairId, name, (Serializable)value); } else { throw new IllegalArgumentException("value must be a String or a Double or a Serializable: "+value.getClass().getName()); } } catch (SQLException e) { - GlobalExceptionHandler.handle("Problem putting value for name="+name, e); + GlobalExceptionHandler.handle("Problem putting value for name="+name + " pairid="+pairId, e); } return null; } public boolean internalContainsKey(Object name) { try { return jdbcCookieJar.containsKey(pairId, (String)name); } catch (SQLException e) { GlobalExceptionHandler.handle("Problem checking for pair="+pairId+" key="+name, e); return false; } } public Object[] internalGetKeys() { try { return jdbcCookieJar.getKeys(pairId); } catch (SQLException e) { GlobalExceptionHandler.handle("Problem getting keys for pair="+pairId, e); return new String[0]; } } public Object internalRemove(Object name) { try { return jdbcCookieJar.remove(pairId, (String)name); } catch (SQLException e) { GlobalExceptionHandler.handle("Problem checking for pair="+pairId+" key="+name, e); return null; } } int pairId; JDBCEventChannelCookieJar jdbcCookieJar; }
true
true
public Object internalPut(String name, Object value) { try { if (value instanceof String) { jdbcCookieJar.put(pairId, name, (String)value); } else if (value instanceof Double) { jdbcCookieJar.put(pairId, name, ((Double)value).doubleValue()); } else if (value instanceof Serializable) { jdbcCookieJar.put(pairId, name, (Serializable)value); } else { throw new IllegalArgumentException("value must be a String or a Double or a Serializable: "+value.getClass().getName()); } } catch (SQLException e) { GlobalExceptionHandler.handle("Problem putting value for name="+name, e); } return null; }
public Object internalPut(String name, Object value) { try { if (value instanceof String) { jdbcCookieJar.put(pairId, name, (String)value); } else if (value instanceof Double) { jdbcCookieJar.put(pairId, name, ((Double)value).doubleValue()); } else if (value instanceof Serializable) { jdbcCookieJar.put(pairId, name, (Serializable)value); } else { throw new IllegalArgumentException("value must be a String or a Double or a Serializable: "+value.getClass().getName()); } } catch (SQLException e) { GlobalExceptionHandler.handle("Problem putting value for name="+name + " pairid="+pairId, e); } return null; }
diff --git a/src/main/java/com/socrata/tools/CopyDataset.java b/src/main/java/com/socrata/tools/CopyDataset.java index bf941a4..72b669c 100644 --- a/src/main/java/com/socrata/tools/CopyDataset.java +++ b/src/main/java/com/socrata/tools/CopyDataset.java @@ -1,354 +1,358 @@ package com.socrata.tools; import com.google.common.collect.Lists; import com.socrata.api.HttpLowLevel; import com.socrata.api.Soda2Consumer; import com.socrata.api.Soda2Producer; import com.socrata.api.SodaDdl; import com.socrata.builders.SoqlQueryBuilder; import com.socrata.exceptions.LongRunningQueryException; import com.socrata.exceptions.SodaError; import com.socrata.model.UpsertResult; import com.socrata.model.importer.Column; import com.socrata.model.importer.Dataset; import com.socrata.model.importer.DatasetInfo; import com.socrata.model.soql.OrderByClause; import com.socrata.model.soql.SoqlQuery; import com.socrata.model.soql.SortOrder; import com.socrata.tools.utils.ConfigurationLoader; import com.socrata.tools.model.SocrataConnectionInfo; import com.socrata.tools.utils.CliUtils; import com.sun.jersey.api.client.ClientResponse; import org.apache.commons.cli.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; import javax.ws.rs.core.MediaType; import java.io.*; import java.nio.charset.Charset; import java.util.List; import java.util.zip.GZIPInputStream; /** */ public class CopyDataset { public static final Option DEST_DOMAIN = OptionBuilder.withArgName("destUrl" ) .hasArg() .withDescription( "The url for the destination domain, e.g. https://foo.bar.baz . This defaults to being the same domain as the source domain" ) .create("d"); public static final Option SOURCE_DOMAIN = OptionBuilder.withArgName("srcDomain") .hasArg() .withDescription( "The url for the source domain. This defaults to what is loaded in the connection config." ) .create("s"); public static final Option CONFIG_FILE = OptionBuilder.withArgName("connectionConfig") .hasArg() .withDescription( "The configuration file to load for user source domain URL/name/password/apptoken. Defaults to ~/.socrata/connection.json" ) .create("c"); public static final Option DEST_CONFIG_FILE = OptionBuilder.withArgName("destConnectionConfig") .hasArg() .withDescription( "The configuration file to load for user destination domain URL/name/password/apptoken. Defaults to whatever is used for the source domain." ) .create("x"); public static final Option DATA_FILE = OptionBuilder.withArgName("dataFile") .hasArg() .withDescription("The directory to look for data files to upload to the newly created dataset. " + "The tool will look for files that have the same name as the dataset id they go with. " + "These can be json or csv. In addition, the can be gzipped.") .create("f"); public static final Option CREATE_ONLY = OptionBuilder.withArgName("createOnly") .withDescription("Don't copy over data, ONLY create the new dataset.") .create("C"); public static final Option COPY_DATA = OptionBuilder.withArgName("copyDataLive") .withDescription("Do NOT use a file to import data. Copy it directly from the live dataset.") .create("p"); public static final Option CREATE_OPTIONS = OptionBuilder.withArgName("createOptions") .hasArg() .withDescription("This adds an option that should be passed on the URL when creating the dataset. E.g. $$testflag=true .") .create("o"); public static final Option USAGE_OPTIONS = OptionBuilder.withArgName("?") .withDescription("Shows usage.") .create("?"); public static final Options OPTIONS = new Options(); static { OPTIONS.addOption(DEST_DOMAIN); OPTIONS.addOption(SOURCE_DOMAIN); OPTIONS.addOption(CONFIG_FILE); OPTIONS.addOption(DATA_FILE); OPTIONS.addOption(CREATE_ONLY); OPTIONS.addOption(CREATE_OPTIONS); OPTIONS.addOption(COPY_DATA); OPTIONS.addOption(USAGE_OPTIONS); OPTIONS.addOption(DEST_CONFIG_FILE); } final boolean createOnly; final boolean copyDataLive; final SocrataConnectionInfo srcConnectionInfo; final SocrataConnectionInfo destConnectionInfo; final String srcDomain; final String destDomain; final File dataFileDir; final List<Pair<String, String>> parsedCreateOptions; /** * DatasetId * userName * userPassword * token * @param args */ public static void main(String[] args) throws SodaError, InterruptedException, IOException, LongRunningQueryException { CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(OPTIONS, args, false); String configFile = cmd.getOptionValue("c", CliUtils.defaultConfigFile().getCanonicalPath()); String destConfigFile = cmd.getOptionValue("x", configFile); if (cmd.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } try { final File config = new File(configFile); if (!config.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + configFile + ". Either use the -c option or setup a connection file there."); } final File destConfig = new File(destConfigFile); if (!destConfig.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + destConfig + ". Either use the -x option or setup a connection file there."); } final SocrataConnectionInfo connectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(config); CliUtils.validateConfiguration(connectionInfo); final SocrataConnectionInfo destConnectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(destConfig); CliUtils.validateConfiguration(destConnectionInfo); final String srcDomain = cmd.getOptionValue("s", connectionInfo.getUrl()); if (StringUtils.isEmpty(srcDomain)) { throw new IllegalArgumentException("No source domain specified in either the connection configuration or the commandline arguments."); } final String destDomain = cmd.getOptionValue("d", srcDomain); final String createOptions = cmd.getOptionValue("o"); final List<Pair<String, String>> parsedCreateOptions = CliUtils.parseOptions(createOptions, Charset.defaultCharset()); final File dataFileDir = new File(cmd.getOptionValue("f", ".")); final boolean copyDataLive = cmd.hasOption("p"); final boolean createOnly = cmd.hasOption("C"); final Writer output = new OutputStreamWriter(System.out); final CopyDataset copyDataset = new CopyDataset(srcDomain, destDomain, connectionInfo, destConnectionInfo, dataFileDir, parsedCreateOptions, createOnly, copyDataLive); final List<Pair<Dataset, UpsertResult>> results = copyDataset.doCopy(cmd.getArgs(), output); output.flush(); for (Pair<Dataset, UpsertResult> result : results) { System.out.println("Created dataset " + destDomain + "/id/" + result.getKey().getId() + ". Created " + result.getValue().getRowsCreated()); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } } catch (ParseException e) { System.err.println( "Parsing failed. Reason: " + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); + } catch (Exception e) { + System.err.println( "Failure copying dataset: " + e.getMessage() ); + e.printStackTrace(); + System.exit(1); } } public CopyDataset(String srcDomain, String destDomain, SocrataConnectionInfo srcConnectionInfo, SocrataConnectionInfo destConnectionInfo, File dataFileDir, List<Pair<String, String>> parsedCreateOptions, boolean createOnly, boolean copyDataLive) { this.srcDomain = srcDomain; this.destDomain = destDomain; this.srcConnectionInfo = srcConnectionInfo; this.destConnectionInfo = destConnectionInfo; this.dataFileDir = dataFileDir; this.parsedCreateOptions = parsedCreateOptions; this.createOnly = createOnly; this.copyDataLive = copyDataLive; } public List<Pair<Dataset, UpsertResult>> doCopy(String[] datasetIds, Writer output) throws SodaError, InterruptedException, LongRunningQueryException, IOException { List<Pair<Dataset, UpsertResult>> results = Lists.newArrayList(); for (String datasetId : datasetIds) { results.add(doCopy(datasetId, output)); } return results; } public Pair<Dataset, UpsertResult> doCopy(String datasetId, Writer output) throws SodaError, InterruptedException, LongRunningQueryException, IOException { final SodaDdl ddlSrc = SodaDdl.newDdl(srcDomain, srcConnectionInfo.getUser(), srcConnectionInfo.getPassword(), srcConnectionInfo.getToken()); final SodaDdl ddlDest = SodaDdl.newDdl(destDomain, destConnectionInfo.getUser(), destConnectionInfo.getPassword(), destConnectionInfo.getToken()); for (Pair<String, String> createOption : parsedCreateOptions) { ddlDest.getHttpLowLevel().getAdditionalParameters().put(createOption.getKey(), createOption.getValue()); } final Dataset srcDataset = loadSourceSchema(ddlSrc, datasetId); final DatasetInfo destDatasetTemplate = Dataset.copy(srcDataset); final Dataset destDataset = createDestSchema(ddlDest, srcDataset, destDatasetTemplate, output); final Soda2Producer producerDest = Soda2Producer.newProducer(destDomain, destConnectionInfo.getUser(), destConnectionInfo.getPassword(), destConnectionInfo.getToken()); UpsertResult upsertResult = new UpsertResult(0, 0, 0, null); //Now for the data part if (!createOnly) { if (copyDataLive) { upsertResult = copyDataLive(producerDest, srcDataset.getId(), destDataset.getId(), output); } else { upsertResult = importDataFile(producerDest, destDataset.getId(), dataFileDir, output); } } return Pair.of(destDataset, upsertResult); } public static Dataset loadSourceSchema(SodaDdl ddlSrc, String datasetId) throws SodaError, InterruptedException { final DatasetInfo datasetInfo = ddlSrc.loadDatasetInfo(datasetId); if (!(datasetInfo instanceof Dataset)) { throw new SodaError("Can currently only copy datasets."); } return (Dataset) datasetInfo; } public static Dataset createDestSchema(SodaDdl ddlDest, Dataset srcDataset, DatasetInfo destDatasetTemplate, Writer output) throws SodaError, InterruptedException, IOException { destDatasetTemplate.setResourceName(null); Dataset newDataset = (Dataset) ddlDest.createDataset(destDatasetTemplate); if (output != null) { output.write("Created dataset " + newDataset.getName() + ". 4x4 is " + newDataset.getId() + "\n"); output.flush(); } for (Column column : srcDataset.getColumns()) { ddlDest.addColumn(newDataset.getId(), column); if (output != null) { output.write("Added column " + column.getName() + ".\n"); output.flush(); } } ddlDest.publish(newDataset.getId()); return (Dataset) ddlDest.loadDatasetInfo(newDataset.getId()); } @Nonnull public static UpsertResult importDataFile(Soda2Producer producerDest, String destId, File dataFile, Writer output) throws IOException, SodaError, InterruptedException { if (!dataFile.exists()) { throw new SodaError(dataFile.getCanonicalPath() + " does not exist.\n"); } String unprocecessedName = dataFile.getName(); String extToProcess = getExtension(unprocecessedName); InputStream is = new FileInputStream(dataFile); if (extToProcess.equals(".gz")) { is = new GZIPInputStream(is); unprocecessedName = unprocecessedName.substring(0, unprocecessedName.length() - extToProcess.length()); extToProcess = getExtension(unprocecessedName); } MediaType mediaType = HttpLowLevel.CSV_TYPE; if (extToProcess.equals(".json")) { mediaType = HttpLowLevel.JSON_TYPE; } if (output != null) { output.write("Upserting file " + dataFile.getCanonicalPath() + " as " + mediaType + "\n"); output.flush(); } return producerDest.upsertStream(destId, mediaType, is); } public UpsertResult copyDataLive(Soda2Producer producerDest, String srcId, String destId, Writer output) throws LongRunningQueryException, SodaError, InterruptedException, IOException { if (output != null) { output.write("Copying data live from " + srcId + ".\n"); output.flush(); } final Soda2Consumer querySource = Soda2Consumer.newConsumer(srcDomain, srcConnectionInfo.getUser(), srcConnectionInfo.getPassword(), srcConnectionInfo.getToken()); SoqlQueryBuilder builder = new SoqlQueryBuilder(SoqlQuery.SELECT_ALL) .addOrderByPhrase(new OrderByClause(SortOrder.Ascending, ":id")) .setLimit(1000); int offset = 0; long rowsAdded = 0; boolean hasMore = true; while (hasMore) { ClientResponse response = querySource.query(srcId, HttpLowLevel.JSON_TYPE, builder.setOffset(offset).build()); UpsertResult result = producerDest.upsertStream(destId, HttpLowLevel.JSON_TYPE, response.getEntityInputStream()); offset+=1000; rowsAdded+=result.getRowsCreated(); if (output != null) { if ((rowsAdded % 40000) == 0) { output.write('\n'); output.flush(); } else { output.write('.'); output.flush(); } } if (result.getRowsCreated() == 0) { hasMore = false; } } return new UpsertResult(rowsAdded, 0, 0, null); } @Nonnull private static String getExtension(String fileName) { final int lastDot = fileName.lastIndexOf('.'); if (lastDot == -1 || lastDot==fileName.length()) { return ""; } return fileName.substring(lastDot); } }
true
true
public static void main(String[] args) throws SodaError, InterruptedException, IOException, LongRunningQueryException { CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(OPTIONS, args, false); String configFile = cmd.getOptionValue("c", CliUtils.defaultConfigFile().getCanonicalPath()); String destConfigFile = cmd.getOptionValue("x", configFile); if (cmd.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } try { final File config = new File(configFile); if (!config.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + configFile + ". Either use the -c option or setup a connection file there."); } final File destConfig = new File(destConfigFile); if (!destConfig.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + destConfig + ". Either use the -x option or setup a connection file there."); } final SocrataConnectionInfo connectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(config); CliUtils.validateConfiguration(connectionInfo); final SocrataConnectionInfo destConnectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(destConfig); CliUtils.validateConfiguration(destConnectionInfo); final String srcDomain = cmd.getOptionValue("s", connectionInfo.getUrl()); if (StringUtils.isEmpty(srcDomain)) { throw new IllegalArgumentException("No source domain specified in either the connection configuration or the commandline arguments."); } final String destDomain = cmd.getOptionValue("d", srcDomain); final String createOptions = cmd.getOptionValue("o"); final List<Pair<String, String>> parsedCreateOptions = CliUtils.parseOptions(createOptions, Charset.defaultCharset()); final File dataFileDir = new File(cmd.getOptionValue("f", ".")); final boolean copyDataLive = cmd.hasOption("p"); final boolean createOnly = cmd.hasOption("C"); final Writer output = new OutputStreamWriter(System.out); final CopyDataset copyDataset = new CopyDataset(srcDomain, destDomain, connectionInfo, destConnectionInfo, dataFileDir, parsedCreateOptions, createOnly, copyDataLive); final List<Pair<Dataset, UpsertResult>> results = copyDataset.doCopy(cmd.getArgs(), output); output.flush(); for (Pair<Dataset, UpsertResult> result : results) { System.out.println("Created dataset " + destDomain + "/id/" + result.getKey().getId() + ". Created " + result.getValue().getRowsCreated()); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } } catch (ParseException e) { System.err.println( "Parsing failed. Reason: " + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } }
public static void main(String[] args) throws SodaError, InterruptedException, IOException, LongRunningQueryException { CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(OPTIONS, args, false); String configFile = cmd.getOptionValue("c", CliUtils.defaultConfigFile().getCanonicalPath()); String destConfigFile = cmd.getOptionValue("x", configFile); if (cmd.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } try { final File config = new File(configFile); if (!config.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + configFile + ". Either use the -c option or setup a connection file there."); } final File destConfig = new File(destConfigFile); if (!destConfig.canRead()) { throw new IllegalArgumentException("Unable to load connection configuration from " + destConfig + ". Either use the -x option or setup a connection file there."); } final SocrataConnectionInfo connectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(config); CliUtils.validateConfiguration(connectionInfo); final SocrataConnectionInfo destConnectionInfo = ConfigurationLoader.loadSocrataConnectionConfig(destConfig); CliUtils.validateConfiguration(destConnectionInfo); final String srcDomain = cmd.getOptionValue("s", connectionInfo.getUrl()); if (StringUtils.isEmpty(srcDomain)) { throw new IllegalArgumentException("No source domain specified in either the connection configuration or the commandline arguments."); } final String destDomain = cmd.getOptionValue("d", srcDomain); final String createOptions = cmd.getOptionValue("o"); final List<Pair<String, String>> parsedCreateOptions = CliUtils.parseOptions(createOptions, Charset.defaultCharset()); final File dataFileDir = new File(cmd.getOptionValue("f", ".")); final boolean copyDataLive = cmd.hasOption("p"); final boolean createOnly = cmd.hasOption("C"); final Writer output = new OutputStreamWriter(System.out); final CopyDataset copyDataset = new CopyDataset(srcDomain, destDomain, connectionInfo, destConnectionInfo, dataFileDir, parsedCreateOptions, createOnly, copyDataLive); final List<Pair<Dataset, UpsertResult>> results = copyDataset.doCopy(cmd.getArgs(), output); output.flush(); for (Pair<Dataset, UpsertResult> result : results) { System.out.println("Created dataset " + destDomain + "/id/" + result.getKey().getId() + ". Created " + result.getValue().getRowsCreated()); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } } catch (ParseException e) { System.err.println( "Parsing failed. Reason: " + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "copydataset", OPTIONS ); System.exit(1); } catch (Exception e) { System.err.println( "Failure copying dataset: " + e.getMessage() ); e.printStackTrace(); System.exit(1); } }
diff --git a/src/dk/dbc/opensearch/components/harvest/FileHarvest.java b/src/dk/dbc/opensearch/components/harvest/FileHarvest.java index ab50730f..a7625fcb 100644 --- a/src/dk/dbc/opensearch/components/harvest/FileHarvest.java +++ b/src/dk/dbc/opensearch/components/harvest/FileHarvest.java @@ -1,461 +1,461 @@ /** * \file FileHarvest.java * \brief The FileHarvest class * \package components.harvest; */ package dk.dbc.opensearch.components.harvest; import dk.dbc.opensearch.common.config.DatadockConfig; import dk.dbc.opensearch.common.config.HarvesterConfig; import dk.dbc.opensearch.common.helpers.XMLFileReader; import dk.dbc.opensearch.common.types.DatadockJob; import dk.dbc.opensearch.common.types.Pair; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.util.HashSet; import java.util.Vector; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * FileHarvest class. Implements the IHarvester interface and acts as a * fileharvester for the datadock. It implements the methods start, * shutdown and getJobs. It is an eventdriven class. * * This file harvester assumes some things about path given as an argument: * * The path has to be a directory with the following structure: * * polling path * | - submitter1 * | | -format1 * | | | - job1 * | | | - job2 * | | -format2 * | | | - job3 * | - submitter2 * . * . * . * * There are no restrictions on the number of submitters, formats or * jobs - and the jobs can be files or directorys. * * The harvester only returns a job after the second consecutive time * it has been found and its filesize is unchanged. */ public class FileHarvest implements IHarvester { static Logger log = Logger.getLogger( FileHarvest.class ); private File path; private Vector< Pair< File, Long > > submitters; private Vector< Pair< File, Long > > formats; private Vector< Pair< String, String > > submittersFormatsVector; //private HashSet< File > jobSet; //private HashSet< Pair< File, Long > > jobApplications; /** * Constructs the FileHarvest class, and starts polling the given path for * files and subsequent file-changes. * * @param path The path to the directory to harvest from. * * @throws IllegalArgumentException if the path given is not a directory. * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws ConfigurationException */ public FileHarvest( File path ) throws IllegalArgumentException, ParserConfigurationException, SAXException, IOException, ConfigurationException { System.out.println(String.format( "Constructor( path='%s' )", path.getAbsolutePath() ) ); log.debug( String.format( "Constructor( path='%s' )", path.getAbsolutePath() ) ); if ( ! path.isDirectory() ) { throw new IllegalArgumentException( String.format( "'%s' is not a directory !", path.getAbsolutePath() ) ); } this.path = path; //this.jobApplications = new HashSet< Pair< File, Long > >(); this.submitters = new Vector< Pair< File, Long > >(); this.formats = new Vector< Pair< File, Long > >(); //this.jobSet = new HashSet< File >(); String datadockJobsFilePath = DatadockConfig.getPath(); File datadockJobsFile = new File( datadockJobsFilePath ); NodeList jobNodeList = XMLFileReader.getNodeList( datadockJobsFile, "job" ); submittersFormatsVector = new Vector< Pair< String, String > >(); for( int i = 0; i < jobNodeList.getLength(); i++ ) { Element pluginElement = (Element)jobNodeList.item( i ); String formatAtt = pluginElement.getAttribute( "format" ); String submitterAtt = pluginElement.getAttribute( "submitter" ); if( ! submittersFormatsVector.contains( formatAtt ) ) { log.debug( String.format( "Adding submitter and format to Vector submitterFormatPair: %s and %s", submitterAtt, formatAtt ) ); Pair< String, String > submitterFormatPair = new Pair< String, String >( submitterAtt, formatAtt ); submittersFormatsVector.add( submitterFormatPair ); } } } /** * Starts The datadock. It initializes vectors and add found jobs to the application vector. */ public void start() { log.debug( "start() called" ); initVectors(); log.debug( "Vectors initialized" ); /*HashSet< Pair< File, Long > > temp = findAllJobs(); for( Pair< File, Long > job : temp ) { System.out.println( String.format( "adding path='%s' to jobSet and jobApllications", job.getFirst().getAbsolutePath() ) ); log.debug( String.format( "adding path='%s' to jobSet and jobApllications", job.getFirst().getAbsolutePath() ) ); jobSet.add( job.getFirst() ); } jobApplications = temp;*/ } /** * Shuts down the fileharvester */ public void shutdown() { log.debug( "shutdown() called" ); } /** * getJobs. Locate jobs and returns them. First off, the * candidates already registered analyzed. if their filesize has * remained the same as last time it is removed from the * applications vector and added to the newJobs vector and * returned when the method exits. * * afterwards it finds new jobs and adds them to the applications * vector, and generate a new snapshot of the harvest directory. * @throws ConfigurationException * * @returns A vector of Datadockjobs containing the necessary information to process the jobs. */ public Vector< DatadockJob > getJobs() throws FileNotFoundException, IOException, ConfigurationException { Vector< DatadockJob > jobs = new Vector< DatadockJob>(); HashSet< Pair< File, Long > > newJobs = getNewJobs(); for( Pair< File, Long > job : newJobs ) { URI uri = job.getFirst().toURI(); String grandParentFile = job.getFirst().getParentFile().getParentFile().getName(); String parentFile = job.getFirst().getParentFile().getName(); DatadockJob datadockJob = new DatadockJob( uri, grandParentFile, parentFile ); log.debug( String.format( "found new job: path='%s', submitter='%s', format='%s'", datadockJob.getUri().getRawPath(), datadockJob.getSubmitter(), datadockJob.getFormat() ) ); jobs.add( datadockJob ); } return jobs; } private HashSet< Pair< File, Long > > getNewJobs() throws FileNotFoundException, IOException, ConfigurationException { log.debug( "Calling FileHarvest.getNewJobs"); HashSet< Pair< File, Long > > jobs = new HashSet< Pair< File, Long > >(); String toHarvestFolder = HarvesterConfig.getFolder(); String harvestDoneFolder = HarvesterConfig.getDoneFolder(); int max = HarvesterConfig.getMaxToHarvest(); log.debug( "FileHarvest.getNewJobs: Vector formats: " + formats.toString() ); for( Pair< File, Long > format : formats ) { File[] files = format.getFirst().listFiles(); int l = files.length; int i = 0; while( i < l && i < max ) { File job = files[i]; //jobs.add( new Pair< File, Long >( job, job.length() ) ); String path = job.getPath(); String newPath = path.replace( toHarvestFolder, harvestDoneFolder ); String destFldrStr = newPath.substring( 0, newPath.lastIndexOf( "/" ) ); File destFldr = new File( destFldrStr ); File dest = new File( newPath ); move( job, destFldr, dest ); jobs.add( new Pair< File, Long >( dest, dest.length() ) ); i++; } } log.debug( "FileHarvest.getNewsJobs done harvesting first files max: " + max ); return jobs; } public void move( File src, File destFldr, File dest ) throws FileNotFoundException, IOException { log.debug( "Creating new destFldr: " + destFldr.getAbsolutePath().toString() ); boolean ok = false; if ( ! destFldr.exists() ) { ok = destFldr.mkdirs(); } else { ok = true; } if ( ok ) { log.debug( "destFldr created: " + destFldr.getPath().toString() ); ok = src.renameTo( dest ); if ( ok ) { - log.debug( "New file created: " + dest.getPath().toString() ); - ok = src.delete(); - if ( ok ) - { - log.debug( "Old file deleted: " + src.getAbsolutePath().toString() ); - } - else - { - log.debug( "Could not delete old file: " + src.getAbsolutePath().toString() ); - throw new IOException( "IOException thrown in FileHarvest.move: Could not delete old file: " + src.getAbsolutePath().toString() ); - } +// log.debug( "New file created: " + dest.getPath().toString() ); +// ok = src.delete(); +// if ( ok ) +// { +// log.debug( "Old file deleted: " + src.getAbsolutePath().toString() ); +// } +// else +// { +// log.debug( "Could not delete old file: " + src.getAbsolutePath().toString() ); +// throw new IOException( "IOException thrown in FileHarvest.move: Could not delete old file: " + src.getAbsolutePath().toString() ); +// } } else { - log.debug( "Could not create new file: " + dest.getAbsolutePath().toString() ); + log.debug( String.format( "Could not rename file: %s to %s", src.getAbsolutePath().toString(), dest.getAbsolutePath().toString() ) ); throw new IOException( "IOException thrown in FileHarvest.move: Could not create new file: " + src.getAbsolutePath().toString() ); } } else { log.debug( "Could not create destination folder for old files: " + destFldr.getAbsolutePath().toString() ); throw new IOException( "IOException thrown in FileHarvest move: Could not create destination folder for old files:" + destFldr.getAbsolutePath().toString() ); } } /*public Vector< DatadockJob > getJobs2() { log.debug( "FileHarvest getJobs called " ); // validating candidates - if the filelength have remained the // same for two consecutive calls it is added to newJobs Vector< DatadockJob > newJobs = new Vector<DatadockJob>(); HashSet< Pair< File, Long > > removeJobs = new HashSet< Pair< File, Long > >(); //System.out.println( jobApplications ); for( Pair< File, Long > job : jobApplications ) { if( job.getFirst().length() == job.getSecond() ) { DatadockJob datadockJob = new DatadockJob( job.getFirst().toURI(), job.getFirst().getParentFile().getParentFile().getName(), job.getFirst().getParentFile().getName() ); System.out.println( String.format( "found new job: path='%s', submitter='%s', format='%s'", datadockJob.getUri().getRawPath(), datadockJob.getSubmitter(), datadockJob.getFormat() ) ); log.debug( String.format( "found new job: path='%s', submitter='%s', format='%s'", datadockJob.getUri().getRawPath(), datadockJob.getSubmitter(), datadockJob.getFormat() ) ); newJobs.add( datadockJob ); removeJobs.add( job ); } } // removing confirmed jobs from applications for( Pair< File, Long > job : removeJobs ) { log.debug( String.format( "Removing job='%s' from applications", job.getFirst().getAbsolutePath() ) ); jobApplications.remove( job ); } // Finding new Jobs // Has anything happened ? boolean changed = false; for( Pair< File, Long > format : formats ) { if( format.getFirst().lastModified() > format.getSecond() ) { changed = true; } } if( changed ) { log.debug( "Files changed" ); for( File newJob : findNewJobs() ) { log.debug( String.format( "adding new job to applications: path='%s'", newJob.getAbsolutePath() ) ); jobApplications.add( new Pair< File, Long >( newJob, newJob.length() ) ); } // generating new snapshot submitters = new Vector<Pair<File, Long >>(); formats = new Vector<Pair<File, Long >>(); initVectors(); jobSet = new HashSet< File >(); for( Pair< File, Long > job : findAllJobs() ) { //log.debug( String.format( "adding path='%s' to jobSet", Tuple.get1( job ).getAbsolutePath() ) ); //log.debug( String.format( "adding path='%s' to jobSet", job.getFirst().getAbsolutePath() ) ); //jobSet.add( Tuple.get1( job ) ); //jobSet.add( job.getFirst() ); } } return newJobs; }*/ /** * Private method to initialize the local vectors representing the * polling directory. */ private void initVectors() { log.debug( "initvectors() called" ); log.debug( "submitterFormatsVector: \n" + submittersFormatsVector.toString() ); log.debug( "Submitters:" ); for( File submitter : path.listFiles() ) { if( submitter.isDirectory() ) { log.debug( String.format( "adding submitter: path='%s'", submitter.getAbsolutePath() ) ); submitters.add( new Pair< File, Long >( submitter, submitter.lastModified() ) ); } } log.debug( "formats:" ); for( Pair<File, Long> submitter : submitters ) { File submitterFile = submitter.getFirst(); for( File format : submitterFile.listFiles() ) { if ( checkSubmitterFormat( submitterFile, format ) ) { log.debug( String.format( "format: path='%s'", format.getAbsolutePath() ) ); formats.add( new Pair< File, Long >( format, format.lastModified() ) ); } } } } private boolean checkSubmitterFormat( File submitterFile, File formatFile ) { String submitterFilePath = sanitize( submitterFile ); String formatFilePath = sanitize( formatFile ); submitterFilePath = submitterFile.getAbsolutePath().substring( submitterFile.getAbsolutePath().lastIndexOf( "/" ) + 1 ); log.debug( "FileHarvest.checkSubmitterFormat -> submitter: " + submitterFilePath ); formatFilePath = formatFile.getAbsolutePath().substring( formatFile.getAbsolutePath().lastIndexOf( "/") + 1 ); log.debug( "FileHarvest.checkSubmitterFormat -> format: " + formatFilePath ); Pair< String, String > pair = new Pair< String, String >( submitterFilePath, formatFilePath ); boolean contains = submittersFormatsVector.contains( pair ); log.debug( "FileHarvest.checkSubmitterFormat -> contains: " + contains ); if ( contains ) { return true; } else { log.debug( "FileHarvest.checkSubmitterFormat -> Vector: " + submittersFormatsVector.toString() ); return false; } } private String sanitize( File file ) { if ( file.getAbsolutePath().endsWith( "/" ) ) { return ( String )file.getAbsolutePath().subSequence( 0 , ( file.getAbsolutePath().length() - 1) ); } else { return file.getAbsolutePath(); } } /** * Finds the new jobs in the poll Directory * * @returns a hashset of new job files. */ /*private HashSet< File > findNewJobs() { log.debug( "findNewJobs() called" ); HashSet< File > currentJobs = new HashSet< File >(); for( Pair< File, Long > job : findAllJobs() ) { currentJobs.add( job.getFirst() ); } HashSet<File> newJobs = new HashSet<File>( jobSet ); log.debug( String.format( "newjob size='%s', '%s'", newJobs.size(), newJobs.size() ) ); newJobs.addAll( currentJobs ); newJobs.removeAll( jobSet ); for( File job : newJobs ) { log.debug( String.format( "found job: '%s'", job.getAbsolutePath() ) ); } return newJobs; }*/ /** * Finds all jobs in the poll Directory * * @returns a hashset of pairs containing new job files and their size. */ /*private HashSet< Pair< File, Long > > findAllJobs() { log.debug( "findAllJobs() called" ); HashSet< Pair< File, Long > > jobs = new HashSet< Pair< File, Long > >(); for( Pair< File, Long > format : formats ) { int l = format.getFirst().listFiles().length; log.debug( "FileHarvest: fileList length:" + l + " Format: " + format.getFirst().getAbsolutePath() ); for( File job : format.getFirst().listFiles() ) { log.debug( String.format( "found job: '%s'", job.getAbsolutePath() ) ); jobs.add( new Pair< File, Long >( job, job.length() ) ); } } return jobs; }*/ }
false
true
public void move( File src, File destFldr, File dest ) throws FileNotFoundException, IOException { log.debug( "Creating new destFldr: " + destFldr.getAbsolutePath().toString() ); boolean ok = false; if ( ! destFldr.exists() ) { ok = destFldr.mkdirs(); } else { ok = true; } if ( ok ) { log.debug( "destFldr created: " + destFldr.getPath().toString() ); ok = src.renameTo( dest ); if ( ok ) { log.debug( "New file created: " + dest.getPath().toString() ); ok = src.delete(); if ( ok ) { log.debug( "Old file deleted: " + src.getAbsolutePath().toString() ); } else { log.debug( "Could not delete old file: " + src.getAbsolutePath().toString() ); throw new IOException( "IOException thrown in FileHarvest.move: Could not delete old file: " + src.getAbsolutePath().toString() ); } } else { log.debug( "Could not create new file: " + dest.getAbsolutePath().toString() ); throw new IOException( "IOException thrown in FileHarvest.move: Could not create new file: " + src.getAbsolutePath().toString() ); } } else { log.debug( "Could not create destination folder for old files: " + destFldr.getAbsolutePath().toString() ); throw new IOException( "IOException thrown in FileHarvest move: Could not create destination folder for old files:" + destFldr.getAbsolutePath().toString() ); } }
public void move( File src, File destFldr, File dest ) throws FileNotFoundException, IOException { log.debug( "Creating new destFldr: " + destFldr.getAbsolutePath().toString() ); boolean ok = false; if ( ! destFldr.exists() ) { ok = destFldr.mkdirs(); } else { ok = true; } if ( ok ) { log.debug( "destFldr created: " + destFldr.getPath().toString() ); ok = src.renameTo( dest ); if ( ok ) { // log.debug( "New file created: " + dest.getPath().toString() ); // ok = src.delete(); // if ( ok ) // { // log.debug( "Old file deleted: " + src.getAbsolutePath().toString() ); // } // else // { // log.debug( "Could not delete old file: " + src.getAbsolutePath().toString() ); // throw new IOException( "IOException thrown in FileHarvest.move: Could not delete old file: " + src.getAbsolutePath().toString() ); // } } else { log.debug( String.format( "Could not rename file: %s to %s", src.getAbsolutePath().toString(), dest.getAbsolutePath().toString() ) ); throw new IOException( "IOException thrown in FileHarvest.move: Could not create new file: " + src.getAbsolutePath().toString() ); } } else { log.debug( "Could not create destination folder for old files: " + destFldr.getAbsolutePath().toString() ); throw new IOException( "IOException thrown in FileHarvest move: Could not create destination folder for old files:" + destFldr.getAbsolutePath().toString() ); } }
diff --git a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/web/RestStatisticsService.java b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/web/RestStatisticsService.java index 30ecfa2f..a3b090fa 100644 --- a/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/web/RestStatisticsService.java +++ b/bitrepository-integrity-service/src/main/java/org/bitrepository/integrityservice/web/RestStatisticsService.java @@ -1,125 +1,125 @@ /* * #%L * Bitrepository Integrity Service * %% * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package org.bitrepository.integrityservice.web; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.common.utils.TimeUtils; import org.bitrepository.common.webobjects.StatisticsCollectionSize; import org.bitrepository.common.webobjects.StatisticsDataSize; import org.bitrepository.common.webobjects.StatisticsPillarSize; import org.bitrepository.integrityservice.IntegrityServiceManager; import org.bitrepository.integrityservice.cache.CollectionStat; import org.bitrepository.integrityservice.cache.IntegrityModel; import org.bitrepository.integrityservice.cache.PillarStat; @Path("/Statistics") public class RestStatisticsService { private IntegrityModel model; public RestStatisticsService() { this.model = IntegrityServiceManager.getIntegrityModel(); } @GET @Path("/getDataSizeHistory/") @Produces(MediaType.APPLICATION_JSON) public List<StatisticsDataSize> getDataSizeHistory(@QueryParam("collectionID") String collectionID, @QueryParam("maxEntries") @DefaultValue("1000") int maxEntries) { List<CollectionStat> stats = model.getLatestCollectionStat(collectionID, maxEntries); List<StatisticsDataSize> data = new ArrayList<StatisticsDataSize>(); for(CollectionStat stat : stats) { StatisticsDataSize obj = new StatisticsDataSize(); Date statTime = stat.getStatsTime(); obj.setDateMillis(statTime.getTime()); obj.setDateString(TimeUtils.shortDate(statTime)); obj.setDataSize(stat.getDataSize()); data.add(obj); } return data; } @GET @Path("/getLatestPillarDataSize/") @Produces(MediaType.APPLICATION_JSON) public List<StatisticsPillarSize> getLatestPillarDataSize() { return getCurrentPillarsDataSize(); } @GET @Path("/getLatestcollectionDataSize/") @Produces(MediaType.APPLICATION_JSON) public List<StatisticsCollectionSize> getLatestCollectionDataSize() { List<StatisticsCollectionSize> data = new ArrayList<StatisticsCollectionSize>(); List<CollectionStat> stats = getLatestCollectionStatistics(); for(CollectionStat stat : stats) { StatisticsCollectionSize obj = new StatisticsCollectionSize(); obj.setCollectionID(stat.getCollectionID()); obj.setDataSize(stat.getDataSize()); data.add(obj); } return data; } public List<CollectionStat> getLatestCollectionStatistics() { List<CollectionStat> res = new ArrayList<CollectionStat>(); for(String collection : SettingsUtils.getAllCollectionsIDs()) { List<CollectionStat> stats = model.getLatestCollectionStat(collection, 1); if(!stats.isEmpty()) { res.add(stats.get(0)); } } return res; } public List<StatisticsPillarSize> getCurrentPillarsDataSize() { Map<String, StatisticsPillarSize> stats = new HashMap<String, StatisticsPillarSize>(); for(String pillar: SettingsUtils.getAllPillarIDs()) { StatisticsPillarSize stat = new StatisticsPillarSize(); stat.setPillarID(pillar); stat.setDataSize(0L); stats.put(pillar, stat); } for(String collection : SettingsUtils.getAllCollectionsIDs()) { for(PillarStat pillarStat : model.getLatestPillarStats(collection)) { StatisticsPillarSize stat = stats.get(pillarStat.getPillarID()); stat.setDataSize(stat.getDataSize() + pillarStat.getDataSize()); stats.put(stat.getPillarID(), stat); } } - return (List<StatisticsPillarSize>) stats.values(); + return new ArrayList<StatisticsPillarSize>(stats.values()); } }
true
true
public List<StatisticsPillarSize> getCurrentPillarsDataSize() { Map<String, StatisticsPillarSize> stats = new HashMap<String, StatisticsPillarSize>(); for(String pillar: SettingsUtils.getAllPillarIDs()) { StatisticsPillarSize stat = new StatisticsPillarSize(); stat.setPillarID(pillar); stat.setDataSize(0L); stats.put(pillar, stat); } for(String collection : SettingsUtils.getAllCollectionsIDs()) { for(PillarStat pillarStat : model.getLatestPillarStats(collection)) { StatisticsPillarSize stat = stats.get(pillarStat.getPillarID()); stat.setDataSize(stat.getDataSize() + pillarStat.getDataSize()); stats.put(stat.getPillarID(), stat); } } return (List<StatisticsPillarSize>) stats.values(); }
public List<StatisticsPillarSize> getCurrentPillarsDataSize() { Map<String, StatisticsPillarSize> stats = new HashMap<String, StatisticsPillarSize>(); for(String pillar: SettingsUtils.getAllPillarIDs()) { StatisticsPillarSize stat = new StatisticsPillarSize(); stat.setPillarID(pillar); stat.setDataSize(0L); stats.put(pillar, stat); } for(String collection : SettingsUtils.getAllCollectionsIDs()) { for(PillarStat pillarStat : model.getLatestPillarStats(collection)) { StatisticsPillarSize stat = stats.get(pillarStat.getPillarID()); stat.setDataSize(stat.getDataSize() + pillarStat.getDataSize()); stats.put(stat.getPillarID(), stat); } } return new ArrayList<StatisticsPillarSize>(stats.values()); }
diff --git a/JMathTextField.java b/JMathTextField.java index dfe619e..c16a920 100644 --- a/JMathTextField.java +++ b/JMathTextField.java @@ -1,151 +1,151 @@ package applets.Termumformungen$in$der$Technik_03_Logistik; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.PlainDocument; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; public class JMathTextField extends JTextField { private static final long serialVersionUID = 3991754180692357067L; { this.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { moveCaretPosition(0); setCaretPosition(getText().length()); } public void focusLost(FocusEvent e) {} }); } private OperatorTree operatorTree = new OperatorTree(); public OperatorTree getOperatorTree() { return operatorTree; } protected void updateByOpTree(javax.swing.text.DocumentFilter.FilterBypass fb) { String oldStr = JMathTextField.this.getText(); String newStr = operatorTree.toString(); int commonStart = Utils.equalStartLen(oldStr, newStr); int commonEnd = Utils.equalEndLen(oldStr, newStr); if(commonEnd + commonStart >= Math.min(oldStr.length(), newStr.length())) commonEnd = Math.min(oldStr.length(), newStr.length()) - commonStart; try { fb.replace(commonStart, oldStr.length() - commonEnd - commonStart, newStr.substring(commonStart, newStr.length() - commonEnd), null); } catch (BadLocationException e) { // this should not happen. we should have checked this. this whole function should be safe throw new AssertionError(e); } } @Override protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String replStr = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 <= s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && replStr.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && replStr.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } - if(replLen == 0 && string.matches("\\+|-|\\*|/|\\^|=")) { - if(s.substring(replOffset).matches("( *((\\+|-|∙|/|\\^|=|\\)).*))|")) { + if(string.matches("\\+|-|\\*|/|\\^|=")) { + if(s.substring(replOffset+replLen).matches("( *(\\+|-|∙|/|\\^|=|\\)).*)|")) { string = string + "_"; insertedDummyChar = true; - } else if(s.substring(replOffset).matches(" .*")) { + } else if(s.substring(replOffset+replLen).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || replStr.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + replStr + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !replStr.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; } }
false
true
protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String replStr = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 <= s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && replStr.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && replStr.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } if(replLen == 0 && string.matches("\\+|-|\\*|/|\\^|=")) { if(s.substring(replOffset).matches("( *((\\+|-|∙|/|\\^|=|\\)).*))|")) { string = string + "_"; insertedDummyChar = true; } else if(s.substring(replOffset).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || replStr.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + replStr + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !replStr.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; }
protected Document createDefaultModel() { PlainDocument d = (PlainDocument) super.createDefaultModel(); d.setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { replace(fb, offset, 0, string, attr); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { replace(fb, offset, length, "", null); } @Override public void replace(FilterBypass fb, int replOffset, int replLen, String string, AttributeSet attrs) throws BadLocationException { String s = JMathTextField.this.getText(); boolean insertedDummyChar = false; boolean insertedBrackets = false; String replStr = s.substring(replOffset, replOffset + replLen); if(string.matches(" |\\)") && replOffset + 1 <= s.length() && s.substring(replOffset, replOffset + 1).equals(string)) { JMathTextField.this.setCaretPosition(replOffset + 1); return; } string = string.replace(" ", ""); if(string.isEmpty() && replStr.equals("(")) { int count = 1; while(replOffset + replLen < s.length()) { replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } else if(string.isEmpty() && replStr.equals(")")) { int count = -1; while(replOffset > 0) { replOffset--; replLen++; replStr = s.substring(replOffset, replOffset + replLen); if(replStr.charAt(0) == '(') count++; else if(replStr.charAt(0) == ')') count--; if(count == 0) break; } } if(string.matches("\\+|-|\\*|/|\\^|=")) { if(s.substring(replOffset+replLen).matches("( *(\\+|-|∙|/|\\^|=|\\)).*)|")) { string = string + "_"; insertedDummyChar = true; } else if(s.substring(replOffset+replLen).matches(" .*")) { string = "_" + string; insertedDummyChar = true; } } else if(string.matches("\\(")) { if(replLen == 0 || replStr.equals("_")) { string = "(_)"; insertedDummyChar = true; } else { string = "(" + replStr + ")"; insertedBrackets = true; } } else if(string.matches("\\)")) return; // ignore that // situation: A = B, press DEL -> make it A = _ if(string.isEmpty() && replOffset > 0 && replLen == 1 && s.substring(replOffset - 1, replOffset).equals(" ") && !replStr.equals("_")) { string = "_"; insertedDummyChar = true; } setNewString(fb, s.substring(0, replOffset) + string + s.substring(replOffset + replLen)); if(insertedDummyChar) { int p = JMathTextField.this.getText().indexOf('_'); if(p >= 0) { JMathTextField.this.setCaretPosition(p); JMathTextField.this.moveCaretPosition(p + 1); } } else if(insertedBrackets) { // move just before the ')' if(JMathTextField.this.getCaretPosition() > 0) JMathTextField.this.setCaretPosition(JMathTextField.this.getCaretPosition() - 1); } } synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException { operatorTree = OTParser.parse(tempStr, null); JMathTextField.this.updateByOpTree(fb); } }); return d; }
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/scheduler/AbstractLinearExecutionJob.java b/ambari-server/src/main/java/org/apache/ambari/server/scheduler/AbstractLinearExecutionJob.java index 7570a6903..5fdd77e9d 100644 --- a/ambari-server/src/main/java/org/apache/ambari/server/scheduler/AbstractLinearExecutionJob.java +++ b/ambari-server/src/main/java/org/apache/ambari/server/scheduler/AbstractLinearExecutionJob.java @@ -1,114 +1,113 @@ /** * 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.ambari.server.scheduler; import org.apache.ambari.server.AmbariException; import org.quartz.DateBuilder; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobKey; import org.quartz.PersistJobDataAfterExecution; import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import static org.quartz.DateBuilder.futureDate; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import static org.quartz.TriggerBuilder.newTrigger; /** * Job that knows how to get the job name and group out of the JobDataMap using * pre-defined keys (constants) and contains code to schedule the identified job. * This abstract Job's implementation of execute() delegates to an abstract * template method "doWork()" (where the extending Job class's real work goes) * and then it schedules the follow-up job. */ @PersistJobDataAfterExecution @DisallowConcurrentExecution public abstract class AbstractLinearExecutionJob implements ExecutionJob { private static Logger LOG = LoggerFactory.getLogger(AbstractLinearExecutionJob.class); protected ExecutionScheduleManager executionScheduleManager; public AbstractLinearExecutionJob(ExecutionScheduleManager executionScheduleManager) { this.executionScheduleManager = executionScheduleManager; } /** * Do the actual work of the fired job. * @throws AmbariException * @param properties */ protected abstract void doWork(Map<String, Object> properties) throws AmbariException; /** * Get the next job id from context and create a trigger to fire the next * job. * @param context * @throws JobExecutionException */ @Override public void execute(JobExecutionContext context) throws JobExecutionException { JobKey jobKey = context.getJobDetail().getKey(); LOG.debug("Executing linear job: " + jobKey); if (!executionScheduleManager.continueOnMisfire(context)) { throw new JobExecutionException("Canceled execution based on misfire" + " toleration threshold, job: " + jobKey + ", scheduleTime = " + context.getScheduledFireTime()); } // Perform work and exit if failure reported try { doWork(context.getMergedJobDataMap().getWrappedMap()); } catch (AmbariException e) { LOG.error("Exception caught on job execution. Exiting linear chain...", e); throw new JobExecutionException(e); } LOG.debug("Finished linear job: " + jobKey); JobDataMap jobDataMap = context.getMergedJobDataMap(); String nextJobName = jobDataMap.getString(NEXT_EXECUTION_JOB_NAME_KEY); String nextJobGroup = jobDataMap.getString(NEXT_EXECUTION_JOB_GROUP_KEY); if (nextJobName == null || nextJobName.isEmpty()) { LOG.debug("End of linear job chain. Returning with success."); return; } - Integer separationSeconds = jobDataMap.getIntegerFromString( - (NEXT_EXECUTION_SEPARATION_SECONDS)); + int separationSeconds = jobDataMap.getIntValue((NEXT_EXECUTION_SEPARATION_SECONDS)); // Create trigger for next job execution Trigger trigger = newTrigger() .forJob(nextJobName, nextJobGroup) .withIdentity("TriggerForJob-" + nextJobName, LINEAR_EXECUTION_TRIGGER_GROUP) .withSchedule(simpleSchedule().withMisfireHandlingInstructionFireNow()) .startAt(futureDate(separationSeconds, DateBuilder.IntervalUnit.SECOND)) .build(); executionScheduleManager.scheduleJob(trigger); } }
true
true
public void execute(JobExecutionContext context) throws JobExecutionException { JobKey jobKey = context.getJobDetail().getKey(); LOG.debug("Executing linear job: " + jobKey); if (!executionScheduleManager.continueOnMisfire(context)) { throw new JobExecutionException("Canceled execution based on misfire" + " toleration threshold, job: " + jobKey + ", scheduleTime = " + context.getScheduledFireTime()); } // Perform work and exit if failure reported try { doWork(context.getMergedJobDataMap().getWrappedMap()); } catch (AmbariException e) { LOG.error("Exception caught on job execution. Exiting linear chain...", e); throw new JobExecutionException(e); } LOG.debug("Finished linear job: " + jobKey); JobDataMap jobDataMap = context.getMergedJobDataMap(); String nextJobName = jobDataMap.getString(NEXT_EXECUTION_JOB_NAME_KEY); String nextJobGroup = jobDataMap.getString(NEXT_EXECUTION_JOB_GROUP_KEY); if (nextJobName == null || nextJobName.isEmpty()) { LOG.debug("End of linear job chain. Returning with success."); return; } Integer separationSeconds = jobDataMap.getIntegerFromString( (NEXT_EXECUTION_SEPARATION_SECONDS)); // Create trigger for next job execution Trigger trigger = newTrigger() .forJob(nextJobName, nextJobGroup) .withIdentity("TriggerForJob-" + nextJobName, LINEAR_EXECUTION_TRIGGER_GROUP) .withSchedule(simpleSchedule().withMisfireHandlingInstructionFireNow()) .startAt(futureDate(separationSeconds, DateBuilder.IntervalUnit.SECOND)) .build(); executionScheduleManager.scheduleJob(trigger); }
public void execute(JobExecutionContext context) throws JobExecutionException { JobKey jobKey = context.getJobDetail().getKey(); LOG.debug("Executing linear job: " + jobKey); if (!executionScheduleManager.continueOnMisfire(context)) { throw new JobExecutionException("Canceled execution based on misfire" + " toleration threshold, job: " + jobKey + ", scheduleTime = " + context.getScheduledFireTime()); } // Perform work and exit if failure reported try { doWork(context.getMergedJobDataMap().getWrappedMap()); } catch (AmbariException e) { LOG.error("Exception caught on job execution. Exiting linear chain...", e); throw new JobExecutionException(e); } LOG.debug("Finished linear job: " + jobKey); JobDataMap jobDataMap = context.getMergedJobDataMap(); String nextJobName = jobDataMap.getString(NEXT_EXECUTION_JOB_NAME_KEY); String nextJobGroup = jobDataMap.getString(NEXT_EXECUTION_JOB_GROUP_KEY); if (nextJobName == null || nextJobName.isEmpty()) { LOG.debug("End of linear job chain. Returning with success."); return; } int separationSeconds = jobDataMap.getIntValue((NEXT_EXECUTION_SEPARATION_SECONDS)); // Create trigger for next job execution Trigger trigger = newTrigger() .forJob(nextJobName, nextJobGroup) .withIdentity("TriggerForJob-" + nextJobName, LINEAR_EXECUTION_TRIGGER_GROUP) .withSchedule(simpleSchedule().withMisfireHandlingInstructionFireNow()) .startAt(futureDate(separationSeconds, DateBuilder.IntervalUnit.SECOND)) .build(); executionScheduleManager.scheduleJob(trigger); }
diff --git a/src/com/android/browser/IntentHandler.java b/src/com/android/browser/IntentHandler.java index 8b3ff1e8..aac7e045 100644 --- a/src/com/android/browser/IntentHandler.java +++ b/src/com/android/browser/IntentHandler.java @@ -1,382 +1,382 @@ /* * 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.browser; import android.app.Activity; import android.app.SearchManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Browser; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Patterns; import com.android.browser.UI.ComboViews; import com.android.browser.search.SearchEngine; import com.android.common.Search; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Handle all browser related intents */ public class IntentHandler { // "source" parameter for Google search suggested by the browser final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; // "source" parameter for Google search from unknown source final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null); private Activity mActivity; private Controller mController; private TabControl mTabControl; private BrowserSettings mSettings; public IntentHandler(Activity browser, Controller controller) { mActivity = browser; mController = controller; mTabControl = mController.getTabControl(); mSettings = controller.getSettings(); } void onNewIntent(Intent intent) { Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mController.setActiveTab(current); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) { mController.bookmarksOrHistoryPicker(ComboViews.Bookmarks); return; } // In case the SearchDialog is open. ((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE)) .stopSearch(); if (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(mActivity, mController, intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } // If url is to view private data files, don't allow. Uri uri = intent.getData(); - if (uri != null && uri.getScheme().startsWith("file") && + if (uri != null && uri.getScheme().toLowerCase().startsWith("file") && uri.getPath().startsWith(mActivity.getDatabasePath("foo").getParent())) { return; } if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false) || urlData.isPreloaded()) { Tab t = mController.openTab(urlData); return; } /* * TODO: Don't allow javascript URIs * 0) If this is a javascript: URI, *always* open a new tab * 1) If the URL is already opened, switch to that tab * 2-phone) Reuse tab with same appId * 2-tablet) Open new tab */ final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (!TextUtils.isEmpty(urlData.mUrl) && urlData.mUrl.startsWith("javascript:")) { // Always open javascript: URIs in new tabs mController.openTab(urlData); return; } if (Intent.ACTION_VIEW.equals(action) && (appId != null) && appId.startsWith(mActivity.getPackageName())) { Tab appTab = mTabControl.getTabFromAppId(appId); if ((appTab != null) && (appTab == mController.getCurrentTab())) { mController.switchToTab(appTab); mController.loadUrlDataIn(appTab, urlData); return; } } if (Intent.ACTION_VIEW.equals(action) && !mActivity.getPackageName().equals(appId)) { if (!BrowserActivity.isTablet(mActivity) && !mSettings.allowAppTabs()) { Tab appTab = mTabControl.getTabFromAppId(appId); if (appTab != null) { mController.reuseTab(appTab, urlData); return; } } // No matching application tab, try to find a regular tab // with a matching url. Tab appTab = mTabControl.findTabWithUrl(urlData.mUrl); if (appTab != null) { // Transfer ownership appTab.setAppId(appId); if (current != appTab) { mController.switchToTab(appTab); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. Tab tab = mController.openTab(urlData); if (tab != null) { tab.setAppId(appId); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { tab.setCloseOnBack(true); } } } } else { if (!urlData.isEmpty() && urlData.mUrl.startsWith("about:debug")) { if ("about:debug.dom".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(false); } else if ("about:debug.dom.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(true); } else if ("about:debug.render".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(false); } else if ("about:debug.render.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(true); } else if ("about:debug.display".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDisplayTree(); } else if ("about:debug.nav".equals(urlData.mUrl)) { current.getWebView().debugDump(); } else { mSettings.toggleDebugSettings(); } return; } // Get rid of the subwindow if it exists mController.dismissSubWindow(current); // If the current Tab is being used as an application tab, // remove the association, since the new Intent means that it is // no longer associated with that application. current.setAppId(null); mController.loadUrlDataIn(current, urlData); } } } protected static UrlData getUrlDataFromIntent(Intent intent) { String url = ""; Map<String, String> headers = null; PreloadedTabControl preloaded = null; String preloadedSearchBoxQuery = null; if (intent != null && (intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { url = UrlUtils.smartUrlFilter(intent.getData()); if (url != null && url.startsWith("http")) { final Bundle pairs = intent .getBundleExtra(Browser.EXTRA_HEADERS); if (pairs != null && !pairs.isEmpty()) { Iterator<String> iter = pairs.keySet().iterator(); headers = new HashMap<String, String>(); while (iter.hasNext()) { String key = iter.next(); headers.put(key, pairs.getString(key)); } } } if (intent.hasExtra(PreloadRequestReceiver.EXTRA_PRELOAD_ID)) { String id = intent.getStringExtra(PreloadRequestReceiver.EXTRA_PRELOAD_ID); preloadedSearchBoxQuery = intent.getStringExtra( PreloadRequestReceiver.EXTRA_SEARCHBOX_SETQUERY); preloaded = Preloader.getInstance().getPreloadedTab(id); } } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); if (url != null) { // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. url = UrlUtils.fixUrl(url); url = UrlUtils.smartUrlFilter(url); String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; if (url.contains(searchSource)) { String source = null; final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { source = appData.getString(Search.SOURCE); } if (TextUtils.isEmpty(source)) { source = GOOGLE_SEARCH_SOURCE_UNKNOWN; } url = url.replace(searchSource, "&source=android-"+source+"&"); } } } } return new UrlData(url, headers, intent, preloaded, preloadedSearchBoxQuery); } /** * Launches the default web search activity with the query parameters if the given intent's data * are identified as plain search terms and not URLs/shortcuts. * @return true if the intent was handled and web search activity was launched, false if not. */ static boolean handleWebSearchIntent(Activity activity, Controller controller, Intent intent) { if (intent == null) return false; String url = null; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { Uri data = intent.getData(); if (data != null) url = data.toString(); } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); } return handleWebSearchRequest(activity, controller, url, intent.getBundleExtra(SearchManager.APP_DATA), intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } /** * Launches the default web search activity with the query parameters if the given url string * was identified as plain search terms and not URL/shortcut. * @return true if the request was handled and web search activity was launched, false if not. */ private static boolean handleWebSearchRequest(Activity activity, Controller controller, String inUrl, Bundle appData, String extraData) { if (inUrl == null) return false; // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. String url = UrlUtils.fixUrl(inUrl).trim(); if (TextUtils.isEmpty(url)) return false; // URLs are handled by the regular flow of control, so // return early. if (Patterns.WEB_URL.matcher(url).matches() || UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) { return false; } final ContentResolver cr = activity.getContentResolver(); final String newUrl = url; if (controller == null || controller.getTabControl() == null || controller.getTabControl().getCurrentWebView() == null || !controller.getTabControl().getCurrentWebView() .isPrivateBrowsingEnabled()) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... unused) { Browser.addSearchUrl(cr, newUrl); return null; } }.execute(); } SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine(); if (searchEngine == null) return false; searchEngine.startSearch(activity, url, appData, extraData); return true; } /** * A UrlData class to abstract how the content will be set to WebView. * This base class uses loadUrl to show the content. */ static class UrlData { final String mUrl; final Map<String, String> mHeaders; final PreloadedTabControl mPreloadedTab; final String mSearchBoxQueryToSubmit; UrlData(String url) { this.mUrl = url; this.mHeaders = null; this.mPreloadedTab = null; this.mSearchBoxQueryToSubmit = null; } UrlData(String url, Map<String, String> headers, Intent intent) { this(url, headers, intent, null, null); } UrlData(String url, Map<String, String> headers, Intent intent, PreloadedTabControl preloaded, String searchBoxQueryToSubmit) { this.mUrl = url; this.mHeaders = headers; this.mPreloadedTab = preloaded; this.mSearchBoxQueryToSubmit = searchBoxQueryToSubmit; } boolean isEmpty() { return (mUrl == null || mUrl.length() == 0); } boolean isPreloaded() { return mPreloadedTab != null; } PreloadedTabControl getPreloadedTab() { return mPreloadedTab; } String getSearchBoxQueryToSubmit() { return mSearchBoxQueryToSubmit; } } }
true
true
void onNewIntent(Intent intent) { Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mController.setActiveTab(current); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) { mController.bookmarksOrHistoryPicker(ComboViews.Bookmarks); return; } // In case the SearchDialog is open. ((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE)) .stopSearch(); if (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(mActivity, mController, intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } // If url is to view private data files, don't allow. Uri uri = intent.getData(); if (uri != null && uri.getScheme().startsWith("file") && uri.getPath().startsWith(mActivity.getDatabasePath("foo").getParent())) { return; } if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false) || urlData.isPreloaded()) { Tab t = mController.openTab(urlData); return; } /* * TODO: Don't allow javascript URIs * 0) If this is a javascript: URI, *always* open a new tab * 1) If the URL is already opened, switch to that tab * 2-phone) Reuse tab with same appId * 2-tablet) Open new tab */ final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (!TextUtils.isEmpty(urlData.mUrl) && urlData.mUrl.startsWith("javascript:")) { // Always open javascript: URIs in new tabs mController.openTab(urlData); return; } if (Intent.ACTION_VIEW.equals(action) && (appId != null) && appId.startsWith(mActivity.getPackageName())) { Tab appTab = mTabControl.getTabFromAppId(appId); if ((appTab != null) && (appTab == mController.getCurrentTab())) { mController.switchToTab(appTab); mController.loadUrlDataIn(appTab, urlData); return; } } if (Intent.ACTION_VIEW.equals(action) && !mActivity.getPackageName().equals(appId)) { if (!BrowserActivity.isTablet(mActivity) && !mSettings.allowAppTabs()) { Tab appTab = mTabControl.getTabFromAppId(appId); if (appTab != null) { mController.reuseTab(appTab, urlData); return; } } // No matching application tab, try to find a regular tab // with a matching url. Tab appTab = mTabControl.findTabWithUrl(urlData.mUrl); if (appTab != null) { // Transfer ownership appTab.setAppId(appId); if (current != appTab) { mController.switchToTab(appTab); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. Tab tab = mController.openTab(urlData); if (tab != null) { tab.setAppId(appId); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { tab.setCloseOnBack(true); } } } } else { if (!urlData.isEmpty() && urlData.mUrl.startsWith("about:debug")) { if ("about:debug.dom".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(false); } else if ("about:debug.dom.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(true); } else if ("about:debug.render".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(false); } else if ("about:debug.render.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(true); } else if ("about:debug.display".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDisplayTree(); } else if ("about:debug.nav".equals(urlData.mUrl)) { current.getWebView().debugDump(); } else { mSettings.toggleDebugSettings(); } return; } // Get rid of the subwindow if it exists mController.dismissSubWindow(current); // If the current Tab is being used as an application tab, // remove the association, since the new Intent means that it is // no longer associated with that application. current.setAppId(null); mController.loadUrlDataIn(current, urlData); } } }
void onNewIntent(Intent intent) { Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mController.setActiveTab(current); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(action)) { mController.bookmarksOrHistoryPicker(ComboViews.Bookmarks); return; } // In case the SearchDialog is open. ((SearchManager) mActivity.getSystemService(Context.SEARCH_SERVICE)) .stopSearch(); if (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(mActivity, mController, intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } // If url is to view private data files, don't allow. Uri uri = intent.getData(); if (uri != null && uri.getScheme().toLowerCase().startsWith("file") && uri.getPath().startsWith(mActivity.getDatabasePath("foo").getParent())) { return; } if (intent.getBooleanExtra(Browser.EXTRA_CREATE_NEW_TAB, false) || urlData.isPreloaded()) { Tab t = mController.openTab(urlData); return; } /* * TODO: Don't allow javascript URIs * 0) If this is a javascript: URI, *always* open a new tab * 1) If the URL is already opened, switch to that tab * 2-phone) Reuse tab with same appId * 2-tablet) Open new tab */ final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (!TextUtils.isEmpty(urlData.mUrl) && urlData.mUrl.startsWith("javascript:")) { // Always open javascript: URIs in new tabs mController.openTab(urlData); return; } if (Intent.ACTION_VIEW.equals(action) && (appId != null) && appId.startsWith(mActivity.getPackageName())) { Tab appTab = mTabControl.getTabFromAppId(appId); if ((appTab != null) && (appTab == mController.getCurrentTab())) { mController.switchToTab(appTab); mController.loadUrlDataIn(appTab, urlData); return; } } if (Intent.ACTION_VIEW.equals(action) && !mActivity.getPackageName().equals(appId)) { if (!BrowserActivity.isTablet(mActivity) && !mSettings.allowAppTabs()) { Tab appTab = mTabControl.getTabFromAppId(appId); if (appTab != null) { mController.reuseTab(appTab, urlData); return; } } // No matching application tab, try to find a regular tab // with a matching url. Tab appTab = mTabControl.findTabWithUrl(urlData.mUrl); if (appTab != null) { // Transfer ownership appTab.setAppId(appId); if (current != appTab) { mController.switchToTab(appTab); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. Tab tab = mController.openTab(urlData); if (tab != null) { tab.setAppId(appId); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { tab.setCloseOnBack(true); } } } } else { if (!urlData.isEmpty() && urlData.mUrl.startsWith("about:debug")) { if ("about:debug.dom".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(false); } else if ("about:debug.dom.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDomTree(true); } else if ("about:debug.render".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(false); } else if ("about:debug.render.file".equals(urlData.mUrl)) { current.getWebViewClassic().dumpRenderTree(true); } else if ("about:debug.display".equals(urlData.mUrl)) { current.getWebViewClassic().dumpDisplayTree(); } else if ("about:debug.nav".equals(urlData.mUrl)) { current.getWebView().debugDump(); } else { mSettings.toggleDebugSettings(); } return; } // Get rid of the subwindow if it exists mController.dismissSubWindow(current); // If the current Tab is being used as an application tab, // remove the association, since the new Intent means that it is // no longer associated with that application. current.setAppId(null); mController.loadUrlDataIn(current, urlData); } } }
diff --git a/core/src/main/java/hudson/security/HudsonFilter.java b/core/src/main/java/hudson/security/HudsonFilter.java index 1b3c3cd37..cadcbf386 100644 --- a/core/src/main/java/hudson/security/HudsonFilter.java +++ b/core/src/main/java/hudson/security/HudsonFilter.java @@ -1,118 +1,119 @@ package hudson.security; import javax.servlet.*; import java.io.IOException; import org.acegisecurity.AuthenticationManager; import org.acegisecurity.ui.rememberme.RememberMeServices; import org.acegisecurity.userdetails.UserDetailsService; /** * {@link Filter} that Hudson uses to implement security support. * * <p> * This is the instance the servlet container creates, but * internally this just acts as a proxy to the real {@link Filter}, * created by {@link SecurityRealm#createFilter(FilterConfig)}. * * @author Kohsuke Kawaguchi * @since 1.160 */ public class HudsonFilter implements Filter { /** * The SecurityRealm specific filter. */ private volatile Filter filter; /** * The {@link #init(FilterConfig)} may be called before the Hudson instance is up (which is * required for initialization of the filter). So we store the * filterConfig for later lazy-initialization of the filter. */ private FilterConfig filterConfig; /** * {@link AuthenticationManager} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().manager}, * so use that instead. */ public static final AuthenticationManagerProxy AUTHENTICATION_MANAGER = new AuthenticationManagerProxy(); /** * {@link UserDetailsService} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().userDetails}, * so use that instead. */ public static final UserDetailsServiceProxy USER_DETAILS_SERVICE_PROXY = new UserDetailsServiceProxy(); /** * {@link RememberMeServices} proxy so that the acegi filter chain can stay the same * even when security setting is reconfigured. * * @deprecated in 1.271. * This proxy always delegate to {@code Hudson.getInstance().getSecurityRealm().getSecurityComponents().rememberMe}, * so use that instead. */ public static final RememberMeServicesProxy REMEMBER_ME_SERVICES_PROXY = new RememberMeServicesProxy(); public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; // this is how we make us available to the rest of Hudson. filterConfig.getServletContext().setAttribute(HudsonFilter.class.getName(),this); } /** * Gets the {@link HudsonFilter} created for the given {@link ServletContext}. */ public static HudsonFilter get(ServletContext context) { return (HudsonFilter)context.getAttribute(HudsonFilter.class.getName()); } /** * Reset the proxies and filter for a change in {@link SecurityRealm}. */ public void reset(SecurityRealm securityRealm) throws ServletException { if (securityRealm != null) { SecurityRealm.SecurityComponents sc = securityRealm.getSecurityComponents(); AUTHENTICATION_MANAGER.setDelegate(sc.manager); USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails); REMEMBER_ME_SERVICES_PROXY.setDelegate(sc.rememberMe); // make sure this.filter is always a valid filter. Filter oldf = this.filter; Filter newf = securityRealm.createFilter(this.filterConfig); newf.init(this.filterConfig); this.filter = newf; - oldf.destroy(); + if(oldf!=null) + oldf.destroy(); } else { // no security related filter needed. AUTHENTICATION_MANAGER.setDelegate(null); USER_DETAILS_SERVICE_PROXY.setDelegate(null); REMEMBER_ME_SERVICES_PROXY.setDelegate(null); filter = null; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // to deal with concurrency, we need to capture the object. Filter f = filter; if(f==null) { // Hudson is starting up. chain.doFilter(request,response); } else { f.doFilter(request,response,chain); } } public void destroy() { // the filter can be null if the filter is not initialized yet. if(filter != null) filter.destroy(); } }
true
true
public void reset(SecurityRealm securityRealm) throws ServletException { if (securityRealm != null) { SecurityRealm.SecurityComponents sc = securityRealm.getSecurityComponents(); AUTHENTICATION_MANAGER.setDelegate(sc.manager); USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails); REMEMBER_ME_SERVICES_PROXY.setDelegate(sc.rememberMe); // make sure this.filter is always a valid filter. Filter oldf = this.filter; Filter newf = securityRealm.createFilter(this.filterConfig); newf.init(this.filterConfig); this.filter = newf; oldf.destroy(); } else { // no security related filter needed. AUTHENTICATION_MANAGER.setDelegate(null); USER_DETAILS_SERVICE_PROXY.setDelegate(null); REMEMBER_ME_SERVICES_PROXY.setDelegate(null); filter = null; } }
public void reset(SecurityRealm securityRealm) throws ServletException { if (securityRealm != null) { SecurityRealm.SecurityComponents sc = securityRealm.getSecurityComponents(); AUTHENTICATION_MANAGER.setDelegate(sc.manager); USER_DETAILS_SERVICE_PROXY.setDelegate(sc.userDetails); REMEMBER_ME_SERVICES_PROXY.setDelegate(sc.rememberMe); // make sure this.filter is always a valid filter. Filter oldf = this.filter; Filter newf = securityRealm.createFilter(this.filterConfig); newf.init(this.filterConfig); this.filter = newf; if(oldf!=null) oldf.destroy(); } else { // no security related filter needed. AUTHENTICATION_MANAGER.setDelegate(null); USER_DETAILS_SERVICE_PROXY.setDelegate(null); REMEMBER_ME_SERVICES_PROXY.setDelegate(null); filter = null; } }
diff --git a/src/gamedev/objects/Dinosaur.java b/src/gamedev/objects/Dinosaur.java index b3304a7..385a7b2 100644 --- a/src/gamedev/objects/Dinosaur.java +++ b/src/gamedev/objects/Dinosaur.java @@ -1,218 +1,222 @@ package gamedev.objects; import gamedev.game.Direction; import gamedev.game.ResourcesManager; import java.util.Random; import org.andengine.engine.handler.physics.PhysicsHandler; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsFactory; import org.andengine.extension.physics.box2d.util.Vector2Pool; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; public class Dinosaur extends AnimatedSprite { public final static long[] ANIMATION_DURATION = { 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120}; public final static int FRAMES_PER_ANIMATION = 13; public final static int TILES_PER_LINE = 26; public Body body; public PhysicsHandler physicsHandler; protected ResourcesManager resourcesManager; protected DinosaurState currentState; protected float animationElapsedTime = 0; protected float animationTime = 10; protected float attackElapsedTime = 0; protected float attackBlockTime = 2; protected boolean firstAttack = false; protected int direction = Direction.WEST; protected int life = 100; protected float velocity = 2f; protected float factorRunning = 2f; // Current vector to move to protected Vector2 moveTo; protected float radius = 5; public enum DinosaurState { WALKING, RUNNING, BEEN_HIT, TIPPING_OVER, ATTACK, ROARING, PAUSED, LOOKING, CHASE_PLAYER, } public Dinosaur(float pX, float pY) { super(pX, pY, ResourcesManager.getInstance().dinosaurGreenRegion, ResourcesManager.getInstance().vbom); this.resourcesManager = ResourcesManager.getInstance(); this.createPhysic(); this.direction = Direction.getRandomDirection(); this.setState(DinosaurState.LOOKING); // Scale it up, so it has normal size. this.mScaleX = this.mScaleX * 2; this.mScaleY = this.mScaleY * 2; } public void setDirection(int direction) { this.direction = direction; } public void setState(DinosaurState state) { this.currentState = state; // Display the correct animation based on the state and direction int rowIndex = 0; boolean animate = true; switch (state) { case WALKING: rowIndex = 0; break; case TIPPING_OVER: rowIndex = 4; this.body.setLinearVelocity(0, 0); animate = false; break; case RUNNING: case CHASE_PLAYER: rowIndex = 8; break; case ROARING: rowIndex = 12; this.body.setLinearVelocity(0, 0); break; case PAUSED: rowIndex = 16; this.body.setLinearVelocity(0, 0); break; case LOOKING: rowIndex = 20; this.body.setLinearVelocity(0, 0); break; case BEEN_HIT: rowIndex = 24; this.body.setLinearVelocity(0, 0); animate = false; break; case ATTACK: rowIndex = 28; this.body.setLinearVelocity(0, 0); break; } int startTile = rowIndex*TILES_PER_LINE + this.direction*FRAMES_PER_ANIMATION; this.animate(ANIMATION_DURATION, startTile, startTile+12, animate); } /** * Set the position where the dinosaur should move * @param x * @param y * @param state WALKING|RUNNING|CHASE_PLAYER */ public void moveTo(float x, float y, DinosaurState state) { // Store the point where to go this.moveTo = new Vector2(x, y); // Calculate the direction for the sprite animation int direction = Direction.getDirectionFromVectors(this.body.getPosition(), this.moveTo); // Calculate the slope between source/destination Vector2 v = Vector2Pool.obtain(x - this.body.getPosition().x, y - this.body.getPosition().y); v.nor(); if (state == DinosaurState.WALKING) { this.body.setLinearVelocity(v.x * this.velocity, v.y * this.velocity); } else { this.body.setLinearVelocity(v.x * this.velocity * this.factorRunning, v.y * this.velocity * this.factorRunning); } Vector2Pool.recycle(v); if (state == DinosaurState.CHASE_PLAYER && direction == this.direction) { } else { this.setDirection(direction); this.setState(state); } } @Override protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); // Check if the dino should chase our player Vector2 playerPos = this.resourcesManager.player.body.getPosition(); float distance = this.body.getPosition().dst(playerPos); if (distance < 0.5) { if (this.currentState != DinosaurState.ATTACK) this.setState(DinosaurState.ATTACK); // TODO Damage should be based on distance... this.attackElapsedTime += pSecondsElapsed; - if (!firstAttack || this.attackElapsedTime > this.attackBlockTime) { + if (!firstAttack) { + this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); this.firstAttack = true; - this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); - this.attackElapsedTime = 0; + } else { + if (this.attackElapsedTime > this.attackBlockTime) { + this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); + this.attackElapsedTime = 0; + } } return; } else if (distance < this.radius) { this.moveTo(playerPos.x, playerPos.y, DinosaurState.CHASE_PLAYER); return; } else { if (this.currentState == DinosaurState.CHASE_PLAYER) { // Force calculation of new state this.animationTime = 0; } } // If walking or running, check if we reached our goal if (this.currentState == DinosaurState.WALKING || this.currentState == DinosaurState.RUNNING) { if (Math.abs(this.body.getPosition().dst(this.moveTo)) < 5) { // Stop dino and force to calculate a new state this.body.setLinearVelocity(0, 0); this.animationTime = 0; } } // Set a random state after a random time. If the state is walking or running, set a random position where the dino walks. this.animationElapsedTime += pSecondsElapsed; if (this.animationElapsedTime > this.animationTime) { this.animationElapsedTime = 0; Random r = new Random(); // Set a random animation time [10...20] for the next animation seconds this.animationTime = 10 + (r.nextFloat() * 10 + 1); // Pick a random state, exclude some states DinosaurState randomState = this.getRandomState(); // If the state is walking, calculate a new random position if (randomState == DinosaurState.WALKING || randomState == DinosaurState.RUNNING) { // The new Position should be in Range [-1000...1000] from the current position float rX = this.body.getPosition().x + (-1000 + (r.nextFloat() * 2000 + 1)); float rY = this.body.getPosition().y + (-1000 + (r.nextFloat() * 2000 + 1)); this.moveTo(rX, rY, randomState); } else { this.setState(randomState); } } } protected void createPhysic() { this.body = PhysicsFactory.createBoxBody(this.resourcesManager.physicsWorld, this, BodyType.KinematicBody, PhysicsFactory.createFixtureDef(0, 0, 0)); this.resourcesManager.physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, this.body, true, true)); } private DinosaurState getRandomState() { Random r = new Random(); DinosaurState randomState = DinosaurState.values()[r.nextInt(7)]; while (randomState == DinosaurState.ATTACK || randomState == DinosaurState.BEEN_HIT || randomState == DinosaurState.TIPPING_OVER || randomState == DinosaurState.CHASE_PLAYER) { randomState = DinosaurState.values()[r.nextInt(7)]; } return randomState; } }
false
true
protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); // Check if the dino should chase our player Vector2 playerPos = this.resourcesManager.player.body.getPosition(); float distance = this.body.getPosition().dst(playerPos); if (distance < 0.5) { if (this.currentState != DinosaurState.ATTACK) this.setState(DinosaurState.ATTACK); // TODO Damage should be based on distance... this.attackElapsedTime += pSecondsElapsed; if (!firstAttack || this.attackElapsedTime > this.attackBlockTime) { this.firstAttack = true; this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); this.attackElapsedTime = 0; } return; } else if (distance < this.radius) { this.moveTo(playerPos.x, playerPos.y, DinosaurState.CHASE_PLAYER); return; } else { if (this.currentState == DinosaurState.CHASE_PLAYER) { // Force calculation of new state this.animationTime = 0; } } // If walking or running, check if we reached our goal if (this.currentState == DinosaurState.WALKING || this.currentState == DinosaurState.RUNNING) { if (Math.abs(this.body.getPosition().dst(this.moveTo)) < 5) { // Stop dino and force to calculate a new state this.body.setLinearVelocity(0, 0); this.animationTime = 0; } } // Set a random state after a random time. If the state is walking or running, set a random position where the dino walks. this.animationElapsedTime += pSecondsElapsed; if (this.animationElapsedTime > this.animationTime) { this.animationElapsedTime = 0; Random r = new Random(); // Set a random animation time [10...20] for the next animation seconds this.animationTime = 10 + (r.nextFloat() * 10 + 1); // Pick a random state, exclude some states DinosaurState randomState = this.getRandomState(); // If the state is walking, calculate a new random position if (randomState == DinosaurState.WALKING || randomState == DinosaurState.RUNNING) { // The new Position should be in Range [-1000...1000] from the current position float rX = this.body.getPosition().x + (-1000 + (r.nextFloat() * 2000 + 1)); float rY = this.body.getPosition().y + (-1000 + (r.nextFloat() * 2000 + 1)); this.moveTo(rX, rY, randomState); } else { this.setState(randomState); } } }
protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); // Check if the dino should chase our player Vector2 playerPos = this.resourcesManager.player.body.getPosition(); float distance = this.body.getPosition().dst(playerPos); if (distance < 0.5) { if (this.currentState != DinosaurState.ATTACK) this.setState(DinosaurState.ATTACK); // TODO Damage should be based on distance... this.attackElapsedTime += pSecondsElapsed; if (!firstAttack) { this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); this.firstAttack = true; } else { if (this.attackElapsedTime > this.attackBlockTime) { this.resourcesManager.player.setLife(this.resourcesManager.player.getLife() - 10); this.attackElapsedTime = 0; } } return; } else if (distance < this.radius) { this.moveTo(playerPos.x, playerPos.y, DinosaurState.CHASE_PLAYER); return; } else { if (this.currentState == DinosaurState.CHASE_PLAYER) { // Force calculation of new state this.animationTime = 0; } } // If walking or running, check if we reached our goal if (this.currentState == DinosaurState.WALKING || this.currentState == DinosaurState.RUNNING) { if (Math.abs(this.body.getPosition().dst(this.moveTo)) < 5) { // Stop dino and force to calculate a new state this.body.setLinearVelocity(0, 0); this.animationTime = 0; } } // Set a random state after a random time. If the state is walking or running, set a random position where the dino walks. this.animationElapsedTime += pSecondsElapsed; if (this.animationElapsedTime > this.animationTime) { this.animationElapsedTime = 0; Random r = new Random(); // Set a random animation time [10...20] for the next animation seconds this.animationTime = 10 + (r.nextFloat() * 10 + 1); // Pick a random state, exclude some states DinosaurState randomState = this.getRandomState(); // If the state is walking, calculate a new random position if (randomState == DinosaurState.WALKING || randomState == DinosaurState.RUNNING) { // The new Position should be in Range [-1000...1000] from the current position float rX = this.body.getPosition().x + (-1000 + (r.nextFloat() * 2000 + 1)); float rY = this.body.getPosition().y + (-1000 + (r.nextFloat() * 2000 + 1)); this.moveTo(rX, rY, randomState); } else { this.setState(randomState); } } }
diff --git a/src/com/ikkerens/worldedit/commands/ExpandCommand.java b/src/com/ikkerens/worldedit/commands/ExpandCommand.java index 3652f70..904059b 100644 --- a/src/com/ikkerens/worldedit/commands/ExpandCommand.java +++ b/src/com/ikkerens/worldedit/commands/ExpandCommand.java @@ -1,119 +1,119 @@ package com.ikkerens.worldedit.commands; import com.ikkerens.worldedit.Util; import com.ikkerens.worldedit.WorldEditPlugin; import com.ikkerens.worldedit.handlers.AbstractCommand; import com.ikkerens.worldedit.model.Selection; import com.ikkerens.worldedit.model.events.SelectionCommandEvent; import com.ikkerens.worldedit.model.wand.Direction; import com.mbserver.api.game.Location; import com.mbserver.api.game.Player; public class ExpandCommand extends AbstractCommand< WorldEditPlugin > { public ExpandCommand( final WorldEditPlugin plugin ) { super( plugin ); } @Override protected void execute( final String label, final Player player, final String[] args ) { if ( args.length != 2 ) { player.sendMessage( "Usage: /" + label + " <amount> <direction>" ); return; } this.getPlugin(); final Selection sel = WorldEditPlugin.getSession( player ).getSelection(); if ( sel.isValid() ) { Location lowest, highest; - if ( args[ 0 ].equalsIgnoreCase( "vert" ) ) { + if ( args[ 0 ].equalsIgnoreCase( "/vert" ) ) { final VerticalExpansionSelectionEvent event = new VerticalExpansionSelectionEvent( player ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); sel.setPositions( Util.newLocation( sel.getWorld(), lowest.getX(), 0, highest.getZ() ), Util.newLocation( sel.getWorld(), highest.getX(), 127, highest.getZ() ) ); sel.inform(); } else return; } else { int amount; try { amount = Integer.parseInt( args[ 0 ] ); } catch ( final NumberFormatException e ) { player.sendMessage( "That amount is invalid." ); return; } - if ( label.equalsIgnoreCase( "shrink" ) ) + if ( label.equalsIgnoreCase( "/shrink" ) ) amount *= -1; Direction dir; try { dir = Direction.valueOf( args[ 1 ].toUpperCase() ); } catch ( final IllegalArgumentException e ) { player.sendMessage( "That direction is invalid." ); return; } final ExpandSelectionCommandEvent event = new ExpandSelectionCommandEvent( player, dir, amount ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); switch ( dir ) { case SOUTH: case UP: case EAST: highest = dir.addToLocation( highest, amount ); break; case NORTH: case DOWN: case WEST: lowest = dir.addToLocation( lowest, amount ); break; } } else return; } sel.setPositions( lowest, highest ); sel.inform(); } else player.sendMessage( NEED_SELECTION ); } public static class ExpandSelectionCommandEvent extends SelectionCommandEvent { private final Direction direction; private final int amount; public ExpandSelectionCommandEvent( final Player player, final Direction direction, final int amount ) { super( player ); this.direction = direction; this.amount = amount; } public Direction getDirection() { return this.direction; } public int getAmount() { return this.amount; } } public static class VerticalExpansionSelectionEvent extends SelectionCommandEvent { public VerticalExpansionSelectionEvent( final Player player ) { super( player ); } } }
false
true
protected void execute( final String label, final Player player, final String[] args ) { if ( args.length != 2 ) { player.sendMessage( "Usage: /" + label + " <amount> <direction>" ); return; } this.getPlugin(); final Selection sel = WorldEditPlugin.getSession( player ).getSelection(); if ( sel.isValid() ) { Location lowest, highest; if ( args[ 0 ].equalsIgnoreCase( "vert" ) ) { final VerticalExpansionSelectionEvent event = new VerticalExpansionSelectionEvent( player ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); sel.setPositions( Util.newLocation( sel.getWorld(), lowest.getX(), 0, highest.getZ() ), Util.newLocation( sel.getWorld(), highest.getX(), 127, highest.getZ() ) ); sel.inform(); } else return; } else { int amount; try { amount = Integer.parseInt( args[ 0 ] ); } catch ( final NumberFormatException e ) { player.sendMessage( "That amount is invalid." ); return; } if ( label.equalsIgnoreCase( "shrink" ) ) amount *= -1; Direction dir; try { dir = Direction.valueOf( args[ 1 ].toUpperCase() ); } catch ( final IllegalArgumentException e ) { player.sendMessage( "That direction is invalid." ); return; } final ExpandSelectionCommandEvent event = new ExpandSelectionCommandEvent( player, dir, amount ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); switch ( dir ) { case SOUTH: case UP: case EAST: highest = dir.addToLocation( highest, amount ); break; case NORTH: case DOWN: case WEST: lowest = dir.addToLocation( lowest, amount ); break; } } else return; } sel.setPositions( lowest, highest ); sel.inform(); } else player.sendMessage( NEED_SELECTION ); }
protected void execute( final String label, final Player player, final String[] args ) { if ( args.length != 2 ) { player.sendMessage( "Usage: /" + label + " <amount> <direction>" ); return; } this.getPlugin(); final Selection sel = WorldEditPlugin.getSession( player ).getSelection(); if ( sel.isValid() ) { Location lowest, highest; if ( args[ 0 ].equalsIgnoreCase( "/vert" ) ) { final VerticalExpansionSelectionEvent event = new VerticalExpansionSelectionEvent( player ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); sel.setPositions( Util.newLocation( sel.getWorld(), lowest.getX(), 0, highest.getZ() ), Util.newLocation( sel.getWorld(), highest.getX(), 127, highest.getZ() ) ); sel.inform(); } else return; } else { int amount; try { amount = Integer.parseInt( args[ 0 ] ); } catch ( final NumberFormatException e ) { player.sendMessage( "That amount is invalid." ); return; } if ( label.equalsIgnoreCase( "/shrink" ) ) amount *= -1; Direction dir; try { dir = Direction.valueOf( args[ 1 ].toUpperCase() ); } catch ( final IllegalArgumentException e ) { player.sendMessage( "That direction is invalid." ); return; } final ExpandSelectionCommandEvent event = new ExpandSelectionCommandEvent( player, dir, amount ); this.getPlugin().getPluginManager().triggerEvent( event ); if ( !event.isCancelled() ) { lowest = sel.getMinimumPosition(); highest = sel.getMaximumPosition(); switch ( dir ) { case SOUTH: case UP: case EAST: highest = dir.addToLocation( highest, amount ); break; case NORTH: case DOWN: case WEST: lowest = dir.addToLocation( lowest, amount ); break; } } else return; } sel.setPositions( lowest, highest ); sel.inform(); } else player.sendMessage( NEED_SELECTION ); }
diff --git a/sonar-server/src/main/java/org/sonar/server/plugins/StaticResourcesServlet.java b/sonar-server/src/main/java/org/sonar/server/plugins/StaticResourcesServlet.java index 5b5366a51c..c86cc6b64f 100644 --- a/sonar-server/src/main/java/org/sonar/server/plugins/StaticResourcesServlet.java +++ b/sonar-server/src/main/java/org/sonar/server/plugins/StaticResourcesServlet.java @@ -1,66 +1,69 @@ package org.sonar.server.plugins; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.platform.Platform; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class StaticResourcesServlet extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(StaticResourcesServlet.class); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pluginKey = getPluginKey(request); String resource = getResourcePath(request); PluginClassLoaders pluginClassLoaders = Platform.getInstance().getContainer().getComponent(PluginClassLoaders.class); ClassLoader classLoader = pluginClassLoaders.getClassLoader(pluginKey); if (classLoader == null) { LOG.error("Plugin not found: " + pluginKey); + response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } InputStream in = null; OutputStream out = null; try { in = classLoader.getResourceAsStream(resource); if (in != null) { out = response.getOutputStream(); IOUtils.copy(in, out); } else { LOG.error("Unable to find resource '" + resource + "' in plugin '" + pluginKey + "'"); + response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { LOG.error("Unable to load static resource '" + resource + "' from plugin '" + pluginKey + "'", e); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } /** * @return part of request URL after servlet path */ protected String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); } protected String getPluginKey(HttpServletRequest request) { return StringUtils.substringBefore(getPluginKeyAndResourcePath(request), "/"); } protected String getResourcePath(HttpServletRequest request) { return "/static/" + StringUtils.substringAfter(getPluginKeyAndResourcePath(request), "/"); } }
false
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pluginKey = getPluginKey(request); String resource = getResourcePath(request); PluginClassLoaders pluginClassLoaders = Platform.getInstance().getContainer().getComponent(PluginClassLoaders.class); ClassLoader classLoader = pluginClassLoaders.getClassLoader(pluginKey); if (classLoader == null) { LOG.error("Plugin not found: " + pluginKey); return; } InputStream in = null; OutputStream out = null; try { in = classLoader.getResourceAsStream(resource); if (in != null) { out = response.getOutputStream(); IOUtils.copy(in, out); } else { LOG.error("Unable to find resource '" + resource + "' in plugin '" + pluginKey + "'"); } } catch (Exception e) { LOG.error("Unable to load static resource '" + resource + "' from plugin '" + pluginKey + "'", e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pluginKey = getPluginKey(request); String resource = getResourcePath(request); PluginClassLoaders pluginClassLoaders = Platform.getInstance().getContainer().getComponent(PluginClassLoaders.class); ClassLoader classLoader = pluginClassLoaders.getClassLoader(pluginKey); if (classLoader == null) { LOG.error("Plugin not found: " + pluginKey); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } InputStream in = null; OutputStream out = null; try { in = classLoader.getResourceAsStream(resource); if (in != null) { out = response.getOutputStream(); IOUtils.copy(in, out); } else { LOG.error("Unable to find resource '" + resource + "' in plugin '" + pluginKey + "'"); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { LOG.error("Unable to load static resource '" + resource + "' from plugin '" + pluginKey + "'", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
diff --git a/java/src/org/exist/messaging/xquery/ListReceivers.java b/java/src/org/exist/messaging/xquery/ListReceivers.java index 3f5e56b..979b248 100644 --- a/java/src/org/exist/messaging/xquery/ListReceivers.java +++ b/java/src/org/exist/messaging/xquery/ListReceivers.java @@ -1,82 +1,82 @@ /* * eXist Open Source Native XML Database * Copyright (C) 2013 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.messaging.xquery; import org.exist.dom.QName; import org.exist.messaging.receive.ReceiversManager; import org.exist.messaging.shared.Constants; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.*; /** * Implementation of the jms:list() function. Provides information about the receivers. * * @author Dannes Wessels */ public class ListReceivers extends BasicFunction { public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("list", MessagingModule.NAMESPACE_URI, MessagingModule.PREFIX), "Retrieve sequence of reciever IDs", new SequenceType[]{ // no params }, new FunctionReturnSequenceType(Type.STRING, Cardinality.ZERO_OR_MORE, "Sequence of receiver IDs") ), }; public ListReceivers(XQueryContext context, FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // User must either be DBA or in the JMS group if (!context.getSubject().hasDbaRole() && !context.getSubject().hasGroup(Constants.JMS_GROUP)) { - String txt = String.format("Permission denied, user '%s' must be a DBA or be in group '%s'", Constants.JMS_GROUP, context.getSubject().getName()); + String txt = String.format("Permission denied, user '%s' must be a DBA or be in group '%s'", context.getSubject().getName(), Constants.JMS_GROUP); XPathException ex = new XPathException(this, txt); - LOG.error(txt, ex); + LOG.error(txt); throw ex; } // Get object that manages the receivers ReceiversManager manager = ReceiversManager.getInstance(); // Conten holfer results ValueSequence returnSequence = new ValueSequence(); // Collect IDs for (Integer id : manager.getIds()) { returnSequence.add(new IntegerValue(id)); } // Return IDs return returnSequence; } }
false
true
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // User must either be DBA or in the JMS group if (!context.getSubject().hasDbaRole() && !context.getSubject().hasGroup(Constants.JMS_GROUP)) { String txt = String.format("Permission denied, user '%s' must be a DBA or be in group '%s'", Constants.JMS_GROUP, context.getSubject().getName()); XPathException ex = new XPathException(this, txt); LOG.error(txt, ex); throw ex; } // Get object that manages the receivers ReceiversManager manager = ReceiversManager.getInstance(); // Conten holfer results ValueSequence returnSequence = new ValueSequence(); // Collect IDs for (Integer id : manager.getIds()) { returnSequence.add(new IntegerValue(id)); } // Return IDs return returnSequence; }
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // User must either be DBA or in the JMS group if (!context.getSubject().hasDbaRole() && !context.getSubject().hasGroup(Constants.JMS_GROUP)) { String txt = String.format("Permission denied, user '%s' must be a DBA or be in group '%s'", context.getSubject().getName(), Constants.JMS_GROUP); XPathException ex = new XPathException(this, txt); LOG.error(txt); throw ex; } // Get object that manages the receivers ReceiversManager manager = ReceiversManager.getInstance(); // Conten holfer results ValueSequence returnSequence = new ValueSequence(); // Collect IDs for (Integer id : manager.getIds()) { returnSequence.add(new IntegerValue(id)); } // Return IDs return returnSequence; }
diff --git a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenCheckoutLocationPage.java b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenCheckoutLocationPage.java index e840467..0e6e430 100644 --- a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenCheckoutLocationPage.java +++ b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/wizards/MavenCheckoutLocationPage.java @@ -1,424 +1,424 @@ /******************************************************************************* * Copyright (c) 2008-2010 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.m2e.core.wizards; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.apache.maven.model.Scm; import org.eclipse.m2e.core.internal.Messages; import org.eclipse.m2e.core.project.ProjectImportConfiguration; import org.eclipse.m2e.core.scm.ScmHandlerFactory; import org.eclipse.m2e.core.scm.ScmHandlerUi; import org.eclipse.m2e.core.scm.ScmTag; import org.eclipse.m2e.core.scm.ScmUrl; /** * @author Eugene Kuleshov */ public class MavenCheckoutLocationPage extends AbstractMavenWizardPage { String scmType; ScmUrl[] scmUrls; String scmParentUrl; Combo scmTypeCombo; Combo scmUrlCombo; Button scmUrlBrowseButton; Button headRevisionButton; Label revisionLabel; Text revisionText; Button revisionBrowseButton; private Button checkoutAllProjectsButton; protected MavenCheckoutLocationPage(ProjectImportConfiguration projectImportConfiguration) { super("MavenCheckoutLocationPage", projectImportConfiguration); setTitle(Messages.MavenCheckoutLocationPage_title); setDescription(Messages.MavenCheckoutLocationPage_description); } public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(5, false); gridLayout.verticalSpacing = 0; composite.setLayout(gridLayout); setControl(composite); SelectionAdapter selectionAdapter = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }; if(scmUrls == null || scmUrls.length < 2) { Label urlLabel = new Label(composite, SWT.NONE); - urlLabel.setLayoutData(new GridData()); urlLabel.setText(Messages.MavenCheckoutLocationPage_lblurl); scmTypeCombo = new Combo(composite, SWT.READ_ONLY); - scmTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); + GridData gd_scmTypeCombo = new GridData(SWT.FILL, SWT.CENTER, false, false); + gd_scmTypeCombo.widthHint = 80; + scmTypeCombo.setLayoutData(gd_scmTypeCombo); scmTypeCombo.setData("name", "mavenCheckoutLocation.typeCombo"); //$NON-NLS-1$ //$NON-NLS-2$ String[] types = ScmHandlerFactory.getTypes(); for(int i = 0; i < types.length; i++ ) { scmTypeCombo.add(types[i]); } scmTypeCombo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String newScmType = scmTypeCombo.getText(); if(!newScmType.equals(scmType)) { scmType = newScmType; scmUrlCombo.setText(""); //$NON-NLS-1$ updatePage(); } } }); if(scmUrls!=null && scmUrls.length == 1) { try { scmType = ScmUrl.getType(scmUrls[0].getUrl()); } catch(CoreException ex) { } } scmUrlCombo = new Combo(composite, SWT.NONE); scmUrlCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); scmUrlCombo.setData("name", "mavenCheckoutLocation.urlCombo"); //$NON-NLS-1$ //$NON-NLS-2$ scmUrlBrowseButton = new Button(composite, SWT.NONE); - scmUrlBrowseButton.setLayoutData(new GridData()); scmUrlBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnBrowse); } headRevisionButton = new Button(composite, SWT.CHECK); GridData headRevisionButtonData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1); headRevisionButtonData.verticalIndent = 5; headRevisionButton.setLayoutData(headRevisionButtonData); headRevisionButton.setText(Messages.MavenCheckoutLocationPage_btnHead); headRevisionButton.setSelection(true); headRevisionButton.addSelectionListener(selectionAdapter); revisionLabel = new Label(composite, SWT.RADIO); GridData revisionButtonData = new GridData(); revisionButtonData.horizontalIndent = 10; revisionLabel.setLayoutData(revisionButtonData); revisionLabel.setText(Messages.MavenCheckoutLocationPage_lblRevision); // revisionButton.addSelectionListener(selectionAdapter); revisionText = new Text(composite, SWT.BORDER); GridData revisionTextData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); revisionTextData.widthHint = 115; revisionTextData.verticalIndent = 3; revisionText.setLayoutData(revisionTextData); if(scmUrls != null) { ScmTag tag = scmUrls[0].getTag(); if(tag!=null) { headRevisionButton.setSelection(false); revisionText.setText(tag.getName()); } } revisionText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updatePage(); } }); revisionBrowseButton = new Button(composite, SWT.NONE); GridData gd_revisionBrowseButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_revisionBrowseButton.verticalIndent = 3; revisionBrowseButton.setLayoutData(gd_revisionBrowseButton); revisionBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnRevSelect); revisionBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String url = scmParentUrl; if(url==null) { return; } String scmType = scmTypeCombo.getText(); ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); String revision = handlerUi.selectRevision(getShell(), scmUrls[0], revisionText.getText()); if(revision!=null) { revisionText.setText(revision); headRevisionButton.setSelection(false); updatePage(); } } }); checkoutAllProjectsButton = new Button(composite, SWT.CHECK); GridData checkoutAllProjectsData = new GridData(SWT.LEFT, SWT.TOP, true, false, 5, 1); checkoutAllProjectsData.verticalIndent = 10; checkoutAllProjectsButton.setLayoutData(checkoutAllProjectsData); checkoutAllProjectsButton.setText(Messages.MavenCheckoutLocationPage_btnCheckout); checkoutAllProjectsButton.setSelection(true); checkoutAllProjectsButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }); GridData advancedSettingsData = new GridData(SWT.FILL, SWT.TOP, true, false, 5, 1); advancedSettingsData.verticalIndent = 10; createAdvancedSettings(composite, advancedSettingsData); if(scmUrls!=null && scmUrls.length == 1) { scmTypeCombo.setText(scmType == null ? "" : scmType); //$NON-NLS-1$ scmUrlCombo.setText(scmUrls[0].getProviderUrl()); } if(scmUrls == null || scmUrls.length < 2) { scmUrlBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); // XXX should use null if there is no scmUrl selected ScmUrl currentUrl = scmUrls==null || scmUrls.length==0 ? new ScmUrl("scm:" + scmType + ":") : scmUrls[0]; //$NON-NLS-1$ //$NON-NLS-2$ ScmUrl scmUrl = handlerUi.selectUrl(getShell(), currentUrl); if(scmUrl!=null) { scmUrlCombo.setText(scmUrl.getProviderUrl()); if(scmUrls==null) { scmUrls = new ScmUrl[1]; } scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } } }); scmUrlCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { final String url = scmUrlCombo.getText(); if(url.startsWith("scm:")) { //$NON-NLS-1$ try { final String type = ScmUrl.getType(url); scmTypeCombo.setText(type); scmType = type; Display.getDefault().asyncExec(new Runnable() { public void run() { scmUrlCombo.setText(url.substring(type.length() + 5)); } }); } catch(CoreException ex) { } return; } if(scmUrls==null) { scmUrls = new ScmUrl[1]; } ScmUrl scmUrl = new ScmUrl("scm:" + scmType + ":" + url); //$NON-NLS-1$ //$NON-NLS-2$ scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } }); } updatePage(); } /* (non-Javadoc) * @see org.eclipse.m2e.wizards.AbstractMavenWizardPage#setVisible(boolean) */ public void setVisible(boolean visible) { super.setVisible(visible); if(dialogSettings!=null && scmUrlCombo!=null) { String[] items = dialogSettings.getArray("scmUrl"); //$NON-NLS-1$ if(items != null) { String text = scmUrlCombo.getText(); scmUrlCombo.setItems(items); if (text.length() > 0) { // setItems() clears the text input, so we need to restore it scmUrlCombo.setText(text); } } } } /* (non-Javadoc) * @see org.eclipse.m2e.wizards.AbstractMavenWizardPage#dispose() */ public void dispose() { if(dialogSettings != null && scmUrlCombo!=null) { Set<String> history = new LinkedHashSet<String>(MAX_HISTORY); String lastValue = scmUrlCombo.getText(); if ( lastValue!=null && lastValue.trim().length() > 0 ) { history.add("scm:" + scmType + ":" + lastValue); //$NON-NLS-1$ //$NON-NLS-2$ } String[] items = scmUrlCombo.getItems(); for(int j = 0; j < items.length && history.size() < MAX_HISTORY; j++ ) { history.add(items[j]); } dialogSettings.put("scmUrl", history.toArray(new String[history.size()])); //$NON-NLS-1$ } super.dispose(); } public IWizardContainer getContainer() { return super.getContainer(); } void updatePage() { boolean canSelectUrl = false ; boolean canSelectRevision = false; ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); if(handlerUi!=null) { canSelectUrl = handlerUi.canSelectUrl(); canSelectRevision = handlerUi.canSelectRevision(); } if(scmUrlBrowseButton!=null) { scmUrlBrowseButton.setEnabled(canSelectUrl); } revisionBrowseButton.setEnabled(canSelectRevision); boolean isHeadRevision = isHeadRevision(); revisionLabel.setEnabled(!isHeadRevision); revisionText.setEnabled(!isHeadRevision); setPageComplete(isPageValid()); } private boolean isPageValid() { setErrorMessage(null); if(scmUrls != null && scmUrls.length < 2) { if(scmType == null) { setErrorMessage(Messages.MavenCheckoutLocationPage_error_empty); return false; } } ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); if(scmUrls == null || scmUrls.length < 2) { if(scmUrls == null || scmUrls.length == 0) { setErrorMessage(Messages.MavenCheckoutLocationPage_error_empty_url); return false; } if(handlerUi!=null && !handlerUi.isValidUrl(scmUrls[0].getUrl())) { setErrorMessage(Messages.MavenCheckoutLocationPage_error_url_empty); return false; } } if(!isHeadRevision()) { String revision = revisionText.getText().trim(); if(revision.length()==0) { setErrorMessage(Messages.MavenCheckoutLocationPage_error_scm_empty); return false; } if(handlerUi!=null && !handlerUi.isValidRevision(null, revision)) { setErrorMessage(Messages.MavenCheckoutLocationPage_error_scm_invalid); return false; } } return true; } public void setParent(String parentUrl) { this.scmParentUrl = parentUrl; } public void setUrls(ScmUrl[] urls) { this.scmUrls = urls; } public ScmUrl[] getUrls() { return scmUrls; } public Scm[] getScms() { if(scmUrls==null) { return new Scm[0]; } String revision = getRevision(); Scm[] scms = new Scm[scmUrls.length]; for(int i = 0; i < scms.length; i++ ) { Scm scm = new Scm(); scm.setConnection(scmUrls[i].getUrl()); scm.setTag(revision); scms[i] = scm; } return scms; } public boolean isCheckoutAllProjects() { return checkoutAllProjectsButton.getSelection(); } public boolean isHeadRevision() { return headRevisionButton.getSelection(); } public String getRevision() { if(isHeadRevision()) { return "HEAD"; //$NON-NLS-1$ } return revisionText.getText().trim(); } public void addListener(final SelectionListener listener) { ModifyListener listenerProxy = new ModifyListener() { public void modifyText(ModifyEvent e) { Event event = new Event(); event.widget = e.widget; listener.widgetSelected(new SelectionEvent(event)); } }; scmUrlCombo.addModifyListener(listenerProxy); revisionText.addModifyListener(listenerProxy); headRevisionButton.addSelectionListener(listener); } }
false
true
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(5, false); gridLayout.verticalSpacing = 0; composite.setLayout(gridLayout); setControl(composite); SelectionAdapter selectionAdapter = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }; if(scmUrls == null || scmUrls.length < 2) { Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setLayoutData(new GridData()); urlLabel.setText(Messages.MavenCheckoutLocationPage_lblurl); scmTypeCombo = new Combo(composite, SWT.READ_ONLY); scmTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); scmTypeCombo.setData("name", "mavenCheckoutLocation.typeCombo"); //$NON-NLS-1$ //$NON-NLS-2$ String[] types = ScmHandlerFactory.getTypes(); for(int i = 0; i < types.length; i++ ) { scmTypeCombo.add(types[i]); } scmTypeCombo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String newScmType = scmTypeCombo.getText(); if(!newScmType.equals(scmType)) { scmType = newScmType; scmUrlCombo.setText(""); //$NON-NLS-1$ updatePage(); } } }); if(scmUrls!=null && scmUrls.length == 1) { try { scmType = ScmUrl.getType(scmUrls[0].getUrl()); } catch(CoreException ex) { } } scmUrlCombo = new Combo(composite, SWT.NONE); scmUrlCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); scmUrlCombo.setData("name", "mavenCheckoutLocation.urlCombo"); //$NON-NLS-1$ //$NON-NLS-2$ scmUrlBrowseButton = new Button(composite, SWT.NONE); scmUrlBrowseButton.setLayoutData(new GridData()); scmUrlBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnBrowse); } headRevisionButton = new Button(composite, SWT.CHECK); GridData headRevisionButtonData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1); headRevisionButtonData.verticalIndent = 5; headRevisionButton.setLayoutData(headRevisionButtonData); headRevisionButton.setText(Messages.MavenCheckoutLocationPage_btnHead); headRevisionButton.setSelection(true); headRevisionButton.addSelectionListener(selectionAdapter); revisionLabel = new Label(composite, SWT.RADIO); GridData revisionButtonData = new GridData(); revisionButtonData.horizontalIndent = 10; revisionLabel.setLayoutData(revisionButtonData); revisionLabel.setText(Messages.MavenCheckoutLocationPage_lblRevision); // revisionButton.addSelectionListener(selectionAdapter); revisionText = new Text(composite, SWT.BORDER); GridData revisionTextData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); revisionTextData.widthHint = 115; revisionTextData.verticalIndent = 3; revisionText.setLayoutData(revisionTextData); if(scmUrls != null) { ScmTag tag = scmUrls[0].getTag(); if(tag!=null) { headRevisionButton.setSelection(false); revisionText.setText(tag.getName()); } } revisionText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updatePage(); } }); revisionBrowseButton = new Button(composite, SWT.NONE); GridData gd_revisionBrowseButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_revisionBrowseButton.verticalIndent = 3; revisionBrowseButton.setLayoutData(gd_revisionBrowseButton); revisionBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnRevSelect); revisionBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String url = scmParentUrl; if(url==null) { return; } String scmType = scmTypeCombo.getText(); ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); String revision = handlerUi.selectRevision(getShell(), scmUrls[0], revisionText.getText()); if(revision!=null) { revisionText.setText(revision); headRevisionButton.setSelection(false); updatePage(); } } }); checkoutAllProjectsButton = new Button(composite, SWT.CHECK); GridData checkoutAllProjectsData = new GridData(SWT.LEFT, SWT.TOP, true, false, 5, 1); checkoutAllProjectsData.verticalIndent = 10; checkoutAllProjectsButton.setLayoutData(checkoutAllProjectsData); checkoutAllProjectsButton.setText(Messages.MavenCheckoutLocationPage_btnCheckout); checkoutAllProjectsButton.setSelection(true); checkoutAllProjectsButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }); GridData advancedSettingsData = new GridData(SWT.FILL, SWT.TOP, true, false, 5, 1); advancedSettingsData.verticalIndent = 10; createAdvancedSettings(composite, advancedSettingsData); if(scmUrls!=null && scmUrls.length == 1) { scmTypeCombo.setText(scmType == null ? "" : scmType); //$NON-NLS-1$ scmUrlCombo.setText(scmUrls[0].getProviderUrl()); } if(scmUrls == null || scmUrls.length < 2) { scmUrlBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); // XXX should use null if there is no scmUrl selected ScmUrl currentUrl = scmUrls==null || scmUrls.length==0 ? new ScmUrl("scm:" + scmType + ":") : scmUrls[0]; //$NON-NLS-1$ //$NON-NLS-2$ ScmUrl scmUrl = handlerUi.selectUrl(getShell(), currentUrl); if(scmUrl!=null) { scmUrlCombo.setText(scmUrl.getProviderUrl()); if(scmUrls==null) { scmUrls = new ScmUrl[1]; } scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } } }); scmUrlCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { final String url = scmUrlCombo.getText(); if(url.startsWith("scm:")) { //$NON-NLS-1$ try { final String type = ScmUrl.getType(url); scmTypeCombo.setText(type); scmType = type; Display.getDefault().asyncExec(new Runnable() { public void run() { scmUrlCombo.setText(url.substring(type.length() + 5)); } }); } catch(CoreException ex) { } return; } if(scmUrls==null) { scmUrls = new ScmUrl[1]; } ScmUrl scmUrl = new ScmUrl("scm:" + scmType + ":" + url); //$NON-NLS-1$ //$NON-NLS-2$ scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } }); } updatePage(); }
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(5, false); gridLayout.verticalSpacing = 0; composite.setLayout(gridLayout); setControl(composite); SelectionAdapter selectionAdapter = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }; if(scmUrls == null || scmUrls.length < 2) { Label urlLabel = new Label(composite, SWT.NONE); urlLabel.setText(Messages.MavenCheckoutLocationPage_lblurl); scmTypeCombo = new Combo(composite, SWT.READ_ONLY); GridData gd_scmTypeCombo = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_scmTypeCombo.widthHint = 80; scmTypeCombo.setLayoutData(gd_scmTypeCombo); scmTypeCombo.setData("name", "mavenCheckoutLocation.typeCombo"); //$NON-NLS-1$ //$NON-NLS-2$ String[] types = ScmHandlerFactory.getTypes(); for(int i = 0; i < types.length; i++ ) { scmTypeCombo.add(types[i]); } scmTypeCombo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String newScmType = scmTypeCombo.getText(); if(!newScmType.equals(scmType)) { scmType = newScmType; scmUrlCombo.setText(""); //$NON-NLS-1$ updatePage(); } } }); if(scmUrls!=null && scmUrls.length == 1) { try { scmType = ScmUrl.getType(scmUrls[0].getUrl()); } catch(CoreException ex) { } } scmUrlCombo = new Combo(composite, SWT.NONE); scmUrlCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); scmUrlCombo.setData("name", "mavenCheckoutLocation.urlCombo"); //$NON-NLS-1$ //$NON-NLS-2$ scmUrlBrowseButton = new Button(composite, SWT.NONE); scmUrlBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnBrowse); } headRevisionButton = new Button(composite, SWT.CHECK); GridData headRevisionButtonData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1); headRevisionButtonData.verticalIndent = 5; headRevisionButton.setLayoutData(headRevisionButtonData); headRevisionButton.setText(Messages.MavenCheckoutLocationPage_btnHead); headRevisionButton.setSelection(true); headRevisionButton.addSelectionListener(selectionAdapter); revisionLabel = new Label(composite, SWT.RADIO); GridData revisionButtonData = new GridData(); revisionButtonData.horizontalIndent = 10; revisionLabel.setLayoutData(revisionButtonData); revisionLabel.setText(Messages.MavenCheckoutLocationPage_lblRevision); // revisionButton.addSelectionListener(selectionAdapter); revisionText = new Text(composite, SWT.BORDER); GridData revisionTextData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); revisionTextData.widthHint = 115; revisionTextData.verticalIndent = 3; revisionText.setLayoutData(revisionTextData); if(scmUrls != null) { ScmTag tag = scmUrls[0].getTag(); if(tag!=null) { headRevisionButton.setSelection(false); revisionText.setText(tag.getName()); } } revisionText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updatePage(); } }); revisionBrowseButton = new Button(composite, SWT.NONE); GridData gd_revisionBrowseButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_revisionBrowseButton.verticalIndent = 3; revisionBrowseButton.setLayoutData(gd_revisionBrowseButton); revisionBrowseButton.setText(Messages.MavenCheckoutLocationPage_btnRevSelect); revisionBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String url = scmParentUrl; if(url==null) { return; } String scmType = scmTypeCombo.getText(); ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); String revision = handlerUi.selectRevision(getShell(), scmUrls[0], revisionText.getText()); if(revision!=null) { revisionText.setText(revision); headRevisionButton.setSelection(false); updatePage(); } } }); checkoutAllProjectsButton = new Button(composite, SWT.CHECK); GridData checkoutAllProjectsData = new GridData(SWT.LEFT, SWT.TOP, true, false, 5, 1); checkoutAllProjectsData.verticalIndent = 10; checkoutAllProjectsButton.setLayoutData(checkoutAllProjectsData); checkoutAllProjectsButton.setText(Messages.MavenCheckoutLocationPage_btnCheckout); checkoutAllProjectsButton.setSelection(true); checkoutAllProjectsButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { updatePage(); } }); GridData advancedSettingsData = new GridData(SWT.FILL, SWT.TOP, true, false, 5, 1); advancedSettingsData.verticalIndent = 10; createAdvancedSettings(composite, advancedSettingsData); if(scmUrls!=null && scmUrls.length == 1) { scmTypeCombo.setText(scmType == null ? "" : scmType); //$NON-NLS-1$ scmUrlCombo.setText(scmUrls[0].getProviderUrl()); } if(scmUrls == null || scmUrls.length < 2) { scmUrlBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ScmHandlerUi handlerUi = ScmHandlerFactory.getHandlerUiByType(scmType); // XXX should use null if there is no scmUrl selected ScmUrl currentUrl = scmUrls==null || scmUrls.length==0 ? new ScmUrl("scm:" + scmType + ":") : scmUrls[0]; //$NON-NLS-1$ //$NON-NLS-2$ ScmUrl scmUrl = handlerUi.selectUrl(getShell(), currentUrl); if(scmUrl!=null) { scmUrlCombo.setText(scmUrl.getProviderUrl()); if(scmUrls==null) { scmUrls = new ScmUrl[1]; } scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } } }); scmUrlCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { final String url = scmUrlCombo.getText(); if(url.startsWith("scm:")) { //$NON-NLS-1$ try { final String type = ScmUrl.getType(url); scmTypeCombo.setText(type); scmType = type; Display.getDefault().asyncExec(new Runnable() { public void run() { scmUrlCombo.setText(url.substring(type.length() + 5)); } }); } catch(CoreException ex) { } return; } if(scmUrls==null) { scmUrls = new ScmUrl[1]; } ScmUrl scmUrl = new ScmUrl("scm:" + scmType + ":" + url); //$NON-NLS-1$ //$NON-NLS-2$ scmUrls[0] = scmUrl; scmParentUrl = scmUrl.getUrl(); updatePage(); } }); } updatePage(); }
diff --git a/src/main/java/de/ailis/jasdoc/util/JsTypeUtils.java b/src/main/java/de/ailis/jasdoc/util/JsTypeUtils.java index 2935212..93865e0 100644 --- a/src/main/java/de/ailis/jasdoc/util/JsTypeUtils.java +++ b/src/main/java/de/ailis/jasdoc/util/JsTypeUtils.java @@ -1,154 +1,154 @@ /* * Copyright (C) 2012 Klaus Reimer <[email protected]> * See LICENSE.md for licensing information. */ package de.ailis.jasdoc.util; import java.util.ArrayList; import java.util.List; /** * JavaScript type utility methods. * * @author Klaus Reimer ([email protected]) */ public final class JsTypeUtils { /** * Private constructor to prevent instantiation. */ private JsTypeUtils() { // Empty } /** * Splits an expression by the specified separator but keeps track of * brackets so separator characters inside of a sub type are ignored. The * splitted parts are also trimmed. * * @param expression * The expression to split. * @param separator * The separator character. * @return The splitted expression parts. */ public static String[] split(final String expression, final char separator) { final List<String> parts = new ArrayList<String>(); int start = 0; int level = 0; final int len = expression.length(); for (int i = 0; i < len; i += 1) { final char c = expression.charAt(i); if (c == separator) { if (level == 0) { parts.add(expression.substring(start, i).trim()); start = i + 1; } } if (c == '{' || c == '<' || c == '[' || c == '(') level += 1; else if (c == '}' || c == '>' || c == ']' || c == ')') level -= 1; } if (start <= len) parts.add(expression.substring(start, len).trim()); return parts.toArray(new String[parts.size()]); } /** * Searches the end index for a specific bracket. * * @param e * The type expression to search in. * @param start * The start index pointing at the opening bracket. * @return The end index. */ public static int findEnd(final String e, final int start) { if (e.length() == 0) return -1; final char startChar = e.charAt(start); final int len = e.length(); int level = 0; char endChar; switch (startChar) { case '(': endChar = ')'; break; case '<': endChar = '>'; break; case '{': endChar = '}'; break; case '[': - endChar = '}'; + endChar = ']'; break; default: return len - 1; } for (int i = start + 1; i < len; i += 1) { final char c = e.charAt(i); if (c == endChar) { if (level == 0) return i; level -= 1; } else if (c == startChar) { level += 1; } } return len - 1; } /** * Splits the specified string into a type and the rest of the string. If * string is "{Object.<string, number>} test" for example then the returned * array contains two elements. The first element is the type expression and * the second element is the rest of the string ("test" in this case) * * @param s * The string to split. * @return The string splitted into a type expression and the rest of the * string. It always returns an array with two elements. All two can * be empty. */ public static String[] splitByType(final String s) { final String all = s.trim(); final int pos = findEnd(all, 0); final String typeExpr = all.substring(0, pos + 1); final String rest = all.substring(pos + 1).trim(); return new String[] { typeExpr, rest }; } /** * Splits the specified string into a type, a name and the rest of the * string. If string is "{Object.<string, number>} test Some doc" for * example then the returned array contains three elements. The first * element is the type expression, the second element is name ("test") and * the rest of the string ("Some doc"). * * @param s * The string to split. * @return The string splitted into a type expression, a name and the rest * of the string. It always returns an array with three elements. * All three can be empty. */ public static String[] splitByTypeAndName(final String s) { final String[] parts = splitByType(s); final String[] parts2 = parts[1].split("\\s+", 2); return new String[] { parts[0], parts2[0], parts2.length == 2 ? parts2[1] : "" }; } }
true
true
public static int findEnd(final String e, final int start) { if (e.length() == 0) return -1; final char startChar = e.charAt(start); final int len = e.length(); int level = 0; char endChar; switch (startChar) { case '(': endChar = ')'; break; case '<': endChar = '>'; break; case '{': endChar = '}'; break; case '[': endChar = '}'; break; default: return len - 1; } for (int i = start + 1; i < len; i += 1) { final char c = e.charAt(i); if (c == endChar) { if (level == 0) return i; level -= 1; } else if (c == startChar) { level += 1; } } return len - 1; }
public static int findEnd(final String e, final int start) { if (e.length() == 0) return -1; final char startChar = e.charAt(start); final int len = e.length(); int level = 0; char endChar; switch (startChar) { case '(': endChar = ')'; break; case '<': endChar = '>'; break; case '{': endChar = '}'; break; case '[': endChar = ']'; break; default: return len - 1; } for (int i = start + 1; i < len; i += 1) { final char c = e.charAt(i); if (c == endChar) { if (level == 0) return i; level -= 1; } else if (c == startChar) { level += 1; } } return len - 1; }
diff --git a/components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java b/components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java index a7a0c0e50..268df4702 100644 --- a/components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java +++ b/components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java @@ -1,602 +1,610 @@ // // OMEXMLServiceImpl.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, 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 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 loci.formats.services; import java.io.IOException; import java.util.Hashtable; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Templates; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import loci.common.services.AbstractService; import loci.common.services.ServiceException; import loci.common.xml.XMLTools; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataConverter; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import loci.formats.ome.OMEXMLMetadata; import loci.formats.ome.OMEXMLMetadataImpl; import ome.xml.OMEXMLFactory; import ome.xml.model.BinData; import ome.xml.model.Channel; import ome.xml.model.Image; import ome.xml.model.MetadataOnly; import ome.xml.model.OME; import ome.xml.model.OMEModel; import ome.xml.model.OMEModelImpl; import ome.xml.model.OMEModelObject; import ome.xml.model.Pixels; import ome.xml.model.StructuredAnnotations; import ome.xml.model.XMLAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/services/OMEXMLServiceImpl.java;hb=HEAD">Gitweb</a></dd></dl> * * @author callan */ public class OMEXMLServiceImpl extends AbstractService implements OMEXMLService { public static final String NO_OME_XML_MSG = "ome-xml.jar is required to read OME-TIFF files. " + "Please download it from " + FormatTools.URL_BIO_FORMATS_LIBRARIES; /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(OMEXMLService.class); /** Reordering stylesheet. */ private static final Templates reorderXSLT = XMLTools.getStylesheet("/loci/formats/meta/reorder-2008-09.xsl", OMEXMLServiceImpl.class); /** Stylesheets for updating from previous schema releases. */ private static final Templates UPDATE_2003FC = XMLTools.getStylesheet("/loci/formats/meta/2003-FC-to-2008-09.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_2006LO = XMLTools.getStylesheet("/loci/formats/meta/2006-LO-to-2008-09.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_200706 = XMLTools.getStylesheet("/loci/formats/meta/2007-06-to-2008-09.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_200802 = XMLTools.getStylesheet("/loci/formats/meta/2008-02-to-2008-09.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_200809 = XMLTools.getStylesheet("/loci/formats/meta/2008-09-to-2009-09.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_200909 = XMLTools.getStylesheet("/loci/formats/meta/2009-09-to-2010-04.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_201004 = XMLTools.getStylesheet("/loci/formats/meta/2010-04-to-2010-06.xsl", OMEXMLServiceImpl.class); private static final Templates UPDATE_201006 = XMLTools.getStylesheet("/loci/formats/meta/2010-06-to-2011-06.xsl", OMEXMLServiceImpl.class); private static final String SCHEMA_PATH = "http://www.openmicroscopy.org/Schemas/OME/"; /** * Default constructor. */ public OMEXMLServiceImpl() { checkClassDependency(ome.xml.model.OMEModelObject.class); } /** @see OMEXMLService#getLatestVersion() */ public String getLatestVersion() { return OMEXMLFactory.LATEST_VERSION; } /** @see OMEXMLService#transformToLatestVersion(String) */ public String transformToLatestVersion(String xml) throws ServiceException { String version = getOMEXMLVersion(xml); if (version.equals(getLatestVersion())) return xml; LOGGER.debug("Attempting to update XML with version: {}", version); LOGGER.trace("Initial dump: {}", xml); String transformed = null; try { if (version.equals("2003-FC")) { xml = verifyOMENamespace(xml); + LOGGER.debug("Running UPDATE_2003FC stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_2003FC); } else if (version.equals("2006-LO")) { xml = verifyOMENamespace(xml); + LOGGER.debug("Running UPDATE_2006LO stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_2006LO); } else if (version.equals("2007-06")) { xml = verifyOMENamespace(xml); + LOGGER.debug("Running UPDATE_200706 stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_200706); } else if (version.equals("2008-02")) { xml = verifyOMENamespace(xml); + LOGGER.debug("Running UPDATE_200802 stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_200802); } else transformed = xml; LOGGER.debug("XML updated to at least 2008-09"); LOGGER.trace("At least 2008-09 dump: {}", transformed); if (!version.equals("2009-09") && !version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); + LOGGER.debug("Running UPDATE_200809 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_200809); } LOGGER.debug("XML updated to at least 2009-09"); LOGGER.trace("At least 2009-09 dump: {}", transformed); if (!version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); + LOGGER.debug("Running UPDATE_200909 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_200909); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-04"); LOGGER.trace("At least 2010-04 dump: {}", transformed); - if (!version.equals("2010-04")) { + if (!version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); + LOGGER.debug("Running UPDATE_201004 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_201004); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-06"); transformed = verifyOMENamespace(transformed); + LOGGER.debug("Running UPDATE_201006 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_201006); LOGGER.debug("XML updated to at least 2011-06"); // fix namespaces transformed = transformed.replaceAll("<ns.*?:", "<"); transformed = transformed.replaceAll("xmlns:ns.*?=", "xmlns:OME="); transformed = transformed.replaceAll("</ns.*?:", "</"); LOGGER.trace("Transformed XML dump: {}", transformed); return transformed; } catch (IOException e) { LOGGER.warn("Could not transform version " + version + " OME-XML."); } return null; } /** @see OMEXMLService#createOMEXMLMetadata() */ public OMEXMLMetadata createOMEXMLMetadata() throws ServiceException { return createOMEXMLMetadata(null); } /** @see OMEXMLService#createOMEXMLMetadata(java.lang.String) */ public OMEXMLMetadata createOMEXMLMetadata(String xml) throws ServiceException { return createOMEXMLMetadata(xml, null); } /** * @see OMEXMLService#createOMEXMLMetadata(java.lang.String, java.lang.String) */ public OMEXMLMetadata createOMEXMLMetadata(String xml, String version) throws ServiceException { if (xml != null) { xml = XMLTools.sanitizeXML(xml); } OMEModelObject ome = xml == null ? null : createRoot(transformToLatestVersion(xml)); OMEXMLMetadata meta = new OMEXMLMetadataImpl(); if (ome != null) meta.setRoot(ome); return meta; } /** @see OMEXMLService#createOMEXMLRoot(java.lang.String) */ public Object createOMEXMLRoot(String xml) throws ServiceException { return createRoot(transformToLatestVersion(xml)); } /** @see OMEXMLService#isOMEXMLMetadata(java.lang.Object) */ public boolean isOMEXMLMetadata(Object o) { return o instanceof OMEXMLMetadata; } /** @see OMEXMLService#isOMEXMLRoot(java.lang.Object) */ public boolean isOMEXMLRoot(Object o) { return o instanceof OMEModelObject; } /** * Constructs an OME root node. <b>NOTE:</b> This method is mostly here to * ensure type safety of return values as instances of service dependency * classes should not leak out of the interface. * @param xml String of XML to create the root node from. * @return An ome.xml.model.OMEModelObject subclass root node. * @throws IOException If there is an error reading from the string. * @throws SAXException If there is an error parsing the XML. * @throws ParserConfigurationException If there is an error preparing the * parsing infrastructure. */ private OMEModelObject createRoot(String xml) throws ServiceException { try { OMEModel model = new OMEModelImpl(); OME ome = new OME(XMLTools.parseDOM(xml).getDocumentElement(), model); model.resolveReferences(); return ome; } catch (Exception e) { throw new ServiceException(e); } } /** @see OMEXMLService#getOMEXMLVersion(java.lang.Object) */ public String getOMEXMLVersion(Object o) { if (o == null) return null; if (o instanceof OMEXMLMetadata || o instanceof OMEModelObject) { return OMEXMLFactory.LATEST_VERSION; } else if (o instanceof String) { String xml = (String) o; try { Element e = XMLTools.parseDOM(xml).getDocumentElement(); String namespace = e.getAttribute("xmlns"); if (namespace == null || namespace.equals("")) { namespace = e.getAttribute("xmlns:ome"); } return namespace.endsWith("ome.xsd") ? "2003-FC" : namespace.substring(namespace.lastIndexOf("/") + 1); } catch (ParserConfigurationException pce) { } catch (SAXException se) { } catch (IOException ioe) { } } return null; } /** @see OMEXMLService#getOMEMetadata(loci.formats.meta.MetadataRetrieve) */ public OMEXMLMetadata getOMEMetadata(MetadataRetrieve src) throws ServiceException { // check if the metadata is already an OME-XML metadata object if (src instanceof OMEXMLMetadata) return (OMEXMLMetadata) src; // populate a new OME-XML metadata object with metadata // converted from the non-OME-XML metadata object OMEXMLMetadata omexmlMeta = createOMEXMLMetadata(); convertMetadata(src, omexmlMeta); return omexmlMeta; } /** @see OMEXMLService#getOMEXML(loci.formats.meta.MetadataRetrieve) */ public String getOMEXML(MetadataRetrieve src) throws ServiceException { OMEXMLMetadata omexmlMeta = getOMEMetadata(src); String xml = omexmlMeta.dumpXML(); // make sure that the namespace has been set correctly // convert XML string to DOM Document doc = null; Exception exception = null; try { doc = XMLTools.parseDOM(xml); } catch (ParserConfigurationException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } catch (IOException exc) { exception = exc; } if (exception != null) { LOGGER.info("Malformed OME-XML", exception); return null; } Element root = doc.getDocumentElement(); root.setAttribute("xmlns", SCHEMA_PATH + getLatestVersion()); // convert tweaked DOM back to XML string try { xml = XMLTools.getXML(doc); } catch (TransformerConfigurationException exc) { exception = exc; } catch (TransformerException exc) { exception = exc; } if (exception != null) { LOGGER.info("Internal XML conversion error", exception); return null; } return xml; } /** @see OMEXMLService#validateOMEXML(java.lang.String) */ public boolean validateOMEXML(String xml) { return validateOMEXML(xml, false); } /** @see OMEXMLService#validateOMEXML(java.lang.String, boolean) */ public boolean validateOMEXML(String xml, boolean pixelsHack) { // HACK: Inject a TiffData element beneath any childless Pixels elements. if (pixelsHack) { // convert XML string to DOM Document doc = null; Exception exception = null; try { doc = XMLTools.parseDOM(xml); } catch (ParserConfigurationException exc) { exception = exc; } catch (SAXException exc) { exception = exc; } catch (IOException exc) { exception = exc; } if (exception != null) { LOGGER.info("Malformed OME-XML", exception); return false; } // inject TiffData elements as needed NodeList list = doc.getElementsByTagName("Pixels"); for (int i=0; i<list.getLength(); i++) { Node node = list.item(i); NodeList children = node.getChildNodes(); boolean needsTiffData = true; for (int j=0; j<children.getLength(); j++) { Node child = children.item(j); String name = child.getLocalName(); if ("TiffData".equals(name) || "BinData".equals(name)) { needsTiffData = false; break; } } if (needsTiffData) { // inject TiffData element Node tiffData = doc.createElement("TiffData"); node.insertBefore(tiffData, node.getFirstChild()); } } // convert tweaked DOM back to XML string try { xml = XMLTools.getXML(doc); } catch (TransformerConfigurationException exc) { exception = exc; } catch (TransformerException exc) { exception = exc; } if (exception != null) { LOGGER.info("Internal XML conversion error", exception); return false; } } return XMLTools.validateXML(xml, "OME-XML"); } /** * @see OMEXMLService#populateOriginalMetadata(loci.formats.ome.OMEXMLMetadata, Hashtable) */ public void populateOriginalMetadata(OMEXMLMetadata omexmlMeta, Hashtable<String, Object> metadata) { ((OMEXMLMetadataImpl) omexmlMeta).resolveReferences(); OME root = (OME) omexmlMeta.getRoot(); StructuredAnnotations annotations = root.getStructuredAnnotations(); if (annotations == null) annotations = new StructuredAnnotations(); int annotationIndex = annotations.sizeOfXMLAnnotationList(); for (String key : metadata.keySet()) { OriginalMetadataAnnotation annotation = new OriginalMetadataAnnotation(); annotation.setID(MetadataTools.createLSID("Annotation", annotationIndex)); annotation.setKey(key); annotation.setValue(metadata.get(key).toString()); annotations.addXMLAnnotation(annotation); annotationIndex++; } root.setStructuredAnnotations(annotations); omexmlMeta.setRoot(root); } /** * @see OMEXMLService#populateOriginalMetadata(loci.formats.ome.OMEXMLMetadata, java.lang.String, java.lang.String) */ public void populateOriginalMetadata(OMEXMLMetadata omexmlMeta, String key, String value) { ((OMEXMLMetadataImpl) omexmlMeta).resolveReferences(); OME root = (OME) omexmlMeta.getRoot(); StructuredAnnotations annotations = root.getStructuredAnnotations(); if (annotations == null) annotations = new StructuredAnnotations(); int annotationIndex = annotations.sizeOfXMLAnnotationList(); OriginalMetadataAnnotation annotation = new OriginalMetadataAnnotation(); annotation.setID(MetadataTools.createLSID("Annotation", annotationIndex)); annotation.setKey(key); annotation.setValue(value); annotations.addXMLAnnotation(annotation); root.setStructuredAnnotations(annotations); omexmlMeta.setRoot(root); } /** * @see OMEXMLService#convertMetadata(java.lang.String, loci.formats.meta.MetadataStore) */ public void convertMetadata(String xml, MetadataStore dest) throws ServiceException { OMEModelObject ome = createRoot(transformToLatestVersion(xml)); String rootVersion = getOMEXMLVersion(ome); String storeVersion = getOMEXMLVersion(dest); if (rootVersion.equals(storeVersion)) { // metadata store is already an OME-XML metadata object of the // correct schema version; populate OME-XML string directly if (!(dest instanceof OMEXMLMetadata)) { throw new IllegalArgumentException( "Expecting OMEXMLMetadata instance."); } dest.setRoot(ome); } else { // metadata store is incompatible; create an OME-XML // metadata object and copy it into the destination IMetadata src = createOMEXMLMetadata(xml); convertMetadata(src, dest); } } /** * @see OMEXMLService#convertMetadata(loci.formats.meta.MetadataRetrieve, loci.formats.meta.MetadataStore) */ public void convertMetadata(MetadataRetrieve src, MetadataStore dest) { MetadataConverter.convertMetadata(src, dest); } /** @see OMEXMLService#removeBinData(OMEXMLMetadata) */ public void removeBinData(OMEXMLMetadata omexmlMeta) { ((OMEXMLMetadataImpl) omexmlMeta).resolveReferences(); OME root = (OME) omexmlMeta.getRoot(); List<Image> images = root.copyImageList(); for (Image img : images) { Pixels pix = img.getPixels(); List<BinData> binData = pix.copyBinDataList(); for (BinData bin : binData) { pix.removeBinData(bin); } } omexmlMeta.setRoot(root); } /** @see OMEXMLService#removeChannels(OMEXMLMetadata, int, int) */ public void removeChannels(OMEXMLMetadata omexmlMeta, int image, int sizeC) { ((OMEXMLMetadataImpl) omexmlMeta).resolveReferences(); OME root = (OME) omexmlMeta.getRoot(); Pixels img = root.getImage(image).getPixels(); List<Channel> channels = img.copyChannelList(); for (int c=0; c<channels.size(); c++) { Channel channel = channels.get(c); if (channel.getID() == null || c >= sizeC) { img.removeChannel(channel); } } omexmlMeta.setRoot(root); } /** @see OMEXMLService#addMetadataOnly(OMEXMLMetadata, int) */ public void addMetadataOnly(OMEXMLMetadata omexmlMeta, int image) { ((OMEXMLMetadataImpl) omexmlMeta).resolveReferences(); MetadataOnly meta = new MetadataOnly(); OME root = (OME) omexmlMeta.getRoot(); Pixels pix = root.getImage(image).getPixels(); pix.setMetadataOnly(meta); omexmlMeta.setRoot(root); } // -- Utility methods - casting -- /** @see OMEXMLService#asStore(loci.formats.meta.MetadataRetrieve) */ public MetadataStore asStore(MetadataRetrieve meta) { return meta instanceof MetadataStore ? (MetadataStore) meta : null; } /** @see OMEXMLService#asRetrieve(loci.formats.meta.MetadataStore) */ public MetadataRetrieve asRetrieve(MetadataStore meta) { return meta instanceof MetadataRetrieve ? (MetadataRetrieve) meta : null; } // -- Helper methods -- /** Ensures that an xmlns:ome element exists. */ private String verifyOMENamespace(String xml) { try { Document doc = XMLTools.parseDOM(xml); Element e = doc.getDocumentElement(); String omeNamespace = e.getAttribute("xmlns:ome"); if (omeNamespace == null || omeNamespace.equals("")) { e.setAttribute("xmlns:ome", e.getAttribute("xmlns")); } return XMLTools.getXML(doc); } catch (ParserConfigurationException pce) { } catch (TransformerConfigurationException tce) { } catch (TransformerException te) { } catch (SAXException se) { } catch (IOException ioe) { } return null; } // -- Helper class -- class OriginalMetadataAnnotation extends XMLAnnotation { private static final String ORIGINAL_METADATA_NS = "openmicroscopy.org/OriginalMetadata"; private String key, value; // -- OriginalMetadataAnnotation methods -- public void setKey(String key) { this.key = key; } public void setValue(String value) { this.value = value; } // -- XMLAnnotation methods -- /* @see ome.xml.model.XMLAnnotation#asXMLElement(Document, Element) */ protected Element asXMLElement(Document document, Element element) { if (element == null) { element = document.createElementNS(XMLAnnotation.NAMESPACE, "XMLAnnotation"); } Element keyElement = document.createElementNS(ORIGINAL_METADATA_NS, "Key"); Element valueElement = document.createElementNS(ORIGINAL_METADATA_NS, "Value"); keyElement.setTextContent(key); valueElement.setTextContent(value); Element originalMetadata = document.createElementNS(ORIGINAL_METADATA_NS, "OriginalMetadata"); originalMetadata.appendChild(keyElement); originalMetadata.appendChild(valueElement); Element annotationValue = document.createElementNS(XMLAnnotation.NAMESPACE, "Value"); annotationValue.appendChild(originalMetadata); element.appendChild(annotationValue); return super.asXMLElement(document, element); } } }
false
true
public String transformToLatestVersion(String xml) throws ServiceException { String version = getOMEXMLVersion(xml); if (version.equals(getLatestVersion())) return xml; LOGGER.debug("Attempting to update XML with version: {}", version); LOGGER.trace("Initial dump: {}", xml); String transformed = null; try { if (version.equals("2003-FC")) { xml = verifyOMENamespace(xml); transformed = XMLTools.transformXML(xml, UPDATE_2003FC); } else if (version.equals("2006-LO")) { xml = verifyOMENamespace(xml); transformed = XMLTools.transformXML(xml, UPDATE_2006LO); } else if (version.equals("2007-06")) { xml = verifyOMENamespace(xml); transformed = XMLTools.transformXML(xml, UPDATE_200706); } else if (version.equals("2008-02")) { xml = verifyOMENamespace(xml); transformed = XMLTools.transformXML(xml, UPDATE_200802); } else transformed = xml; LOGGER.debug("XML updated to at least 2008-09"); LOGGER.trace("At least 2008-09 dump: {}", transformed); if (!version.equals("2009-09") && !version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); transformed = XMLTools.transformXML(transformed, UPDATE_200809); } LOGGER.debug("XML updated to at least 2009-09"); LOGGER.trace("At least 2009-09 dump: {}", transformed); if (!version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); transformed = XMLTools.transformXML(transformed, UPDATE_200909); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-04"); LOGGER.trace("At least 2010-04 dump: {}", transformed); if (!version.equals("2010-04")) { transformed = verifyOMENamespace(transformed); transformed = XMLTools.transformXML(transformed, UPDATE_201004); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-06"); transformed = verifyOMENamespace(transformed); transformed = XMLTools.transformXML(transformed, UPDATE_201006); LOGGER.debug("XML updated to at least 2011-06"); // fix namespaces transformed = transformed.replaceAll("<ns.*?:", "<"); transformed = transformed.replaceAll("xmlns:ns.*?=", "xmlns:OME="); transformed = transformed.replaceAll("</ns.*?:", "</"); LOGGER.trace("Transformed XML dump: {}", transformed); return transformed; } catch (IOException e) { LOGGER.warn("Could not transform version " + version + " OME-XML."); } return null; }
public String transformToLatestVersion(String xml) throws ServiceException { String version = getOMEXMLVersion(xml); if (version.equals(getLatestVersion())) return xml; LOGGER.debug("Attempting to update XML with version: {}", version); LOGGER.trace("Initial dump: {}", xml); String transformed = null; try { if (version.equals("2003-FC")) { xml = verifyOMENamespace(xml); LOGGER.debug("Running UPDATE_2003FC stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_2003FC); } else if (version.equals("2006-LO")) { xml = verifyOMENamespace(xml); LOGGER.debug("Running UPDATE_2006LO stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_2006LO); } else if (version.equals("2007-06")) { xml = verifyOMENamespace(xml); LOGGER.debug("Running UPDATE_200706 stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_200706); } else if (version.equals("2008-02")) { xml = verifyOMENamespace(xml); LOGGER.debug("Running UPDATE_200802 stylesheet."); transformed = XMLTools.transformXML(xml, UPDATE_200802); } else transformed = xml; LOGGER.debug("XML updated to at least 2008-09"); LOGGER.trace("At least 2008-09 dump: {}", transformed); if (!version.equals("2009-09") && !version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); LOGGER.debug("Running UPDATE_200809 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_200809); } LOGGER.debug("XML updated to at least 2009-09"); LOGGER.trace("At least 2009-09 dump: {}", transformed); if (!version.equals("2010-04") && !version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); LOGGER.debug("Running UPDATE_200909 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_200909); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-04"); LOGGER.trace("At least 2010-04 dump: {}", transformed); if (!version.equals("2010-06")) { transformed = verifyOMENamespace(transformed); LOGGER.debug("Running UPDATE_201004 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_201004); } else transformed = xml; LOGGER.debug("XML updated to at least 2010-06"); transformed = verifyOMENamespace(transformed); LOGGER.debug("Running UPDATE_201006 stylesheet."); transformed = XMLTools.transformXML(transformed, UPDATE_201006); LOGGER.debug("XML updated to at least 2011-06"); // fix namespaces transformed = transformed.replaceAll("<ns.*?:", "<"); transformed = transformed.replaceAll("xmlns:ns.*?=", "xmlns:OME="); transformed = transformed.replaceAll("</ns.*?:", "</"); LOGGER.trace("Transformed XML dump: {}", transformed); return transformed; } catch (IOException e) { LOGGER.warn("Could not transform version " + version + " OME-XML."); } return null; }
diff --git a/Sources/AddHostDialog.java b/Sources/AddHostDialog.java index a921bf6..d08c23a 100644 --- a/Sources/AddHostDialog.java +++ b/Sources/AddHostDialog.java @@ -1,174 +1,178 @@ // // Copyright (C) 2007-2008 David Czechowski All Rights Reserved. // // This is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this software; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // import java.awt.*; import java.awt.event.*; // // The Dialog is used to add another host to VncThumbnailViewer // class AddHostDialog extends Dialog implements ActionListener, ItemListener { static String readEncPassword(String encPass) { if(encPass.length() != 16) { // FIX-ME: change this, to something that's easier to detect //throw new Exception("VNC Enc. Passwords must be 16 chars"); System.out.println("VNC Enc. Passwords must be 16 chars"); return encPass; } byte[] pw = {0, 0, 0, 0, 0, 0, 0, 0}; int len = encPass.length() / 2; if(len > 8) { len = 8; } for(int i = 0; i < len; i++) { String hex = encPass.substring(i*2, i*2+2); Integer x = new Integer(Integer.parseInt(hex, 16)); pw[i] = x.byteValue(); } byte[] key = {23, 82, 107, 6, 35, 78, 88, 7}; DesCipher des = new DesCipher(key); des.decrypt(pw, 0, pw, 0); return new String(pw); } VncThumbnailViewer tnviewer; TextField hostField; TextField portField; TextField usernameField; TextField passwordField; Choice authChoice; Button connectButton; Button cancelButton; // // Constructor. // public AddHostDialog(VncThumbnailViewer tnviewer) { super(tnviewer, true); this.tnviewer = tnviewer; // GUI Stuff: - setSize(250, 175); setResizable(false); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); setFont(new Font("Helvetica", Font.PLAIN, 14)); hostField = new TextField("", 10); portField = new TextField("5900", 10); usernameField = new TextField("", 10); usernameField.enable(false); // not needed by default passwordField = new TextField("", 10); passwordField.setEchoChar('*'); passwordField.enable(false); // not needed by default authChoice = new Choice(); authChoice.addItemListener(this); authChoice.add("(none)"); authChoice.add("Password"); authChoice.add("VNC Enc. Password"); authChoice.add("MS-Logon"); connectButton = new Button("Connect..."); cancelButton = new Button("Cancel"); connectButton.addActionListener(this); cancelButton.addActionListener(this); // End of Row Components: c.gridwidth = GridBagConstraints.REMAINDER; //end row gridbag.setConstraints(authChoice, c); gridbag.setConstraints(hostField, c); gridbag.setConstraints(portField, c); gridbag.setConstraints(usernameField, c); gridbag.setConstraints(passwordField, c); gridbag.setConstraints(connectButton, c); add(new Label("Host", Label.RIGHT)); add(hostField); add(new Label("Port", Label.RIGHT)); add(portField); add(new Label("Authentication:", Label.RIGHT)); add(authChoice); add(new Label("Username", Label.RIGHT)); add(usernameField); add(new Label("Password", Label.RIGHT)); add(passwordField); add(cancelButton); add(connectButton); - //add(panel); + Point loc = tnviewer.getLocation(); + Dimension dim = tnviewer.getSize(); + loc.x += (dim.width/2)-50; + loc.y += (dim.height/2)-50; + setLocation(loc); + pack(); validate(); setVisible(true); } void callAddHost() { String host = hostField.getText(); int port = Integer.parseInt(portField.getText()); // Password: String pass = passwordField.getText(); // MS-Logon: String user = usernameField.getText(); // Encrypted Password: if(authChoice.getSelectedItem() == "VNC Enc. Password") { pass = readEncPassword(pass); } tnviewer.launchViewer(host, port, pass, user); } // Action Listener Event: public void actionPerformed(ActionEvent evt) { if(evt.getSource() == connectButton) { callAddHost(); } this.dispose(); } public void itemStateChanged(ItemEvent e) { if(authChoice.getSelectedItem() == "(none)") { passwordField.enable(false); } else { passwordField.enable(true); } if(authChoice.getSelectedItem() == "MS-Logon") { usernameField.enable(true); } else { usernameField.enable(false); } } }
false
true
public AddHostDialog(VncThumbnailViewer tnviewer) { super(tnviewer, true); this.tnviewer = tnviewer; // GUI Stuff: setSize(250, 175); setResizable(false); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); setFont(new Font("Helvetica", Font.PLAIN, 14)); hostField = new TextField("", 10); portField = new TextField("5900", 10); usernameField = new TextField("", 10); usernameField.enable(false); // not needed by default passwordField = new TextField("", 10); passwordField.setEchoChar('*'); passwordField.enable(false); // not needed by default authChoice = new Choice(); authChoice.addItemListener(this); authChoice.add("(none)"); authChoice.add("Password"); authChoice.add("VNC Enc. Password"); authChoice.add("MS-Logon"); connectButton = new Button("Connect..."); cancelButton = new Button("Cancel"); connectButton.addActionListener(this); cancelButton.addActionListener(this); // End of Row Components: c.gridwidth = GridBagConstraints.REMAINDER; //end row gridbag.setConstraints(authChoice, c); gridbag.setConstraints(hostField, c); gridbag.setConstraints(portField, c); gridbag.setConstraints(usernameField, c); gridbag.setConstraints(passwordField, c); gridbag.setConstraints(connectButton, c); add(new Label("Host", Label.RIGHT)); add(hostField); add(new Label("Port", Label.RIGHT)); add(portField); add(new Label("Authentication:", Label.RIGHT)); add(authChoice); add(new Label("Username", Label.RIGHT)); add(usernameField); add(new Label("Password", Label.RIGHT)); add(passwordField); add(cancelButton); add(connectButton); //add(panel); validate(); setVisible(true); }
public AddHostDialog(VncThumbnailViewer tnviewer) { super(tnviewer, true); this.tnviewer = tnviewer; // GUI Stuff: setResizable(false); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); setFont(new Font("Helvetica", Font.PLAIN, 14)); hostField = new TextField("", 10); portField = new TextField("5900", 10); usernameField = new TextField("", 10); usernameField.enable(false); // not needed by default passwordField = new TextField("", 10); passwordField.setEchoChar('*'); passwordField.enable(false); // not needed by default authChoice = new Choice(); authChoice.addItemListener(this); authChoice.add("(none)"); authChoice.add("Password"); authChoice.add("VNC Enc. Password"); authChoice.add("MS-Logon"); connectButton = new Button("Connect..."); cancelButton = new Button("Cancel"); connectButton.addActionListener(this); cancelButton.addActionListener(this); // End of Row Components: c.gridwidth = GridBagConstraints.REMAINDER; //end row gridbag.setConstraints(authChoice, c); gridbag.setConstraints(hostField, c); gridbag.setConstraints(portField, c); gridbag.setConstraints(usernameField, c); gridbag.setConstraints(passwordField, c); gridbag.setConstraints(connectButton, c); add(new Label("Host", Label.RIGHT)); add(hostField); add(new Label("Port", Label.RIGHT)); add(portField); add(new Label("Authentication:", Label.RIGHT)); add(authChoice); add(new Label("Username", Label.RIGHT)); add(usernameField); add(new Label("Password", Label.RIGHT)); add(passwordField); add(cancelButton); add(connectButton); Point loc = tnviewer.getLocation(); Dimension dim = tnviewer.getSize(); loc.x += (dim.width/2)-50; loc.y += (dim.height/2)-50; setLocation(loc); pack(); validate(); setVisible(true); }
diff --git a/VisualizationModule/src/org/gephi/visualization/component/EdgeSettingsPanel.java b/VisualizationModule/src/org/gephi/visualization/component/EdgeSettingsPanel.java index 4127a503f..28e752eca 100644 --- a/VisualizationModule/src/org/gephi/visualization/component/EdgeSettingsPanel.java +++ b/VisualizationModule/src/org/gephi/visualization/component/EdgeSettingsPanel.java @@ -1,463 +1,464 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]> Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.visualization.component; import java.awt.Color; import java.awt.color.ColorSpace; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.gephi.ui.components.JColorButton; import org.gephi.visualization.VizController; import org.gephi.visualization.VizModel; /** * * @author Mathieu Bastian */ public class EdgeSettingsPanel extends javax.swing.JPanel { /** Creates new form EdgeSettingsPanel */ public EdgeSettingsPanel() { initComponents(); } public void setup() { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("init")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeHasUniColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("showEdges")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeUniColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeSelectionColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeInSelectionColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeOutSelectionColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeBothSelectionColor")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("edgeScale")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("metaEdgeScale")) { refreshSharedConfig(); } } }); refreshSharedConfig(); showEdgesCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setShowEdges(showEdgesCheckbox.isSelected()); setEnable(true); } }); ((JColorButton) edgeColorButton).addPropertyChangeListener(JColorButton.EVENT_COLOR, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeUniColor(((JColorButton) edgeColorButton).getColorArray()); } }); sourceNodeColorCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeHasUniColor(!sourceNodeColorCheckbox.isSelected()); } }); selectionColorCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeSelectionColor(selectionColorCheckbox.isSelected()); } }); edgeInSelectionColorChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeInSelectionColor(edgeInSelectionColorChooser.getColor().getComponents(null)); } }); edgeBothSelectionColorChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeBothSelectionColor(edgeBothSelectionColorChooser.getColor().getComponents(null)); } }); edgeOutSelectionColorChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setEdgeOutSelectionColor(edgeOutSelectionColorChooser.getColor().getComponents(null)); } }); scaleSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); if (vizModel.getEdgeScale() != (scaleSlider.getValue() / 10f + 0.1f)) { vizModel.setEdgeScale(scaleSlider.getValue() / 10f + 0.1f); } } }); metaScaleSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); int val = metaScaleSlider.getValue(); if (vizModel.getMetaEdgeScale() != (val / 50f + 0.0001f)) { vizModel.setMetaEdgeScale(val / 50f + 0.0001f); } } }); } private void refreshSharedConfig() { VizModel vizModel = VizController.getInstance().getVizModel(); setEnable(!vizModel.isDefaultModel()); if (vizModel.isDefaultModel()) { return; } if (showEdgesCheckbox.isSelected() != vizModel.isShowEdges()) { showEdgesCheckbox.setSelected(vizModel.isShowEdges()); } float[] edgeCol = vizModel.getEdgeUniColor(); ((JColorButton) edgeColorButton).setColor(new Color(edgeCol[0], edgeCol[1], edgeCol[2], edgeCol[3])); if (sourceNodeColorCheckbox.isSelected() != !vizModel.isEdgeHasUniColor()) { sourceNodeColorCheckbox.setSelected(!vizModel.isEdgeHasUniColor()); } if (selectionColorCheckbox.isSelected() != vizModel.isEdgeSelectionColor()) { selectionColorCheckbox.setSelected(vizModel.isEdgeSelectionColor()); } Color in = new Color(ColorSpace.getInstance(ColorSpace.CS_sRGB), vizModel.getEdgeInSelectionColor(), 1f); Color out = new Color(ColorSpace.getInstance(ColorSpace.CS_sRGB), vizModel.getEdgeOutSelectionColor(), 1f); Color both = new Color(ColorSpace.getInstance(ColorSpace.CS_sRGB), vizModel.getEdgeBothSelectionColor(), 1f); if (!edgeInSelectionColorChooser.getColor().equals(in)) { edgeInSelectionColorChooser.setColor(in); } if (!edgeBothSelectionColorChooser.getColor().equals(out)) { edgeBothSelectionColorChooser.setColor(out); } if (!edgeOutSelectionColorChooser.getColor().equals(both)) { edgeOutSelectionColorChooser.setColor(both); } if (scaleSlider.getValue() / 10f + 0.1f != vizModel.getEdgeScale()) { scaleSlider.setValue((int) ((vizModel.getEdgeScale() - 0.1f) * 10)); } if (metaScaleSlider.getValue() / 50f + 0.0001f != vizModel.getMetaEdgeScale()) { metaScaleSlider.setValue((int) ((vizModel.getMetaEdgeScale() - 0.0001f) * 50)); } } private void setEnable(boolean enable) { showEdgesCheckbox.setEnabled(enable); edgeColorButton.setEnabled(enable && showEdgesCheckbox.isSelected()); sourceNodeColorCheckbox.setEnabled(enable && showEdgesCheckbox.isSelected()); labelEdgeColor.setEnabled(enable && showEdgesCheckbox.isSelected()); scaleSlider.setEnabled(enable && showEdgesCheckbox.isSelected()); metaScaleSlider.setEnabled(enable && showEdgesCheckbox.isSelected()); labelScale.setEnabled(enable && showEdgesCheckbox.isSelected()); labelMetaScale.setEnabled(enable && showEdgesCheckbox.isSelected()); selectionColorCheckbox.setEnabled(enable && showEdgesCheckbox.isSelected()); edgeInSelectionColorChooser.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); edgeBothSelectionColorChooser.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); edgeOutSelectionColorChooser.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); labelIn.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); labelOut.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); labelBoth.setEnabled(enable && showEdgesCheckbox.isSelected() && selectionColorCheckbox.isSelected()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; showEdgesCheckbox = new javax.swing.JCheckBox(); labelEdgeColor = new javax.swing.JLabel(); edgeColorButton = new JColorButton(Color.BLACK); sourceNodeColorCheckbox = new javax.swing.JCheckBox(); selectionColorPanel = new javax.swing.JPanel(); selectionColorCheckbox = new javax.swing.JCheckBox(); edgeInSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeOutSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeBothSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); labelIn = new javax.swing.JLabel(); labelOut = new javax.swing.JLabel(); labelBoth = new javax.swing.JLabel(); scalePanel = new javax.swing.JPanel(); labelScale = new javax.swing.JLabel(); scaleSlider = new javax.swing.JSlider(); metaScalePanel = new javax.swing.JPanel(); labelMetaScale = new javax.swing.JLabel(); metaScaleSlider = new javax.swing.JSlider(); showEdgesCheckbox.setFont(new java.awt.Font("Tahoma", 1, 11)); showEdgesCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.showEdgesCheckbox.text")); // NOI18N labelEdgeColor.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelEdgeColor.text")); // NOI18N edgeColorButton.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeColorButton.text")); // NOI18N sourceNodeColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.sourceNodeColorCheckbox.text")); // NOI18N sourceNodeColorCheckbox.setBorder(null); sourceNodeColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setMargin(new java.awt.Insets(2, 0, 2, 2)); selectionColorPanel.setOpaque(false); selectionColorPanel.setLayout(new java.awt.GridBagLayout()); selectionColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.text")); // NOI18N selectionColorCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.toolTipText")); // NOI18N selectionColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); selectionColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); - selectionColorCheckbox.setMaximumSize(new java.awt.Dimension(150, 18)); - selectionColorCheckbox.setPreferredSize(new java.awt.Dimension(150, 18)); + selectionColorCheckbox.setMaximumSize(new java.awt.Dimension(160, 18)); + selectionColorCheckbox.setMinimumSize(new java.awt.Dimension(160, 18)); + selectionColorCheckbox.setPreferredSize(new java.awt.Dimension(160, 18)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; selectionColorPanel.add(selectionColorCheckbox, gridBagConstraints); edgeInSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeInSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeInSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeInSelectionColorChooser); edgeInSelectionColorChooser.setLayout(edgeInSelectionColorChooserLayout); edgeInSelectionColorChooserLayout.setHorizontalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeInSelectionColorChooserLayout.setVerticalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeInSelectionColorChooser, gridBagConstraints); edgeOutSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeOutSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeOutSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeOutSelectionColorChooser); edgeOutSelectionColorChooser.setLayout(edgeOutSelectionColorChooserLayout); edgeOutSelectionColorChooserLayout.setHorizontalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeOutSelectionColorChooserLayout.setVerticalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); selectionColorPanel.add(edgeOutSelectionColorChooser, gridBagConstraints); edgeBothSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeBothSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeBothSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeBothSelectionColorChooser); edgeBothSelectionColorChooser.setLayout(edgeBothSelectionColorChooserLayout); edgeBothSelectionColorChooserLayout.setHorizontalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeBothSelectionColorChooserLayout.setVerticalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeBothSelectionColorChooser, gridBagConstraints); labelIn.setFont(new java.awt.Font("Tahoma", 0, 10)); labelIn.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelIn.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); selectionColorPanel.add(labelIn, gridBagConstraints); labelOut.setFont(new java.awt.Font("Tahoma", 0, 10)); labelOut.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelOut.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 10, 0, 0); selectionColorPanel.add(labelOut, gridBagConstraints); labelBoth.setFont(new java.awt.Font("Tahoma", 0, 10)); labelBoth.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelBoth.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0); selectionColorPanel.add(labelBoth, gridBagConstraints); scalePanel.setOpaque(false); scalePanel.setLayout(new java.awt.GridBagLayout()); labelScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelScale.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); scalePanel.add(labelScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; scalePanel.add(scaleSlider, gridBagConstraints); metaScalePanel.setOpaque(false); metaScalePanel.setLayout(new java.awt.GridBagLayout()); labelMetaScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelMetaScale.text")); // NOI18N labelMetaScale.setMaximumSize(new java.awt.Dimension(136, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); metaScalePanel.add(labelMetaScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; metaScalePanel.add(metaScaleSlider, gridBagConstraints); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelEdgeColor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(sourceNodeColorCheckbox)) .addGap(28, 28, 28) .addComponent(scalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(selectionColorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(metaScalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(metaScalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox))) - .addContainerGap(10, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(labelEdgeColor)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(sourceNodeColorCheckbox)) .addComponent(scalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) - .addComponent(metaScalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) - .addComponent(selectionColorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)))) + .addComponent(selectionColorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) + .addComponent(metaScalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private net.java.dev.colorchooser.ColorChooser edgeBothSelectionColorChooser; private javax.swing.JButton edgeColorButton; private net.java.dev.colorchooser.ColorChooser edgeInSelectionColorChooser; private net.java.dev.colorchooser.ColorChooser edgeOutSelectionColorChooser; private javax.swing.JLabel labelBoth; private javax.swing.JLabel labelEdgeColor; private javax.swing.JLabel labelIn; private javax.swing.JLabel labelMetaScale; private javax.swing.JLabel labelOut; private javax.swing.JLabel labelScale; private javax.swing.JPanel metaScalePanel; private javax.swing.JSlider metaScaleSlider; private javax.swing.JPanel scalePanel; private javax.swing.JSlider scaleSlider; private javax.swing.JCheckBox selectionColorCheckbox; private javax.swing.JPanel selectionColorPanel; private javax.swing.JCheckBox showEdgesCheckbox; private javax.swing.JCheckBox sourceNodeColorCheckbox; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; showEdgesCheckbox = new javax.swing.JCheckBox(); labelEdgeColor = new javax.swing.JLabel(); edgeColorButton = new JColorButton(Color.BLACK); sourceNodeColorCheckbox = new javax.swing.JCheckBox(); selectionColorPanel = new javax.swing.JPanel(); selectionColorCheckbox = new javax.swing.JCheckBox(); edgeInSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeOutSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeBothSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); labelIn = new javax.swing.JLabel(); labelOut = new javax.swing.JLabel(); labelBoth = new javax.swing.JLabel(); scalePanel = new javax.swing.JPanel(); labelScale = new javax.swing.JLabel(); scaleSlider = new javax.swing.JSlider(); metaScalePanel = new javax.swing.JPanel(); labelMetaScale = new javax.swing.JLabel(); metaScaleSlider = new javax.swing.JSlider(); showEdgesCheckbox.setFont(new java.awt.Font("Tahoma", 1, 11)); showEdgesCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.showEdgesCheckbox.text")); // NOI18N labelEdgeColor.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelEdgeColor.text")); // NOI18N edgeColorButton.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeColorButton.text")); // NOI18N sourceNodeColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.sourceNodeColorCheckbox.text")); // NOI18N sourceNodeColorCheckbox.setBorder(null); sourceNodeColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setMargin(new java.awt.Insets(2, 0, 2, 2)); selectionColorPanel.setOpaque(false); selectionColorPanel.setLayout(new java.awt.GridBagLayout()); selectionColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.text")); // NOI18N selectionColorCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.toolTipText")); // NOI18N selectionColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); selectionColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); selectionColorCheckbox.setMaximumSize(new java.awt.Dimension(150, 18)); selectionColorCheckbox.setPreferredSize(new java.awt.Dimension(150, 18)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; selectionColorPanel.add(selectionColorCheckbox, gridBagConstraints); edgeInSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeInSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeInSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeInSelectionColorChooser); edgeInSelectionColorChooser.setLayout(edgeInSelectionColorChooserLayout); edgeInSelectionColorChooserLayout.setHorizontalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeInSelectionColorChooserLayout.setVerticalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeInSelectionColorChooser, gridBagConstraints); edgeOutSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeOutSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeOutSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeOutSelectionColorChooser); edgeOutSelectionColorChooser.setLayout(edgeOutSelectionColorChooserLayout); edgeOutSelectionColorChooserLayout.setHorizontalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeOutSelectionColorChooserLayout.setVerticalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); selectionColorPanel.add(edgeOutSelectionColorChooser, gridBagConstraints); edgeBothSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeBothSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeBothSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeBothSelectionColorChooser); edgeBothSelectionColorChooser.setLayout(edgeBothSelectionColorChooserLayout); edgeBothSelectionColorChooserLayout.setHorizontalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeBothSelectionColorChooserLayout.setVerticalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeBothSelectionColorChooser, gridBagConstraints); labelIn.setFont(new java.awt.Font("Tahoma", 0, 10)); labelIn.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelIn.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); selectionColorPanel.add(labelIn, gridBagConstraints); labelOut.setFont(new java.awt.Font("Tahoma", 0, 10)); labelOut.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelOut.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 10, 0, 0); selectionColorPanel.add(labelOut, gridBagConstraints); labelBoth.setFont(new java.awt.Font("Tahoma", 0, 10)); labelBoth.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelBoth.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0); selectionColorPanel.add(labelBoth, gridBagConstraints); scalePanel.setOpaque(false); scalePanel.setLayout(new java.awt.GridBagLayout()); labelScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelScale.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); scalePanel.add(labelScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; scalePanel.add(scaleSlider, gridBagConstraints); metaScalePanel.setOpaque(false); metaScalePanel.setLayout(new java.awt.GridBagLayout()); labelMetaScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelMetaScale.text")); // NOI18N labelMetaScale.setMaximumSize(new java.awt.Dimension(136, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); metaScalePanel.add(labelMetaScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; metaScalePanel.add(metaScaleSlider, gridBagConstraints); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelEdgeColor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(sourceNodeColorCheckbox)) .addGap(28, 28, 28) .addComponent(scalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(selectionColorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(metaScalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox))) .addContainerGap(10, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(labelEdgeColor)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(sourceNodeColorCheckbox)) .addComponent(scalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) .addComponent(metaScalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) .addComponent(selectionColorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; showEdgesCheckbox = new javax.swing.JCheckBox(); labelEdgeColor = new javax.swing.JLabel(); edgeColorButton = new JColorButton(Color.BLACK); sourceNodeColorCheckbox = new javax.swing.JCheckBox(); selectionColorPanel = new javax.swing.JPanel(); selectionColorCheckbox = new javax.swing.JCheckBox(); edgeInSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeOutSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); edgeBothSelectionColorChooser = new net.java.dev.colorchooser.ColorChooser(); labelIn = new javax.swing.JLabel(); labelOut = new javax.swing.JLabel(); labelBoth = new javax.swing.JLabel(); scalePanel = new javax.swing.JPanel(); labelScale = new javax.swing.JLabel(); scaleSlider = new javax.swing.JSlider(); metaScalePanel = new javax.swing.JPanel(); labelMetaScale = new javax.swing.JLabel(); metaScaleSlider = new javax.swing.JSlider(); showEdgesCheckbox.setFont(new java.awt.Font("Tahoma", 1, 11)); showEdgesCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.showEdgesCheckbox.text")); // NOI18N labelEdgeColor.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelEdgeColor.text")); // NOI18N edgeColorButton.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeColorButton.text")); // NOI18N sourceNodeColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.sourceNodeColorCheckbox.text")); // NOI18N sourceNodeColorCheckbox.setBorder(null); sourceNodeColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); sourceNodeColorCheckbox.setMargin(new java.awt.Insets(2, 0, 2, 2)); selectionColorPanel.setOpaque(false); selectionColorPanel.setLayout(new java.awt.GridBagLayout()); selectionColorCheckbox.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.text")); // NOI18N selectionColorCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.selectionColorCheckbox.toolTipText")); // NOI18N selectionColorCheckbox.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); selectionColorCheckbox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); selectionColorCheckbox.setMaximumSize(new java.awt.Dimension(160, 18)); selectionColorCheckbox.setMinimumSize(new java.awt.Dimension(160, 18)); selectionColorCheckbox.setPreferredSize(new java.awt.Dimension(160, 18)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; selectionColorPanel.add(selectionColorCheckbox, gridBagConstraints); edgeInSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeInSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeInSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeInSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeInSelectionColorChooser); edgeInSelectionColorChooser.setLayout(edgeInSelectionColorChooserLayout); edgeInSelectionColorChooserLayout.setHorizontalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeInSelectionColorChooserLayout.setVerticalGroup( edgeInSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeInSelectionColorChooser, gridBagConstraints); edgeOutSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeOutSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeOutSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeOutSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeOutSelectionColorChooser); edgeOutSelectionColorChooser.setLayout(edgeOutSelectionColorChooserLayout); edgeOutSelectionColorChooserLayout.setHorizontalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeOutSelectionColorChooserLayout.setVerticalGroup( edgeOutSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); selectionColorPanel.add(edgeOutSelectionColorChooser, gridBagConstraints); edgeBothSelectionColorChooser.setMinimumSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setPreferredSize(new java.awt.Dimension(14, 14)); edgeBothSelectionColorChooser.setToolTipText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.edgeBothSelectionColorChooser.toolTipText")); // NOI18N javax.swing.GroupLayout edgeBothSelectionColorChooserLayout = new javax.swing.GroupLayout(edgeBothSelectionColorChooser); edgeBothSelectionColorChooser.setLayout(edgeBothSelectionColorChooserLayout); edgeBothSelectionColorChooserLayout.setHorizontalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); edgeBothSelectionColorChooserLayout.setVerticalGroup( edgeBothSelectionColorChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 12, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); selectionColorPanel.add(edgeBothSelectionColorChooser, gridBagConstraints); labelIn.setFont(new java.awt.Font("Tahoma", 0, 10)); labelIn.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelIn.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); selectionColorPanel.add(labelIn, gridBagConstraints); labelOut.setFont(new java.awt.Font("Tahoma", 0, 10)); labelOut.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelOut.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 10, 0, 0); selectionColorPanel.add(labelOut, gridBagConstraints); labelBoth.setFont(new java.awt.Font("Tahoma", 0, 10)); labelBoth.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelBoth.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0); selectionColorPanel.add(labelBoth, gridBagConstraints); scalePanel.setOpaque(false); scalePanel.setLayout(new java.awt.GridBagLayout()); labelScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelScale.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); scalePanel.add(labelScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; scalePanel.add(scaleSlider, gridBagConstraints); metaScalePanel.setOpaque(false); metaScalePanel.setLayout(new java.awt.GridBagLayout()); labelMetaScale.setText(org.openide.util.NbBundle.getMessage(EdgeSettingsPanel.class, "EdgeSettingsPanel.labelMetaScale.text")); // NOI18N labelMetaScale.setMaximumSize(new java.awt.Dimension(136, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(3, 5, 2, 0); metaScalePanel.add(labelMetaScale, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; metaScalePanel.add(metaScaleSlider, gridBagConstraints); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelEdgeColor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(sourceNodeColorCheckbox)) .addGap(28, 28, 28) .addComponent(scalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(selectionColorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(metaScalePanel, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(showEdgesCheckbox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(labelEdgeColor)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(edgeColorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(sourceNodeColorCheckbox)) .addComponent(scalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) .addComponent(selectionColorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE) .addComponent(metaScalePanel, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)))) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/com/hasgeek/funnel/misc/SessionsListLoader.java b/src/com/hasgeek/funnel/misc/SessionsListLoader.java index 6d249fa..12c5753 100644 --- a/src/com/hasgeek/funnel/misc/SessionsListLoader.java +++ b/src/com/hasgeek/funnel/misc/SessionsListLoader.java @@ -1,174 +1,174 @@ package com.hasgeek.funnel.misc; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v4.content.AsyncTaskLoader; import com.hasgeek.funnel.fragment.SessionsListFragment; import java.util.ArrayList; import java.util.List; public class SessionsListLoader extends AsyncTaskLoader<List<EventSessionRow>> { private SQLiteDatabase mDatabase; private List<EventSessionRow> mData; private int mMode; public SessionsListLoader(Context context, int mode) { super(context); mDatabase = DBManager.getInstance(context).getWritableDatabase(); mMode = mode; } @Override public List<EventSessionRow> loadInBackground() { List<EventSession> esList = new ArrayList<EventSession>(); Cursor sessions; if (mMode == SessionsListFragment.All_SESSIONS) { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + - "ORDER BY s.date_ist ASC", + "ORDER BY s.date_ist, s.slot_ist", null); } else { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + "WHERE s.bookmarked = ? " + - "ORDER BY s.date_ist ASC", + "ORDER BY s.date_ist, s.slot_ist", new String[] { "true" }); } if (sessions.moveToFirst()) { do { boolean bookmarkState = false; if (!sessions.isNull(sessions.getColumnIndex("bookmarked"))) { bookmarkState = sessions.getString(sessions.getColumnIndex("bookmarked")).equals("true"); } EventSession es = new EventSession( sessions.getString(sessions.getColumnIndex("id")), sessions.getString(sessions.getColumnIndex("title")), sessions.getString(sessions.getColumnIndex("speaker")), sessions.getString(sessions.getColumnIndex("section")), sessions.getString(sessions.getColumnIndex("level")), sessions.getString(sessions.getColumnIndex("description")), sessions.getString(sessions.getColumnIndex("url")), sessions.getString(sessions.getColumnIndex("date_ist")), sessions.getString(sessions.getColumnIndex("slot_ist")), sessions.getString(sessions.getColumnIndex("roomtitle")), sessions.getString(sessions.getColumnIndex("bgcolor")), bookmarkState ); esList.add(es); } while (sessions.moveToNext()); } sessions.close(); List<EventSessionRow> list = new ArrayList<EventSessionRow>(); String oldDate = esList.get(0).getDateInIst(); String oldSlotTime = esList.get(0).getSlotInIst24Hrs(); List<EventSession> temp = new ArrayList<EventSession>(); for (EventSession e : esList) { if (e.getDateInIst().equals(oldDate) && e.getSlotInIst24Hrs().equals(oldSlotTime)) { temp.add(e); } else { // First, save current row slot EventSessionRow row = new EventSessionRow(oldDate, oldSlotTime, temp); list.add(row); temp = new ArrayList<EventSession>(); // Then, start a new row oldDate = e.getDateInIst(); oldSlotTime = e.getSlotInIst24Hrs(); temp.add(e); } } return list; } @Override public void deliverResult(List<EventSessionRow> data) { if (isReset()) { releaseResources(data); return; } // Hold a reference to the old data so it doesn't get garbage collected. // The old data may still be in use (i.e. bound to an adapter, etc.), so // we must protect it until the new data has been delivered. List<EventSessionRow> oldData = mData; mData = data; if (isStarted()) { super.deliverResult(data); } // Invalidate the old data as we don't need it any more. if (oldData != null && oldData != data) { releaseResources(oldData); } } @Override protected void onStartLoading() { if (mData != null) { deliverResult(mData); } if (takeContentChanged() || mData == null) { forceLoad(); } } @Override protected void onStopLoading() { // The Loader is in a stopped state, so we should attempt to cancel the // current load (if there is one). cancelLoad(); // Note that we leave the observer as is; Loaders in a stopped state // should still monitor the data source for changes so that the Loader // will know to force a new load if it is ever started again. } @Override protected void onReset() { // Ensure the loader has been stopped. onStopLoading(); // At this point we can release the resources associated with 'mData'. if (mData != null) { releaseResources(mData); mData = null; } } @Override public void onCanceled(List<EventSessionRow> data) { super.onCanceled(data); releaseResources(data); } private void releaseResources(List<EventSessionRow> data) { // For a simple List, there is nothing to do. For something like a Cursor, we // would close it in this method. All resources associated with the Loader // should be released here. } }
false
true
public List<EventSessionRow> loadInBackground() { List<EventSession> esList = new ArrayList<EventSession>(); Cursor sessions; if (mMode == SessionsListFragment.All_SESSIONS) { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + "ORDER BY s.date_ist ASC", null); } else { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + "WHERE s.bookmarked = ? " + "ORDER BY s.date_ist ASC", new String[] { "true" }); } if (sessions.moveToFirst()) { do { boolean bookmarkState = false; if (!sessions.isNull(sessions.getColumnIndex("bookmarked"))) { bookmarkState = sessions.getString(sessions.getColumnIndex("bookmarked")).equals("true"); } EventSession es = new EventSession( sessions.getString(sessions.getColumnIndex("id")), sessions.getString(sessions.getColumnIndex("title")), sessions.getString(sessions.getColumnIndex("speaker")), sessions.getString(sessions.getColumnIndex("section")), sessions.getString(sessions.getColumnIndex("level")), sessions.getString(sessions.getColumnIndex("description")), sessions.getString(sessions.getColumnIndex("url")), sessions.getString(sessions.getColumnIndex("date_ist")), sessions.getString(sessions.getColumnIndex("slot_ist")), sessions.getString(sessions.getColumnIndex("roomtitle")), sessions.getString(sessions.getColumnIndex("bgcolor")), bookmarkState ); esList.add(es); } while (sessions.moveToNext()); } sessions.close(); List<EventSessionRow> list = new ArrayList<EventSessionRow>(); String oldDate = esList.get(0).getDateInIst(); String oldSlotTime = esList.get(0).getSlotInIst24Hrs(); List<EventSession> temp = new ArrayList<EventSession>(); for (EventSession e : esList) { if (e.getDateInIst().equals(oldDate) && e.getSlotInIst24Hrs().equals(oldSlotTime)) { temp.add(e); } else { // First, save current row slot EventSessionRow row = new EventSessionRow(oldDate, oldSlotTime, temp); list.add(row); temp = new ArrayList<EventSession>(); // Then, start a new row oldDate = e.getDateInIst(); oldSlotTime = e.getSlotInIst24Hrs(); temp.add(e); } } return list; }
public List<EventSessionRow> loadInBackground() { List<EventSession> esList = new ArrayList<EventSession>(); Cursor sessions; if (mMode == SessionsListFragment.All_SESSIONS) { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + "ORDER BY s.date_ist, s.slot_ist", null); } else { sessions = mDatabase.rawQuery( "SELECT s.id, s.title, s.speaker, s.section, s.level, s.description, s.url, s.bookmarked, s.date_ist, s.slot_ist, " + "r.title as roomtitle, r.bgcolor " + "FROM sessions s " + "LEFT JOIN rooms r on s.room = r.name " + "WHERE s.bookmarked = ? " + "ORDER BY s.date_ist, s.slot_ist", new String[] { "true" }); } if (sessions.moveToFirst()) { do { boolean bookmarkState = false; if (!sessions.isNull(sessions.getColumnIndex("bookmarked"))) { bookmarkState = sessions.getString(sessions.getColumnIndex("bookmarked")).equals("true"); } EventSession es = new EventSession( sessions.getString(sessions.getColumnIndex("id")), sessions.getString(sessions.getColumnIndex("title")), sessions.getString(sessions.getColumnIndex("speaker")), sessions.getString(sessions.getColumnIndex("section")), sessions.getString(sessions.getColumnIndex("level")), sessions.getString(sessions.getColumnIndex("description")), sessions.getString(sessions.getColumnIndex("url")), sessions.getString(sessions.getColumnIndex("date_ist")), sessions.getString(sessions.getColumnIndex("slot_ist")), sessions.getString(sessions.getColumnIndex("roomtitle")), sessions.getString(sessions.getColumnIndex("bgcolor")), bookmarkState ); esList.add(es); } while (sessions.moveToNext()); } sessions.close(); List<EventSessionRow> list = new ArrayList<EventSessionRow>(); String oldDate = esList.get(0).getDateInIst(); String oldSlotTime = esList.get(0).getSlotInIst24Hrs(); List<EventSession> temp = new ArrayList<EventSession>(); for (EventSession e : esList) { if (e.getDateInIst().equals(oldDate) && e.getSlotInIst24Hrs().equals(oldSlotTime)) { temp.add(e); } else { // First, save current row slot EventSessionRow row = new EventSessionRow(oldDate, oldSlotTime, temp); list.add(row); temp = new ArrayList<EventSession>(); // Then, start a new row oldDate = e.getDateInIst(); oldSlotTime = e.getSlotInIst24Hrs(); temp.add(e); } } return list; }
diff --git a/src/webserviceclient/WebServiceClientImpl.java b/src/webserviceclient/WebServiceClientImpl.java index b105d56..97249e2 100644 --- a/src/webserviceclient/WebServiceClientImpl.java +++ b/src/webserviceclient/WebServiceClientImpl.java @@ -1,102 +1,102 @@ package webserviceclient; 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.Random; import java.util.Set; import mediator.MediatorWebServiceClient; import model.service.Service; import model.service.ServiceImpl; import model.user.Buyer; import model.user.Manufacturer; import model.user.User; /** * Implements {@link WebServiceClient}. * * @author cmihail, radu-tutueanu */ public class WebServiceClientImpl implements WebServiceClient { private final MediatorWebServiceClient mediator; public WebServiceClientImpl(MediatorWebServiceClient mediator) { this.mediator = mediator; } @Override public Map<Service, Set<User>> login(User user, String password) { // TODO login to WebService try { Thread.sleep(500); // TODO delete (only for testing) } catch (InterruptedException e) { e.printStackTrace(); System.exit(1); } // Create mockup data. Map<Service, Set<User>> mapServiceUsers = new HashMap<Service, Set<User>>(); Random random = new Random(); // Randomize users. Set<User> users = new HashSet<User>(); int numOfUsers = random.nextInt(user.getServices().size()) + 2; // minimum 2 users for (int i = 0; i < numOfUsers; i++) { int numOfServices = random.nextInt(user.getServices().size() - 1); numOfServices++; // minimum 1 service int order = random.nextInt(2), limit = 0; if (order == 0) limit = user.getServices().size() - 1; List<Service> services = new ArrayList<Service>(); for (int j = 0; j < numOfServices; j++) { int index = Math.abs(j - limit); services.add(new ServiceImpl(user.getServices().get(index).getName())); } switch (user.getType()) { case BUYER: - users.add(new Buyer("Username " + i, services)); + users.add(new Manufacturer("Username " + i, services)); break; case MANUFACTURER: - users.add(new Manufacturer("Username " + i, services)); + users.add(new Buyer("Username " + i, services)); break; } } Iterator<Service> it = user.getServices().iterator(); while (it.hasNext()) { Service service = it.next(); Set<User> serviceUsers = new HashSet<User>(); Iterator<User> usersIt = users.iterator(); while (usersIt.hasNext()) { User u = usersIt.next(); Iterator<Service> serviceIt = u.getServices().iterator(); while (serviceIt.hasNext()) { Service s = serviceIt.next(); if (service.getName().equals(s.getName())) { serviceUsers.add(u); } } } mapServiceUsers.put(service, serviceUsers); } return mapServiceUsers; } @Override public void logout(User user) { // TODO logout user from WebService } }
false
true
public Map<Service, Set<User>> login(User user, String password) { // TODO login to WebService try { Thread.sleep(500); // TODO delete (only for testing) } catch (InterruptedException e) { e.printStackTrace(); System.exit(1); } // Create mockup data. Map<Service, Set<User>> mapServiceUsers = new HashMap<Service, Set<User>>(); Random random = new Random(); // Randomize users. Set<User> users = new HashSet<User>(); int numOfUsers = random.nextInt(user.getServices().size()) + 2; // minimum 2 users for (int i = 0; i < numOfUsers; i++) { int numOfServices = random.nextInt(user.getServices().size() - 1); numOfServices++; // minimum 1 service int order = random.nextInt(2), limit = 0; if (order == 0) limit = user.getServices().size() - 1; List<Service> services = new ArrayList<Service>(); for (int j = 0; j < numOfServices; j++) { int index = Math.abs(j - limit); services.add(new ServiceImpl(user.getServices().get(index).getName())); } switch (user.getType()) { case BUYER: users.add(new Buyer("Username " + i, services)); break; case MANUFACTURER: users.add(new Manufacturer("Username " + i, services)); break; } } Iterator<Service> it = user.getServices().iterator(); while (it.hasNext()) { Service service = it.next(); Set<User> serviceUsers = new HashSet<User>(); Iterator<User> usersIt = users.iterator(); while (usersIt.hasNext()) { User u = usersIt.next(); Iterator<Service> serviceIt = u.getServices().iterator(); while (serviceIt.hasNext()) { Service s = serviceIt.next(); if (service.getName().equals(s.getName())) { serviceUsers.add(u); } } } mapServiceUsers.put(service, serviceUsers); } return mapServiceUsers; }
public Map<Service, Set<User>> login(User user, String password) { // TODO login to WebService try { Thread.sleep(500); // TODO delete (only for testing) } catch (InterruptedException e) { e.printStackTrace(); System.exit(1); } // Create mockup data. Map<Service, Set<User>> mapServiceUsers = new HashMap<Service, Set<User>>(); Random random = new Random(); // Randomize users. Set<User> users = new HashSet<User>(); int numOfUsers = random.nextInt(user.getServices().size()) + 2; // minimum 2 users for (int i = 0; i < numOfUsers; i++) { int numOfServices = random.nextInt(user.getServices().size() - 1); numOfServices++; // minimum 1 service int order = random.nextInt(2), limit = 0; if (order == 0) limit = user.getServices().size() - 1; List<Service> services = new ArrayList<Service>(); for (int j = 0; j < numOfServices; j++) { int index = Math.abs(j - limit); services.add(new ServiceImpl(user.getServices().get(index).getName())); } switch (user.getType()) { case BUYER: users.add(new Manufacturer("Username " + i, services)); break; case MANUFACTURER: users.add(new Buyer("Username " + i, services)); break; } } Iterator<Service> it = user.getServices().iterator(); while (it.hasNext()) { Service service = it.next(); Set<User> serviceUsers = new HashSet<User>(); Iterator<User> usersIt = users.iterator(); while (usersIt.hasNext()) { User u = usersIt.next(); Iterator<Service> serviceIt = u.getServices().iterator(); while (serviceIt.hasNext()) { Service s = serviceIt.next(); if (service.getName().equals(s.getName())) { serviceUsers.add(u); } } } mapServiceUsers.put(service, serviceUsers); } return mapServiceUsers; }
diff --git a/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilder.java b/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilder.java index 5b195d2aa..8460061a4 100644 --- a/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilder.java +++ b/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilder.java @@ -1,183 +1,185 @@ package org.apache.maven.continuum.project.builder.maven; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.net.URL; import java.util.List; import org.apache.maven.continuum.builddefinition.BuildDefinitionService; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.execution.maven.m1.MavenOneBuildExecutor; import org.apache.maven.continuum.execution.maven.m1.MavenOneMetadataHelper; import org.apache.maven.continuum.execution.maven.m1.MavenOneMetadataHelperException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.builder.AbstractContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.codehaus.plexus.util.StringUtils; /** * @author <a href="mailto:[email protected]">Trygve Laugst&oslash;l</a> * @version $Id$ * @plexus.component role="org.apache.maven.continuum.project.builder.ContinuumProjectBuilder" * role-hint="maven-one-builder" */ public class MavenOneContinuumProjectBuilder extends AbstractContinuumProjectBuilder implements ContinuumProjectBuilder { public static final String ID = "maven-one-builder"; /** * @plexus.requirement */ private BuildDefinitionService buildDefinitionService; /** * @plexus.requirement */ private MavenOneMetadataHelper metadataHelper; // ---------------------------------------------------------------------- // ProjectCreator Implementation // ---------------------------------------------------------------------- public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password ) throws ContinuumProjectBuilderException { return buildProjectsFromMetadata( url, username, password, true ); } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects ) throws ContinuumProjectBuilderException { try { return buildProjectsFromMetadata( url, username, password, recursiveProjects, buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate() ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate ) throws ContinuumProjectBuilderException { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); File pomFile; pomFile = createMetadataFile( result, url, username, password ); if ( pomFile == null ) { return result; } Project project = new Project(); try { metadataHelper.mapMetadata( result, pomFile, project ); if ( result.hasErrors() ) { return result; } for ( BuildDefinition bd : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() ) { - project.addBuildDefinition( bd ); + BuildDefinition cloneBuildDefinition = buildDefinitionService.cloneBuildDefinition( bd ); + cloneBuildDefinition.setTemplate( false ); + project.addBuildDefinition( cloneBuildDefinition ); } result.addProject( project, MavenOneBuildExecutor.ID ); } catch ( MavenOneMetadataHelperException e ) { log.error( "Unknown error while processing metadata", e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } finally { if ( pomFile.exists() ) { pomFile.delete(); } } ProjectGroup projectGroup = new ProjectGroup(); // ---------------------------------------------------------------------- // Group id // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( project.getGroupId() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); } projectGroup.setGroupId( project.getGroupId() ); // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { name = project.getGroupId(); } projectGroup.setName( name ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- projectGroup.setDescription( project.getDescription() ); result.addProjectGroup( projectGroup ); return result; } public BuildDefinitionTemplate getDefaultBuildDefinitionTemplate() throws ContinuumProjectBuilderException { try { return buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate(); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } }
true
true
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate ) throws ContinuumProjectBuilderException { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); File pomFile; pomFile = createMetadataFile( result, url, username, password ); if ( pomFile == null ) { return result; } Project project = new Project(); try { metadataHelper.mapMetadata( result, pomFile, project ); if ( result.hasErrors() ) { return result; } for ( BuildDefinition bd : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() ) { project.addBuildDefinition( bd ); } result.addProject( project, MavenOneBuildExecutor.ID ); } catch ( MavenOneMetadataHelperException e ) { log.error( "Unknown error while processing metadata", e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } finally { if ( pomFile.exists() ) { pomFile.delete(); } } ProjectGroup projectGroup = new ProjectGroup(); // ---------------------------------------------------------------------- // Group id // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( project.getGroupId() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); } projectGroup.setGroupId( project.getGroupId() ); // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { name = project.getGroupId(); } projectGroup.setName( name ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- projectGroup.setDescription( project.getDescription() ); result.addProjectGroup( projectGroup ); return result; }
public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate ) throws ContinuumProjectBuilderException { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); File pomFile; pomFile = createMetadataFile( result, url, username, password ); if ( pomFile == null ) { return result; } Project project = new Project(); try { metadataHelper.mapMetadata( result, pomFile, project ); if ( result.hasErrors() ) { return result; } for ( BuildDefinition bd : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() ) { BuildDefinition cloneBuildDefinition = buildDefinitionService.cloneBuildDefinition( bd ); cloneBuildDefinition.setTemplate( false ); project.addBuildDefinition( cloneBuildDefinition ); } result.addProject( project, MavenOneBuildExecutor.ID ); } catch ( MavenOneMetadataHelperException e ) { log.error( "Unknown error while processing metadata", e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } finally { if ( pomFile.exists() ) { pomFile.delete(); } } ProjectGroup projectGroup = new ProjectGroup(); // ---------------------------------------------------------------------- // Group id // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( project.getGroupId() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); } projectGroup.setGroupId( project.getGroupId() ); // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { name = project.getGroupId(); } projectGroup.setName( name ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- projectGroup.setDescription( project.getDescription() ); result.addProjectGroup( projectGroup ); return result; }
diff --git a/aufgabe2/Square.java b/aufgabe2/Square.java index 8a12a7b..42d19b3 100644 --- a/aufgabe2/Square.java +++ b/aufgabe2/Square.java @@ -1,86 +1,86 @@ /** * * Represents a square * @author Grupppe 5 * */ public class Square { /** * the width of the square */ private double width; /** * the bottom left corner of the square * bottom right corner * top right corner * top left corner */ private Point blc; private Point brc; private Point trc; private Point tlc; /** * creates a square with its bottom left corner at (0,0) and a width of 1 * * blc = bottom left corner * brc = bottom right corner * trc = top right corner * tlc = top left corner */ public Square() { this.blc = new Point(0,0); this.brc = new Point(1,0); this.trc = new Point(1,1); this.tlc = new Point(0,1); this.width = 1.0; } /** * constructs a square with the given parameters * @param p the point in the bottom left corner of the square * @param w is the edge length * * */ public Square(Point p, double w) { this.width = w; this.blc = new Point(p.getX(), p.getY()); - this.brc = new Point(p.getX(), p.getY()); - this.trc = new Point(p.getX(), p.getY()); - this.tlc = new Point(p.getX(), p.getY()); + this.brc = new Point(p.getX()+w, p.getY()); + this.trc = new Point(p.getX()+w, p.getY()+w); + this.tlc = new Point(p.getX(), p.getY()+w); } /** * Move this square to a new position. * @param dx the distance from current position in x direction * @param dy the distance from current position in y direction */ public void shift(double dx, double dy) { this.blc.shift(dx, dy); this.brc.shift(dx, dy); this.trc.shift(dx, dy); this.tlc.shift(dx, dy); } /** * * @return a line from the bottom left corner of the square to the bottom right corner */ public Line getBottomLine() { return new Line(blc, new Point(blc.getX() + width, blc.getY())); } /** * * @return a string with the coordinates of the bottom left corner * and the edge length */ @Override public String toString() { return "<Square> bottom left corner: " + this.blc.toString() + " - width: " + this.width; } }
true
true
public Square(Point p, double w) { this.width = w; this.blc = new Point(p.getX(), p.getY()); this.brc = new Point(p.getX(), p.getY()); this.trc = new Point(p.getX(), p.getY()); this.tlc = new Point(p.getX(), p.getY()); }
public Square(Point p, double w) { this.width = w; this.blc = new Point(p.getX(), p.getY()); this.brc = new Point(p.getX()+w, p.getY()); this.trc = new Point(p.getX()+w, p.getY()+w); this.tlc = new Point(p.getX(), p.getY()+w); }
diff --git a/src/net/canarymod/hook/player/KickDelegate.java b/src/net/canarymod/hook/player/KickDelegate.java index 5d094e6..d2d2d18 100644 --- a/src/net/canarymod/hook/player/KickDelegate.java +++ b/src/net/canarymod/hook/player/KickDelegate.java @@ -1,18 +1,18 @@ package net.canarymod.hook.player; import net.canarymod.hook.Hook; import net.canarymod.hook.HookDelegate; /** * The delegate for {@link LoginHook} * @author Chris Ksoll * */ public class KickDelegate extends HookDelegate { @Override public Hook callHook(Hook hook) { - return this.li.onLogin((LoginHook)hook); + return this.li.onKick((KickHook)hook); } }
true
true
public Hook callHook(Hook hook) { return this.li.onLogin((LoginHook)hook); }
public Hook callHook(Hook hook) { return this.li.onKick((KickHook)hook); }
diff --git a/shivas-server/src/main/java/org/shivas/server/database/repositories/AccountRepository.java b/shivas-server/src/main/java/org/shivas/server/database/repositories/AccountRepository.java index 7d518fb..46cc28a 100644 --- a/shivas-server/src/main/java/org/shivas/server/database/repositories/AccountRepository.java +++ b/shivas-server/src/main/java/org/shivas/server/database/repositories/AccountRepository.java @@ -1,130 +1,130 @@ package org.shivas.server.database.repositories; import java.security.NoSuchAlgorithmException; import java.sql.ResultSet; import java.sql.SQLException; import javax.inject.Inject; import javax.inject.Singleton; import org.atomium.EntityManager; import org.atomium.repository.EntityRepository; import org.atomium.repository.impl.AbstractLiveEntityRepository; import org.atomium.util.Filter; import org.atomium.util.query.Op; import org.atomium.util.query.Query; import org.atomium.util.query.SelectQueryBuilder; import org.atomium.util.query.UpdateQueryBuilder; import org.joda.time.DateTime; import org.shivas.common.collections.Maps2; import org.shivas.common.crypto.Cipher; import org.shivas.common.crypto.Sha1Cipher; import org.shivas.protocol.client.enums.Channel; import org.shivas.server.core.ChannelList; import org.shivas.server.database.models.Account; import org.shivas.server.database.models.Player; import org.shivas.server.utils.Converters; @Singleton public class AccountRepository extends AbstractLiveEntityRepository<Integer, Account> { public static final String TABLE_NAME = "accounts"; private SelectQueryBuilder loadByIdQuery, loadByNameQuery; private UpdateQueryBuilder saveQuery; private EntityRepository<Integer, Player> players; @Inject public AccountRepository(EntityManager em, EntityRepository<Integer, Player> players) { super(em); this.players = players; this.loadByIdQuery = em.builder().select(TABLE_NAME).where("id", Op.EQ); this.loadByNameQuery = em.builder().select(TABLE_NAME).where("name", Op.EQ); this.saveQuery = em.builder() .update(TABLE_NAME) .value("rights").value("banned") .value("points").value("connected").value("channels") .value("last_connection").value("last_address").value("nb_connections") .where("id", Op.EQ); } public Cipher passwordCipher() { try { return new Sha1Cipher(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // MUST NOT HAPPEN return null; } } public Account find(String name) { Query query = loadByNameQuery.toQuery(); query.setParameter("name", name); return find(query); } @Override protected Query buildLoadQuery(Integer pk) { Query query = loadByIdQuery.toQuery(); query.setParameter("id", pk); return query; } @Override protected Query buildSaveQuery(Account entity) { Query query = saveQuery.toQuery(); query.setParameter("id", entity.id()); query.setParameter("rights", entity.hasRights()); query.setParameter("banned", entity.isBanned()); query.setParameter("points", entity.getPoints()); query.setParameter("connected", entity.isConnected()); query.setParameter("channels", entity.getChannels()); query.setParameter("last_connection", entity.getLastConnection()); query.setParameter("last_address", entity.getLastAddress()); query.setParameter("nb_connections", entity.getNbConnections()); return query; } @Override protected Account load(ResultSet result) throws SQLException { final int id = result.getInt("id"); Account account = new Account( id, 0, result.getString("name"), result.getString("password"), result.getString("nickname"), result.getString("question"), result.getString("answer"), result.getBoolean("rights"), result.getBoolean("banned"), result.getInt("community"), result.getInt("points"), - new DateTime(result.getDate("subscription_end")), + em.builder().dateTimeFormatter().parseDateTime(result.getString("subscription_end")), result.getBoolean("connected"), ChannelList.parseChannelList(result.getString("channels")), - new DateTime(result.getDate("last_connection")), + em.builder().dateTimeFormatter().parseDateTime(result.getString("last_connection")), result.getString("last_address"), result.getInt("nb_connections"), Maps2.toMap(this.players.filter(new Filter<Player>() { public Boolean invoke(Player arg1) throws Exception { return arg1.getOwnerReference().getPk() == id; } }), Converters.PLAYER_TO_ID) ); if (account.hasRights() && !account.getChannels().contains(Channel.Admin)) { account.getChannels().add(Channel.Admin); } return account; } }
false
true
protected Account load(ResultSet result) throws SQLException { final int id = result.getInt("id"); Account account = new Account( id, 0, result.getString("name"), result.getString("password"), result.getString("nickname"), result.getString("question"), result.getString("answer"), result.getBoolean("rights"), result.getBoolean("banned"), result.getInt("community"), result.getInt("points"), new DateTime(result.getDate("subscription_end")), result.getBoolean("connected"), ChannelList.parseChannelList(result.getString("channels")), new DateTime(result.getDate("last_connection")), result.getString("last_address"), result.getInt("nb_connections"), Maps2.toMap(this.players.filter(new Filter<Player>() { public Boolean invoke(Player arg1) throws Exception { return arg1.getOwnerReference().getPk() == id; } }), Converters.PLAYER_TO_ID) ); if (account.hasRights() && !account.getChannels().contains(Channel.Admin)) { account.getChannels().add(Channel.Admin); } return account; }
protected Account load(ResultSet result) throws SQLException { final int id = result.getInt("id"); Account account = new Account( id, 0, result.getString("name"), result.getString("password"), result.getString("nickname"), result.getString("question"), result.getString("answer"), result.getBoolean("rights"), result.getBoolean("banned"), result.getInt("community"), result.getInt("points"), em.builder().dateTimeFormatter().parseDateTime(result.getString("subscription_end")), result.getBoolean("connected"), ChannelList.parseChannelList(result.getString("channels")), em.builder().dateTimeFormatter().parseDateTime(result.getString("last_connection")), result.getString("last_address"), result.getInt("nb_connections"), Maps2.toMap(this.players.filter(new Filter<Player>() { public Boolean invoke(Player arg1) throws Exception { return arg1.getOwnerReference().getPk() == id; } }), Converters.PLAYER_TO_ID) ); if (account.hasRights() && !account.getChannels().contains(Channel.Admin)) { account.getChannels().add(Channel.Admin); } return account; }
diff --git a/levi-webapp/src/main/java/org/levi/web/TaskActionServlet.java b/levi-webapp/src/main/java/org/levi/web/TaskActionServlet.java index 268fd34..8b35ba9 100644 --- a/levi-webapp/src/main/java/org/levi/web/TaskActionServlet.java +++ b/levi-webapp/src/main/java/org/levi/web/TaskActionServlet.java @@ -1,43 +1,43 @@ package org.levi.web; import org.levi.engine.db.DBManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: umashanthi * Date: 5/24/11 * Time: 10:56 AM * To change this template use File | Settings | File Templates. */ public class TaskActionServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); assert action != null; if (action.equals("claimTask")) { assert request.getParameter("username") != null; String username = request.getParameter("username"); assert request.getParameter("taskId") != null; - String taskId = request.getParameter("taksId"); + String taskId = request.getParameter("taskId"); assert request.getParameter("processInstanceId") != null; String processInstanceId = request.getParameter("processInstanceId"); assert request.getSession().getAttribute("dbManager") != null; DBManager dbManager = (DBManager) request.getSession().getAttribute("dbManager"); dbManager.claimUserTask(taskId, processInstanceId, username); response.sendRedirect("tasks"); } else { //other task actions should be handled here } } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); assert action != null; if (action.equals("claimTask")) { assert request.getParameter("username") != null; String username = request.getParameter("username"); assert request.getParameter("taskId") != null; String taskId = request.getParameter("taksId"); assert request.getParameter("processInstanceId") != null; String processInstanceId = request.getParameter("processInstanceId"); assert request.getSession().getAttribute("dbManager") != null; DBManager dbManager = (DBManager) request.getSession().getAttribute("dbManager"); dbManager.claimUserTask(taskId, processInstanceId, username); response.sendRedirect("tasks"); } else { //other task actions should be handled here } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); assert action != null; if (action.equals("claimTask")) { assert request.getParameter("username") != null; String username = request.getParameter("username"); assert request.getParameter("taskId") != null; String taskId = request.getParameter("taskId"); assert request.getParameter("processInstanceId") != null; String processInstanceId = request.getParameter("processInstanceId"); assert request.getSession().getAttribute("dbManager") != null; DBManager dbManager = (DBManager) request.getSession().getAttribute("dbManager"); dbManager.claimUserTask(taskId, processInstanceId, username); response.sendRedirect("tasks"); } else { //other task actions should be handled here } }
diff --git a/src/main/java/org/guanxi/sp/engine/service/saml2/SAML2ProfileService.java b/src/main/java/org/guanxi/sp/engine/service/saml2/SAML2ProfileService.java index 7041964..0f26d6a 100644 --- a/src/main/java/org/guanxi/sp/engine/service/saml2/SAML2ProfileService.java +++ b/src/main/java/org/guanxi/sp/engine/service/saml2/SAML2ProfileService.java @@ -1,195 +1,197 @@ //: "The contents of this file are subject to the Mozilla Public License //: Version 1.1 (the "License"); you may not use this file except in //: compliance with the License. You may obtain a copy of the License at //: http://www.mozilla.org/MPL/ //: //: Software distributed under the License is distributed on an "AS IS" //: basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the //: License for the specific language governing rights and limitations //: under the License. //: //: The Original Code is Guanxi (http://www.guanxi.uhi.ac.uk). //: //: The Initial Developer of the Original Code is Alistair Young [email protected] //: All Rights Reserved. //: package org.guanxi.sp.engine.service.saml2; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlOptions; import org.guanxi.common.GuanxiException; import org.guanxi.common.Utils; import org.guanxi.common.definitions.SAML; import org.guanxi.common.entity.EntityFarm; import org.guanxi.common.entity.EntityManager; import org.guanxi.common.metadata.Metadata; import org.guanxi.common.security.SecUtilsConfig; import org.guanxi.sp.engine.service.generic.ProfileService; import org.guanxi.xal.saml2.metadata.GuardRoleDescriptorExtensions; import org.guanxi.xal.saml_2_0.assertion.NameIDType; import org.guanxi.xal.saml_2_0.metadata.EndpointType; import org.guanxi.xal.saml_2_0.metadata.EntityDescriptorType; import org.guanxi.xal.saml_2_0.protocol.AuthnRequestDocument; import org.guanxi.xal.saml_2_0.protocol.AuthnRequestType; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Calendar; import java.util.HashMap; /** * SAML2 ProfileService implementation * * @author alistair */ public class SAML2ProfileService implements ProfileService { /** Our logger */ private static final Logger logger = Logger.getLogger(SAML2ProfileService.class.getName()); /** The JSP to use to POST the AuthnRequest to the IdP */ private String httpPOSTView = null; /** The JSP to use to GET the AuthnRequest to the IdP */ private String httpRedirectView = null; /** The default endpoint for receiving SAML Response messages */ private String assertionConsumerServiceURL = null; /** @see org.guanxi.sp.engine.service.generic.ProfileService#init() */ public void init() {} /** @see org.guanxi.sp.engine.service.generic.ProfileService#doProfile(javax.servlet.http.HttpServletRequest, String, String, org.guanxi.xal.saml2.metadata.GuardRoleDescriptorExtensions, String, org.guanxi.common.entity.EntityFarm) */ public ModelAndView doProfile(HttpServletRequest request, String guardID, String guardSessionID, GuardRoleDescriptorExtensions guardNativeMetadata, String entityID, EntityFarm farm) throws GuanxiException { ModelAndView mAndV = new ModelAndView(); String relayState = guardSessionID.replaceAll("GUARD", "ENGINE"); // Load the metadata for the IdP EntityManager manager = farm.getEntityManagerForID(entityID); if (manager == null) { logger.error("Could not find manager for IdP '" + entityID); throw new GuanxiException("Could not find manager for IdP " + entityID); } Metadata entityMetadata = manager.getMetadata(entityID); if (entityMetadata == null) { logger.error("Could not find manager for IdP " + entityID); throw new GuanxiException("Could not find metadata for IdP " + entityID); } EntityDescriptorType saml2Metadata = (EntityDescriptorType)entityMetadata.getPrivateData(); String wbssoURL = null; String binding = null; EndpointType[] ssos = saml2Metadata.getIDPSSODescriptorArray(0).getSingleSignOnServiceArray(); for (EndpointType sso : ssos) { - if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) { + if ((sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) || + (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT))) { wbssoURL = sso.getLocation(); - binding = SAML.SAML2_BINDING_HTTP_POST; + if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) binding = SAML.SAML2_BINDING_HTTP_POST; + else if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT)) binding = SAML.SAML2_BINDING_HTTP_REDIRECT; break; } } if (wbssoURL == null) { logger.error("IdP does not support WBSSO " + entityID); throw new GuanxiException("IdP does not support WBSSO " + entityID); } // Create an AuthnRequest AuthnRequestDocument authnRequestDoc = AuthnRequestDocument.Factory.newInstance(); AuthnRequestType authnRequest = authnRequestDoc.addNewAuthnRequest(); authnRequest.setID(Utils.createNCNameID()); authnRequest.setVersion("2.0"); authnRequest.setIssueInstant(Calendar.getInstance()); Utils.zuluXmlObject(authnRequest, 0); NameIDType issuer = NameIDType.Factory.newInstance(); issuer.setStringValue(guardID); authnRequest.setIssuer(issuer); authnRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL); authnRequest.setProtocolBinding(SAML.SAML2_BINDING_HTTP_POST); // Only if signed //authnRequest.setDestination("https://sgarbh.smo.uhi.ac.uk:8443/idp/profile/SAML2/POST/SSO"); // Sort out the namespaces for saving the Response HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveSuggestedPrefixes(namespaces); xmlOptions.setSaveNamespacesFirst(); // Get the config ready for signing SecUtilsConfig secUtilsConfig = new SecUtilsConfig(); secUtilsConfig.setKeystoreFile(guardNativeMetadata.getKeystore()); secUtilsConfig.setKeystorePass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setKeystoreType("JKS"); secUtilsConfig.setPrivateKeyAlias(guardID); secUtilsConfig.setPrivateKeyPass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setCertificateAlias(guardID); // Break out to DOM land to get the SAML Response signed... /* Document signedDoc = null; try { // Need to use newDomNode to preserve namespace information signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document)authnRequestDoc.newDomNode(xmlOptions), ""); // ...and go back to XMLBeans land when it's ready authnRequestDoc = AuthnRequestDocument.Factory.parse(signedDoc); } catch(GuanxiException ge) { logger.error("Could not sign AuthnRequest", ge); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } catch(XmlException xe) { logger.error("Couldn't convert signed AuthnRequest back to XMLBeans", xe); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } */ // Base 64 encode the AuthnRequest //String authnRequestB64 = Utils.base64(signedDoc); //String authnRequestB64 = Utils.base64((Document)authnRequestDoc.newDomNode(xmlOptions)); // Do the profile quickstep String authnRequestForIdP = null; if (binding.equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { mAndV.setViewName(httpRedirectView); String deflatedRequest = Utils.deflate(authnRequestDoc.toString(), Utils.RFC1951_DEFAULT_COMPRESSION_LEVEL, Utils.RFC1951_NO_WRAP); authnRequestForIdP = Utils.base64(deflatedRequest.getBytes()); authnRequestForIdP = authnRequestForIdP.replaceAll(System.getProperty("line.separator"), ""); try { authnRequestForIdP = URLEncoder.encode(authnRequestForIdP, "UTF-8"); relayState = URLEncoder.encode(relayState, "UTF-8"); } catch(UnsupportedEncodingException uee) { logger.error("couldn't encode SAMLRequest"); throw new GuanxiException("couldn't encode SAMLRequest: " + uee.getMessage()); } } else if (binding.equals(SAML.SAML2_BINDING_HTTP_POST)) { mAndV.setViewName(httpPOSTView); authnRequestForIdP = Utils.base64(authnRequestDoc.toString().getBytes()); } // Send the AuthnRequest to the IdP mAndV.getModel().put("SAMLRequest", authnRequestForIdP); mAndV.getModel().put("RelayState", relayState); mAndV.getModel().put("wbsso_endpoint", wbssoURL); return mAndV; } // Setters public void setHttpPOSTView(String httpPOSTView) { this.httpPOSTView = httpPOSTView; } public void setHttpRedirectView(String httpRedirectView) { this.httpRedirectView = httpRedirectView; } public void setAssertionConsumerServiceURL(String assertionConsumerServiceURL) { this.assertionConsumerServiceURL = assertionConsumerServiceURL; } }
false
true
public ModelAndView doProfile(HttpServletRequest request, String guardID, String guardSessionID, GuardRoleDescriptorExtensions guardNativeMetadata, String entityID, EntityFarm farm) throws GuanxiException { ModelAndView mAndV = new ModelAndView(); String relayState = guardSessionID.replaceAll("GUARD", "ENGINE"); // Load the metadata for the IdP EntityManager manager = farm.getEntityManagerForID(entityID); if (manager == null) { logger.error("Could not find manager for IdP '" + entityID); throw new GuanxiException("Could not find manager for IdP " + entityID); } Metadata entityMetadata = manager.getMetadata(entityID); if (entityMetadata == null) { logger.error("Could not find manager for IdP " + entityID); throw new GuanxiException("Could not find metadata for IdP " + entityID); } EntityDescriptorType saml2Metadata = (EntityDescriptorType)entityMetadata.getPrivateData(); String wbssoURL = null; String binding = null; EndpointType[] ssos = saml2Metadata.getIDPSSODescriptorArray(0).getSingleSignOnServiceArray(); for (EndpointType sso : ssos) { if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) { wbssoURL = sso.getLocation(); binding = SAML.SAML2_BINDING_HTTP_POST; break; } } if (wbssoURL == null) { logger.error("IdP does not support WBSSO " + entityID); throw new GuanxiException("IdP does not support WBSSO " + entityID); } // Create an AuthnRequest AuthnRequestDocument authnRequestDoc = AuthnRequestDocument.Factory.newInstance(); AuthnRequestType authnRequest = authnRequestDoc.addNewAuthnRequest(); authnRequest.setID(Utils.createNCNameID()); authnRequest.setVersion("2.0"); authnRequest.setIssueInstant(Calendar.getInstance()); Utils.zuluXmlObject(authnRequest, 0); NameIDType issuer = NameIDType.Factory.newInstance(); issuer.setStringValue(guardID); authnRequest.setIssuer(issuer); authnRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL); authnRequest.setProtocolBinding(SAML.SAML2_BINDING_HTTP_POST); // Only if signed //authnRequest.setDestination("https://sgarbh.smo.uhi.ac.uk:8443/idp/profile/SAML2/POST/SSO"); // Sort out the namespaces for saving the Response HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveSuggestedPrefixes(namespaces); xmlOptions.setSaveNamespacesFirst(); // Get the config ready for signing SecUtilsConfig secUtilsConfig = new SecUtilsConfig(); secUtilsConfig.setKeystoreFile(guardNativeMetadata.getKeystore()); secUtilsConfig.setKeystorePass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setKeystoreType("JKS"); secUtilsConfig.setPrivateKeyAlias(guardID); secUtilsConfig.setPrivateKeyPass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setCertificateAlias(guardID); // Break out to DOM land to get the SAML Response signed... /* Document signedDoc = null; try { // Need to use newDomNode to preserve namespace information signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document)authnRequestDoc.newDomNode(xmlOptions), ""); // ...and go back to XMLBeans land when it's ready authnRequestDoc = AuthnRequestDocument.Factory.parse(signedDoc); } catch(GuanxiException ge) { logger.error("Could not sign AuthnRequest", ge); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } catch(XmlException xe) { logger.error("Couldn't convert signed AuthnRequest back to XMLBeans", xe); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } */ // Base 64 encode the AuthnRequest //String authnRequestB64 = Utils.base64(signedDoc); //String authnRequestB64 = Utils.base64((Document)authnRequestDoc.newDomNode(xmlOptions)); // Do the profile quickstep String authnRequestForIdP = null; if (binding.equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { mAndV.setViewName(httpRedirectView); String deflatedRequest = Utils.deflate(authnRequestDoc.toString(), Utils.RFC1951_DEFAULT_COMPRESSION_LEVEL, Utils.RFC1951_NO_WRAP); authnRequestForIdP = Utils.base64(deflatedRequest.getBytes()); authnRequestForIdP = authnRequestForIdP.replaceAll(System.getProperty("line.separator"), ""); try { authnRequestForIdP = URLEncoder.encode(authnRequestForIdP, "UTF-8"); relayState = URLEncoder.encode(relayState, "UTF-8"); } catch(UnsupportedEncodingException uee) { logger.error("couldn't encode SAMLRequest"); throw new GuanxiException("couldn't encode SAMLRequest: " + uee.getMessage()); } } else if (binding.equals(SAML.SAML2_BINDING_HTTP_POST)) { mAndV.setViewName(httpPOSTView); authnRequestForIdP = Utils.base64(authnRequestDoc.toString().getBytes()); } // Send the AuthnRequest to the IdP mAndV.getModel().put("SAMLRequest", authnRequestForIdP); mAndV.getModel().put("RelayState", relayState); mAndV.getModel().put("wbsso_endpoint", wbssoURL); return mAndV; }
public ModelAndView doProfile(HttpServletRequest request, String guardID, String guardSessionID, GuardRoleDescriptorExtensions guardNativeMetadata, String entityID, EntityFarm farm) throws GuanxiException { ModelAndView mAndV = new ModelAndView(); String relayState = guardSessionID.replaceAll("GUARD", "ENGINE"); // Load the metadata for the IdP EntityManager manager = farm.getEntityManagerForID(entityID); if (manager == null) { logger.error("Could not find manager for IdP '" + entityID); throw new GuanxiException("Could not find manager for IdP " + entityID); } Metadata entityMetadata = manager.getMetadata(entityID); if (entityMetadata == null) { logger.error("Could not find manager for IdP " + entityID); throw new GuanxiException("Could not find metadata for IdP " + entityID); } EntityDescriptorType saml2Metadata = (EntityDescriptorType)entityMetadata.getPrivateData(); String wbssoURL = null; String binding = null; EndpointType[] ssos = saml2Metadata.getIDPSSODescriptorArray(0).getSingleSignOnServiceArray(); for (EndpointType sso : ssos) { if ((sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) || (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT))) { wbssoURL = sso.getLocation(); if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST)) binding = SAML.SAML2_BINDING_HTTP_POST; else if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT)) binding = SAML.SAML2_BINDING_HTTP_REDIRECT; break; } } if (wbssoURL == null) { logger.error("IdP does not support WBSSO " + entityID); throw new GuanxiException("IdP does not support WBSSO " + entityID); } // Create an AuthnRequest AuthnRequestDocument authnRequestDoc = AuthnRequestDocument.Factory.newInstance(); AuthnRequestType authnRequest = authnRequestDoc.addNewAuthnRequest(); authnRequest.setID(Utils.createNCNameID()); authnRequest.setVersion("2.0"); authnRequest.setIssueInstant(Calendar.getInstance()); Utils.zuluXmlObject(authnRequest, 0); NameIDType issuer = NameIDType.Factory.newInstance(); issuer.setStringValue(guardID); authnRequest.setIssuer(issuer); authnRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL); authnRequest.setProtocolBinding(SAML.SAML2_BINDING_HTTP_POST); // Only if signed //authnRequest.setDestination("https://sgarbh.smo.uhi.ac.uk:8443/idp/profile/SAML2/POST/SSO"); // Sort out the namespaces for saving the Response HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL); namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveSuggestedPrefixes(namespaces); xmlOptions.setSaveNamespacesFirst(); // Get the config ready for signing SecUtilsConfig secUtilsConfig = new SecUtilsConfig(); secUtilsConfig.setKeystoreFile(guardNativeMetadata.getKeystore()); secUtilsConfig.setKeystorePass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setKeystoreType("JKS"); secUtilsConfig.setPrivateKeyAlias(guardID); secUtilsConfig.setPrivateKeyPass(guardNativeMetadata.getKeystorePassword()); secUtilsConfig.setCertificateAlias(guardID); // Break out to DOM land to get the SAML Response signed... /* Document signedDoc = null; try { // Need to use newDomNode to preserve namespace information signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document)authnRequestDoc.newDomNode(xmlOptions), ""); // ...and go back to XMLBeans land when it's ready authnRequestDoc = AuthnRequestDocument.Factory.parse(signedDoc); } catch(GuanxiException ge) { logger.error("Could not sign AuthnRequest", ge); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } catch(XmlException xe) { logger.error("Couldn't convert signed AuthnRequest back to XMLBeans", xe); mAndV.setViewName(errorView); mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message", null, request.getLocale())); return mAndV; } */ // Base 64 encode the AuthnRequest //String authnRequestB64 = Utils.base64(signedDoc); //String authnRequestB64 = Utils.base64((Document)authnRequestDoc.newDomNode(xmlOptions)); // Do the profile quickstep String authnRequestForIdP = null; if (binding.equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) { mAndV.setViewName(httpRedirectView); String deflatedRequest = Utils.deflate(authnRequestDoc.toString(), Utils.RFC1951_DEFAULT_COMPRESSION_LEVEL, Utils.RFC1951_NO_WRAP); authnRequestForIdP = Utils.base64(deflatedRequest.getBytes()); authnRequestForIdP = authnRequestForIdP.replaceAll(System.getProperty("line.separator"), ""); try { authnRequestForIdP = URLEncoder.encode(authnRequestForIdP, "UTF-8"); relayState = URLEncoder.encode(relayState, "UTF-8"); } catch(UnsupportedEncodingException uee) { logger.error("couldn't encode SAMLRequest"); throw new GuanxiException("couldn't encode SAMLRequest: " + uee.getMessage()); } } else if (binding.equals(SAML.SAML2_BINDING_HTTP_POST)) { mAndV.setViewName(httpPOSTView); authnRequestForIdP = Utils.base64(authnRequestDoc.toString().getBytes()); } // Send the AuthnRequest to the IdP mAndV.getModel().put("SAMLRequest", authnRequestForIdP); mAndV.getModel().put("RelayState", relayState); mAndV.getModel().put("wbsso_endpoint", wbssoURL); return mAndV; }
diff --git a/src/test/java/com/camilolopes/readerweb/services/impl/UserServiceimImplTest.java b/src/test/java/com/camilolopes/readerweb/services/impl/UserServiceimImplTest.java index bd16cf0..4bf56ac 100644 --- a/src/test/java/com/camilolopes/readerweb/services/impl/UserServiceimImplTest.java +++ b/src/test/java/com/camilolopes/readerweb/services/impl/UserServiceimImplTest.java @@ -1,104 +1,104 @@ package com.camilolopes.readerweb.services.impl; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import com.camilolopes.readerweb.dbunit.DBUnitConfiguration; import com.camilolopes.readerweb.enums.StatusUser; import com.camilolopes.readerweb.model.bean.User; import com.camilolopes.readerweb.services.interfaces.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:**/OrderPersistenceTests-context.xml"}) @TransactionConfiguration(defaultRollback=true,transactionManager="transactionManager") @Transactional public class UserServiceimImplTest extends DBUnitConfiguration{ @Autowired private UserService userServiceImpl; private User user; @Before public void setUp() throws Exception { user = new User(); getSetUpOperation().execute(getConnection(), getDataSet()); } private void setupUserData() { user.setEmail("[email protected]"); user.setLastname("lopes"); user.setName("camilo"); user.setPassword("123456"); user.setRegisterDate(new Date()); user.setStatus(StatusUser.ATIVE); } @Test public void testAddNewUserWithSucess() { setupUserData(); try{ int expectedTotalUser = 1 + userServiceImpl.readAll().size(); userServiceImpl.saveOrUpdate(user); assertNotNull(userServiceImpl.readAll()); assertEquals(expectedTotalUser ,userServiceImpl.readAll().size()); }catch (Exception e) { fail("not expected result " + e.fillInStackTrace()); } } @Test public void testDeletedUserById() throws Exception { assertEquals(userServiceImpl.readAll().size(),getDataSet().getTable("USER").getRowCount()); User userFound = (User) getSessionFactory().getCurrentSession().get(User.class, new Long("1")); assertNotNull(userFound); userServiceImpl.delete(userFound); userFound = (User) getSessionFactory().getCurrentSession().get(User.class, 1L); assertNull(userFound); } @Test public void testFindUserById() { assertNotNull(userServiceImpl.searchById(1L)); } @Test public void testUserNotFoundById(){ assertNull(userServiceImpl.searchById(0L)); } @Test public void testReturnAllUsersExists() { assertNotNull(userServiceImpl.readAll()); assertFalse(userServiceImpl.readAll().isEmpty()); } @Test public void testUpdateEmailOfUser(){ User user = (User) getSessionFactory().getCurrentSession().get(User.class, 1L); user.setEmail("[email protected]"); userServiceImpl.saveOrUpdate(user); User userFound = userServiceImpl.searchById(1L); assertEquals(user.getEmail(), userFound.getEmail() ); } @Test public void testUpdateDataOfTheUser(){ User user = (User) getSessionFactory().getCurrentSession().get(User.class, 2L); - String expectedNameUser = "joão "; + String expectedNameUser = "joão"; assertEquals(expectedNameUser, user.getName()); user.setName("Pedro"); user.setLastname("Leão"); user.setRegisterDate(new Date()); user.setStatus(StatusUser.INACTIVE); userServiceImpl.saveOrUpdate(user); User userUpdated = userServiceImpl.searchById(2L); assertEquals(user.getName(), userUpdated.getName()); assertFalse(user.getStatus()!= userUpdated.getStatus()); } }
true
true
public void testUpdateDataOfTheUser(){ User user = (User) getSessionFactory().getCurrentSession().get(User.class, 2L); String expectedNameUser = "joão "; assertEquals(expectedNameUser, user.getName()); user.setName("Pedro"); user.setLastname("Leão"); user.setRegisterDate(new Date()); user.setStatus(StatusUser.INACTIVE); userServiceImpl.saveOrUpdate(user); User userUpdated = userServiceImpl.searchById(2L); assertEquals(user.getName(), userUpdated.getName()); assertFalse(user.getStatus()!= userUpdated.getStatus()); }
public void testUpdateDataOfTheUser(){ User user = (User) getSessionFactory().getCurrentSession().get(User.class, 2L); String expectedNameUser = "joão"; assertEquals(expectedNameUser, user.getName()); user.setName("Pedro"); user.setLastname("Leão"); user.setRegisterDate(new Date()); user.setStatus(StatusUser.INACTIVE); userServiceImpl.saveOrUpdate(user); User userUpdated = userServiceImpl.searchById(2L); assertEquals(user.getName(), userUpdated.getName()); assertFalse(user.getStatus()!= userUpdated.getStatus()); }
diff --git a/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessDefinitionFormGet.java b/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessDefinitionFormGet.java index 4e16f564e..07ad54bf7 100644 --- a/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessDefinitionFormGet.java +++ b/modules/activiti-rest/src/main/java/org/activiti/rest/api/process/ProcessDefinitionFormGet.java @@ -1,43 +1,43 @@ package org.activiti.rest.api.process; import org.activiti.rest.util.ActivitiWebScript; import org.springframework.extensions.webscripts.Cache; import org.springframework.extensions.webscripts.Status; import org.springframework.extensions.webscripts.WebScriptException; import org.springframework.extensions.webscripts.WebScriptRequest; import java.util.Map; /** * Returns a process definition's form. * * @author Erik Winlöf */ public class ProcessDefinitionFormGet extends ActivitiWebScript { /** * Returns a process definition's form. * * @param req The webscripts request * @param status The webscripts status * @param cache The webscript cache * @param model The webscripts template model */ @Override protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) { String processDefinitionId = getMandatoryPathParameter(req, "processDefinitionId"); Object processDefinitionForm = getRepositoryService().getStartFormById(processDefinitionId); if (processDefinitionForm != null) { if (processDefinitionForm instanceof String) { model.put("form", processDefinitionForm); } else { - throw new WebScriptException(Status.STATUS_NOT_IMPLEMENTED, "The form for process definitionForm '" + processDefinitionForm + "' cannot be rendered using the rest api."); + throw new WebScriptException(Status.STATUS_NOT_IMPLEMENTED, "The form for process definition '" + processDefinitionId + "' cannot be rendered using the rest api."); } } else { - throw new WebScriptException(Status.STATUS_NOT_FOUND, "There is no form for process definitionForm '" + processDefinitionForm + "'."); + throw new WebScriptException(Status.STATUS_NOT_FOUND, "There is no form for process definition '" + processDefinitionId + "'."); } } }
false
true
protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) { String processDefinitionId = getMandatoryPathParameter(req, "processDefinitionId"); Object processDefinitionForm = getRepositoryService().getStartFormById(processDefinitionId); if (processDefinitionForm != null) { if (processDefinitionForm instanceof String) { model.put("form", processDefinitionForm); } else { throw new WebScriptException(Status.STATUS_NOT_IMPLEMENTED, "The form for process definitionForm '" + processDefinitionForm + "' cannot be rendered using the rest api."); } } else { throw new WebScriptException(Status.STATUS_NOT_FOUND, "There is no form for process definitionForm '" + processDefinitionForm + "'."); } }
protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) { String processDefinitionId = getMandatoryPathParameter(req, "processDefinitionId"); Object processDefinitionForm = getRepositoryService().getStartFormById(processDefinitionId); if (processDefinitionForm != null) { if (processDefinitionForm instanceof String) { model.put("form", processDefinitionForm); } else { throw new WebScriptException(Status.STATUS_NOT_IMPLEMENTED, "The form for process definition '" + processDefinitionId + "' cannot be rendered using the rest api."); } } else { throw new WebScriptException(Status.STATUS_NOT_FOUND, "There is no form for process definition '" + processDefinitionId + "'."); } }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dList.java b/src/main/java/net/aufdemrand/denizen/objects/dList.java index 2f9d54ad3..a3a315175 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dList.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dList.java @@ -1,420 +1,422 @@ package net.aufdemrand.denizen.objects; import net.aufdemrand.denizen.flags.FlagManager; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.debugging.dB; import org.bukkit.ChatColor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class dList extends ArrayList<String> implements dObject { final static Pattern flag_by_id = Pattern.compile("(fl\\[((?:p@|n@)(.+?))\\]@|fl@)(.+)", Pattern.CASE_INSENSITIVE); final static Pattern split_char = Pattern.compile("\\|"); final static Pattern identifier = Pattern.compile("li@", Pattern.CASE_INSENSITIVE); @ObjectFetcher("li, fl") public static dList valueOf(String string) { if (string == null) return null; /////// // Match @object format // Make sure string matches what this interpreter can accept. Matcher m; m = flag_by_id.matcher(string); if (m.matches()) { FlagManager flag_manager = DenizenAPI.getCurrentInstance().flagManager(); try { // Global if (m.group(1).equalsIgnoreCase("fl@")) { if (FlagManager.serverHasFlag(m.group(4))) return new dList(flag_manager.getGlobalFlag(m.group(4))); } else if (m.group(2).toLowerCase().startsWith("p@")) { if (FlagManager.playerHasFlag(dPlayer.valueOf(m.group(3)), m.group(4))) return new dList(flag_manager.getPlayerFlag(m.group(3), m.group(4))); } else if (m.group(2).toLowerCase().startsWith("n@")) { if (FlagManager.npcHasFlag(dNPC.valueOf(m.group(3)), m.group(4))) return new dList(flag_manager.getNPCFlag(Integer.valueOf(m.group(3)), m.group(4))); } } catch (Exception e) { dB.echoDebug("Flag '" + m.group() + "' could not be found!"); return null; } } // Use value of string, which will seperate values by the use of a pipe '|' return new dList(string.replaceFirst(identifier.pattern(), "")); } public static boolean matches(String arg) { Matcher m; m = flag_by_id.matcher(arg); return m.matches() || arg.contains("|") || arg.toLowerCase().startsWith("li@"); } ///////////// // Constructors ////////// // A list of dObjects public dList(ArrayList<? extends dObject> dObjectList) { for (dObject obj : dObjectList) add(obj.identify()); } // Empty dList public dList() { } // A string of items, split by '|' public dList(String items) { if (items != null) addAll(Arrays.asList(split_char.split(items))); } // A List<String> of items public dList(List<String> items) { if (items != null) addAll(items); } // A List<String> of items, with a prefix public dList(List<String> items, String prefix) { for (String element : items) { add(prefix + element); } } // A Flag public dList(FlagManager.Flag flag) { this.flag = flag; addAll(flag.values()); } ///////////// // Instance Fields/Methods ////////// private FlagManager.Flag flag = null; ////////////////////////////// // DSCRIPT ARGUMENT METHODS ///////////////////////// private String prefix = "List"; @Override public String getPrefix() { return prefix; } @Override public dList setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return "<G>" + prefix + "='<Y>" + identify() + "<G>' "; } @Override public boolean isUnique() { return flag != null; } @Override public String getType() { return "List"; } public String[] toArray() { List<String> list = new ArrayList<String>(); for (String string : this) { list.add(string); } return list.toArray(new String[list.size()]); } // Return a list that includes only elements belonging to a certain class public List<dObject> filter(Class<? extends dObject> dClass) { List<dObject> results = new ArrayList<dObject>(); for (String element : this) { try { if ((Boolean) dClass.getMethod("matches", String.class).invoke(null, element)) { dObject object = (dObject) dClass.getMethod("valueOf", String.class).invoke(null, element); // Only add the object if it is not null, thus filtering useless // list items if (object != null) { results.add(object); } } } catch (Exception e) { e.printStackTrace(); } } if (results.size() > 0) return results; else return null; } @Override public String toString() { return identify(); } @Override public String identify() { if (flag != null) return flag.toString(); if (isEmpty()) return "li@"; StringBuilder dScriptArg = new StringBuilder(); dScriptArg.append("li@"); for (String item : this) { dScriptArg.append(item); // Items are separated by the | character in dLists dScriptArg.append('|'); } return dScriptArg.toString().substring(0, dScriptArg.length() - 1); } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] - // @attribute <[email protected]_cslist> @returns Element + // @attribute <[email protected]_cslist> + // @returns Element + // @returns // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("ascslist") || attribute.startsWith("as_cslist")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert a comma and space after each item dScriptArg.append(", "); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("size")) return new Element(size()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("is_empty")) return new Element(isEmpty()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_string> // @returns Element // @description // returns each item in the list as a single 'String'. // --> if (attribute.startsWith("asstring") || attribute.startsWith("as_string")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert space between items. dScriptArg.append(' '); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][...|...]> // @returns dList // @description // returns a new dList excluding the items specified. // --> if (attribute.startsWith("exclude")) { String[] exclusions = split_char.split(attribute.getContext(1)); // Create a new dList that will contain the exclusions dList list = new dList(this); // Iterate through for (String exclusion : exclusions) for (int i = 0;i < list.size();i++) if (list.get(i).equalsIgnoreCase(exclusion)) list.remove(i--); // Return the modified list return list.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][#]> // @returns Element // @description // returns an Element of the value specified by the supplied context. // --> if (attribute.startsWith("get")) { if (isEmpty()) return "null"; int index = attribute.getIntContext(1); if (index > size()) return "null"; String item; if (index > 0) item = get(index - 1); else item = get(0); return new Element(item).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last")) { return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("contains")) { if (attribute.hasContext(1)) { boolean state = false; for (String element : this) { if (element.equalsIgnoreCase(attribute.getContext(1))) { state = true; break; } } return new Element(state).getAttribute(attribute.fulfill(1)); } } if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("identify")) { return new Element(identify()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("type")) { return new Element(getType()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // gets a random item in the list and returns it as an Element. // --> if (attribute.startsWith("random")) { if (!this.isEmpty()) return new Element(this.get(new Random().nextInt(this.size()))) .getAttribute(attribute.fulfill(1)); } // FLAG Specific Attributes // Note: is_expired attribute is handled in player/npc/server // since expired flags return 'null' // <--[tag] // @attribute <fl@flag_name.is_expired> // @returns Element(boolean) // @description // returns true of the flag is expired or does not exist, false if it // is not yet expired, or has no expiration. // --> // <--[tag] // @attribute <fl@flag_name.expiration> // @returns Duration // @description // returns a Duration of the time remaining on the flag, if it // has an expiration. // --> if (flag != null && attribute.startsWith("expiration")) { return flag.expiration() .getAttribute(attribute.fulfill(1)); } // Need this attribute (for flags) since they return the last // element of the list, unless '.as_list' is specified. // <--[tag] // @attribute <fl@flag_name.as_list> // @returns dList // @description // returns a dList containing the items in the flag // --> if (flag != null && (attribute.startsWith("as_list") || attribute.startsWith("aslist"))) return new dList(this).getAttribute(attribute.fulfill(1)); // If this is a flag, return the last element (this is how it has always worked...) // Use as_list to return a list representation of the flag. // If this is NOT a flag, but instead a normal dList, return an element // with dList's identify() value. return (flag != null ? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0)) : new Element(identify()).getAttribute(attribute.fulfill(0))); } }
true
true
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] // @attribute <[email protected]_cslist> @returns Element // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("ascslist") || attribute.startsWith("as_cslist")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert a comma and space after each item dScriptArg.append(", "); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("size")) return new Element(size()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("is_empty")) return new Element(isEmpty()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_string> // @returns Element // @description // returns each item in the list as a single 'String'. // --> if (attribute.startsWith("asstring") || attribute.startsWith("as_string")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert space between items. dScriptArg.append(' '); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][...|...]> // @returns dList // @description // returns a new dList excluding the items specified. // --> if (attribute.startsWith("exclude")) { String[] exclusions = split_char.split(attribute.getContext(1)); // Create a new dList that will contain the exclusions dList list = new dList(this); // Iterate through for (String exclusion : exclusions) for (int i = 0;i < list.size();i++) if (list.get(i).equalsIgnoreCase(exclusion)) list.remove(i--); // Return the modified list return list.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][#]> // @returns Element // @description // returns an Element of the value specified by the supplied context. // --> if (attribute.startsWith("get")) { if (isEmpty()) return "null"; int index = attribute.getIntContext(1); if (index > size()) return "null"; String item; if (index > 0) item = get(index - 1); else item = get(0); return new Element(item).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last")) { return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("contains")) { if (attribute.hasContext(1)) { boolean state = false; for (String element : this) { if (element.equalsIgnoreCase(attribute.getContext(1))) { state = true; break; } } return new Element(state).getAttribute(attribute.fulfill(1)); } } if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("identify")) { return new Element(identify()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("type")) { return new Element(getType()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // gets a random item in the list and returns it as an Element. // --> if (attribute.startsWith("random")) { if (!this.isEmpty()) return new Element(this.get(new Random().nextInt(this.size()))) .getAttribute(attribute.fulfill(1)); } // FLAG Specific Attributes // Note: is_expired attribute is handled in player/npc/server // since expired flags return 'null' // <--[tag] // @attribute <fl@flag_name.is_expired> // @returns Element(boolean) // @description // returns true of the flag is expired or does not exist, false if it // is not yet expired, or has no expiration. // --> // <--[tag] // @attribute <fl@flag_name.expiration> // @returns Duration // @description // returns a Duration of the time remaining on the flag, if it // has an expiration. // --> if (flag != null && attribute.startsWith("expiration")) { return flag.expiration() .getAttribute(attribute.fulfill(1)); } // Need this attribute (for flags) since they return the last // element of the list, unless '.as_list' is specified. // <--[tag] // @attribute <fl@flag_name.as_list> // @returns dList // @description // returns a dList containing the items in the flag // --> if (flag != null && (attribute.startsWith("as_list") || attribute.startsWith("aslist"))) return new dList(this).getAttribute(attribute.fulfill(1)); // If this is a flag, return the last element (this is how it has always worked...) // Use as_list to return a list representation of the flag. // If this is NOT a flag, but instead a normal dList, return an element // with dList's identify() value. return (flag != null ? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0)) : new Element(identify()).getAttribute(attribute.fulfill(0))); }
public String getAttribute(Attribute attribute) { if (attribute == null) return null; // <--[tag] // @attribute <[email protected]_cslist> // @returns Element // @returns // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("ascslist") || attribute.startsWith("as_cslist")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert a comma and space after each item dScriptArg.append(", "); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("size")) return new Element(size()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element // @description // returns 'comma-separated' list of the contents of this dList. // --> if (attribute.startsWith("is_empty")) return new Element(isEmpty()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_string> // @returns Element // @description // returns each item in the list as a single 'String'. // --> if (attribute.startsWith("asstring") || attribute.startsWith("as_string")) { if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1)); StringBuilder dScriptArg = new StringBuilder(); for (String item : this) { dScriptArg.append(item); // Insert space between items. dScriptArg.append(' '); } return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][...|...]> // @returns dList // @description // returns a new dList excluding the items specified. // --> if (attribute.startsWith("exclude")) { String[] exclusions = split_char.split(attribute.getContext(1)); // Create a new dList that will contain the exclusions dList list = new dList(this); // Iterate through for (String exclusion : exclusions) for (int i = 0;i < list.size();i++) if (list.get(i).equalsIgnoreCase(exclusion)) list.remove(i--); // Return the modified list return list.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected][#]> // @returns Element // @description // returns an Element of the value specified by the supplied context. // --> if (attribute.startsWith("get")) { if (isEmpty()) return "null"; int index = attribute.getIntContext(1); if (index > size()) return "null"; String item; if (index > 0) item = get(index - 1); else item = get(0); return new Element(item).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("last")) { return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("contains")) { if (attribute.hasContext(1)) { boolean state = false; for (String element : this) { if (element.equalsIgnoreCase(attribute.getContext(1))) { state = true; break; } } return new Element(state).getAttribute(attribute.fulfill(1)); } } if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("identify")) { return new Element(identify()) .getAttribute(attribute.fulfill(1)); } if (attribute.startsWith("type")) { return new Element(getType()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // gets a random item in the list and returns it as an Element. // --> if (attribute.startsWith("random")) { if (!this.isEmpty()) return new Element(this.get(new Random().nextInt(this.size()))) .getAttribute(attribute.fulfill(1)); } // FLAG Specific Attributes // Note: is_expired attribute is handled in player/npc/server // since expired flags return 'null' // <--[tag] // @attribute <fl@flag_name.is_expired> // @returns Element(boolean) // @description // returns true of the flag is expired or does not exist, false if it // is not yet expired, or has no expiration. // --> // <--[tag] // @attribute <fl@flag_name.expiration> // @returns Duration // @description // returns a Duration of the time remaining on the flag, if it // has an expiration. // --> if (flag != null && attribute.startsWith("expiration")) { return flag.expiration() .getAttribute(attribute.fulfill(1)); } // Need this attribute (for flags) since they return the last // element of the list, unless '.as_list' is specified. // <--[tag] // @attribute <fl@flag_name.as_list> // @returns dList // @description // returns a dList containing the items in the flag // --> if (flag != null && (attribute.startsWith("as_list") || attribute.startsWith("aslist"))) return new dList(this).getAttribute(attribute.fulfill(1)); // If this is a flag, return the last element (this is how it has always worked...) // Use as_list to return a list representation of the flag. // If this is NOT a flag, but instead a normal dList, return an element // with dList's identify() value. return (flag != null ? new Element(flag.getLast().asString()).getAttribute(attribute.fulfill(0)) : new Element(identify()).getAttribute(attribute.fulfill(0))); }
diff --git a/crypto/src/org/bouncycastle/openpgp/PGPObjectFactory.java b/crypto/src/org/bouncycastle/openpgp/PGPObjectFactory.java index ad5d0bbd..a297f983 100644 --- a/crypto/src/org/bouncycastle/openpgp/PGPObjectFactory.java +++ b/crypto/src/org/bouncycastle/openpgp/PGPObjectFactory.java @@ -1,112 +1,112 @@ package org.bouncycastle.openpgp; import org.bouncycastle.bcpg.BCPGInputStream; import org.bouncycastle.bcpg.PacketTags; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * General class for reading a PGP object stream. * <p> * Note: if this class finds a PGPPublicKey or a PGPSecretKey it * will create a PGPPublicKeyRing, or a PGPSecretKeyRing for each * key found. If all you are trying to do is read a key ring file use * either PGPPublicKeyRingCollection or PGPSecretKeyRingCollection. */ public class PGPObjectFactory { BCPGInputStream in; public PGPObjectFactory( InputStream in) { this.in = new BCPGInputStream(in); } public PGPObjectFactory( byte[] bytes) { this(new ByteArrayInputStream(bytes)); } /** * Return the next object in the stream, or null if the end is reached. * * @return Object * @throws IOException on a parse error */ public Object nextObject() throws IOException { List l; switch (in.nextPacketTag()) { case -1: return null; case PacketTags.SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.SIGNATURE) { try { l.add(new PGPSignature(in)); } catch (PGPException e) { throw new IOException("can't create signature object: " + e); } } return new PGPSignatureList((PGPSignature[])l.toArray(new PGPSignature[l.size()])); case PacketTags.SECRET_KEY: try { return new PGPSecretKeyRing(in); } catch (PGPException e) { throw new IOException("can't create secret key object: " + e); } case PacketTags.PUBLIC_KEY: return new PGPPublicKeyRing(in); case PacketTags.COMPRESSED_DATA: return new PGPCompressedData(in); case PacketTags.LITERAL_DATA: return new PGPLiteralData(in); case PacketTags.PUBLIC_KEY_ENC_SESSION: case PacketTags.SYMMETRIC_KEY_ENC_SESSION: return new PGPEncryptedDataList(in); case PacketTags.ONE_PASS_SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.ONE_PASS_SIGNATURE) { try { l.add(new PGPOnePassSignature(in)); } catch (PGPException e) { throw new IOException("can't create one pass signature object: " + e); } } return new PGPOnePassSignatureList((PGPOnePassSignature[])l.toArray(new PGPOnePassSignature[l.size()])); case PacketTags.MARKER: return new PGPMarker(in); case PacketTags.EXPERIMENTAL_1: case PacketTags.EXPERIMENTAL_2: case PacketTags.EXPERIMENTAL_3: case PacketTags.EXPERIMENTAL_4: return in.readPacket(); } - throw new IOException("unknown object in stream " + in.nextPacketTag()); + throw new IOException("unknown object in stream: " + in.nextPacketTag()); } }
true
true
public Object nextObject() throws IOException { List l; switch (in.nextPacketTag()) { case -1: return null; case PacketTags.SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.SIGNATURE) { try { l.add(new PGPSignature(in)); } catch (PGPException e) { throw new IOException("can't create signature object: " + e); } } return new PGPSignatureList((PGPSignature[])l.toArray(new PGPSignature[l.size()])); case PacketTags.SECRET_KEY: try { return new PGPSecretKeyRing(in); } catch (PGPException e) { throw new IOException("can't create secret key object: " + e); } case PacketTags.PUBLIC_KEY: return new PGPPublicKeyRing(in); case PacketTags.COMPRESSED_DATA: return new PGPCompressedData(in); case PacketTags.LITERAL_DATA: return new PGPLiteralData(in); case PacketTags.PUBLIC_KEY_ENC_SESSION: case PacketTags.SYMMETRIC_KEY_ENC_SESSION: return new PGPEncryptedDataList(in); case PacketTags.ONE_PASS_SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.ONE_PASS_SIGNATURE) { try { l.add(new PGPOnePassSignature(in)); } catch (PGPException e) { throw new IOException("can't create one pass signature object: " + e); } } return new PGPOnePassSignatureList((PGPOnePassSignature[])l.toArray(new PGPOnePassSignature[l.size()])); case PacketTags.MARKER: return new PGPMarker(in); case PacketTags.EXPERIMENTAL_1: case PacketTags.EXPERIMENTAL_2: case PacketTags.EXPERIMENTAL_3: case PacketTags.EXPERIMENTAL_4: return in.readPacket(); } throw new IOException("unknown object in stream " + in.nextPacketTag()); }
public Object nextObject() throws IOException { List l; switch (in.nextPacketTag()) { case -1: return null; case PacketTags.SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.SIGNATURE) { try { l.add(new PGPSignature(in)); } catch (PGPException e) { throw new IOException("can't create signature object: " + e); } } return new PGPSignatureList((PGPSignature[])l.toArray(new PGPSignature[l.size()])); case PacketTags.SECRET_KEY: try { return new PGPSecretKeyRing(in); } catch (PGPException e) { throw new IOException("can't create secret key object: " + e); } case PacketTags.PUBLIC_KEY: return new PGPPublicKeyRing(in); case PacketTags.COMPRESSED_DATA: return new PGPCompressedData(in); case PacketTags.LITERAL_DATA: return new PGPLiteralData(in); case PacketTags.PUBLIC_KEY_ENC_SESSION: case PacketTags.SYMMETRIC_KEY_ENC_SESSION: return new PGPEncryptedDataList(in); case PacketTags.ONE_PASS_SIGNATURE: l = new ArrayList(); while (in.nextPacketTag() == PacketTags.ONE_PASS_SIGNATURE) { try { l.add(new PGPOnePassSignature(in)); } catch (PGPException e) { throw new IOException("can't create one pass signature object: " + e); } } return new PGPOnePassSignatureList((PGPOnePassSignature[])l.toArray(new PGPOnePassSignature[l.size()])); case PacketTags.MARKER: return new PGPMarker(in); case PacketTags.EXPERIMENTAL_1: case PacketTags.EXPERIMENTAL_2: case PacketTags.EXPERIMENTAL_3: case PacketTags.EXPERIMENTAL_4: return in.readPacket(); } throw new IOException("unknown object in stream: " + in.nextPacketTag()); }
diff --git a/namecheap-java-client/src/main/java/com/pairconsulting/dnsclient/namecheap/request/DomainCreateRequest.java b/namecheap-java-client/src/main/java/com/pairconsulting/dnsclient/namecheap/request/DomainCreateRequest.java index 2da5913..b3db0ce 100644 --- a/namecheap-java-client/src/main/java/com/pairconsulting/dnsclient/namecheap/request/DomainCreateRequest.java +++ b/namecheap-java-client/src/main/java/com/pairconsulting/dnsclient/namecheap/request/DomainCreateRequest.java @@ -1,103 +1,104 @@ package com.pairconsulting.dnsclient.namecheap.request; import com.pairconsulting.dnsclient.model.Domain; import org.apache.commons.lang.StringUtils; import org.apache.http.message.BasicNameValuePair; import java.util.Properties; public class DomainCreateRequest extends DNSBaseRequest{ public DomainCreateRequest(Domain domain, Properties properties) { super(properties); addParam(new BasicNameValuePair("DomainName", domain.getName())); addParam(new BasicNameValuePair("Years", "1")); //registrant addParam(new BasicNameValuePair("RegistrantFirstName", properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("RegistrantLastName", properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("RegistrantAddress1", properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("RegistrantCity", properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("RegistrantStateProvince", properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("RegistrantPostalCode", properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("RegistrantCountry", properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("RegistrantPhone", properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("RegistrantEmailAddress", properties.getProperty("RegistrantEmailAddress"))); //tech info addParam(new BasicNameValuePair("TechFirstName", StringUtils.isNotEmpty(properties.getProperty("TechFirstName")) ? properties.getProperty("TechFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("TechLastName", StringUtils.isNotEmpty(properties.getProperty("TechLastName")) ? properties.getProperty("TechLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("TechAddress1", StringUtils.isNotEmpty(properties.getProperty("TechAddress1")) ? properties.getProperty("TechAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("TechCity", StringUtils.isNotEmpty(properties.getProperty("TechCity")) ? properties.getProperty("TechCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("TechStateProvince", StringUtils.isNotEmpty(properties.getProperty("TechStateProvince")) ? properties.getProperty("TechStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("TechPostalCode", StringUtils.isNotEmpty(properties.getProperty("TechPostalCode")) ? properties.getProperty("TechPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("TechCountry", StringUtils.isNotEmpty(properties.getProperty("TechCountry")) ? properties.getProperty("TechCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("TechPhone", StringUtils.isNotEmpty(properties.getProperty("TechPhone")) ? properties.getProperty("TechPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("TechEmailAddress", StringUtils.isNotEmpty(properties.getProperty("TechEmailAddress")) ? properties.getProperty("TechEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //admin info addParam(new BasicNameValuePair("AdminFirstName", StringUtils.isNotEmpty(properties.getProperty("AdminFirstName")) ? properties.getProperty("AdminFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AdminLastName", StringUtils.isNotEmpty(properties.getProperty("AdminLastName")) ? properties.getProperty("AdminLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AdminAddress1", StringUtils.isNotEmpty(properties.getProperty("AdminAddress1")) ? properties.getProperty("AdminAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AdminCity", StringUtils.isNotEmpty(properties.getProperty("AdminCity")) ? properties.getProperty("AdminCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AdminStateProvince", StringUtils.isNotEmpty(properties.getProperty("AdminStateProvince")) ? properties.getProperty("AdminStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AdminPostalCode", StringUtils.isNotEmpty(properties.getProperty("AdminPostalCode")) ? properties.getProperty("AdminPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AdminCountry", StringUtils.isNotEmpty(properties.getProperty("AdminCountry")) ? properties.getProperty("AdminCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AdminPhone", StringUtils.isNotEmpty(properties.getProperty("AdminPhone")) ? properties.getProperty("AdminPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AdminEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AdminEmailAddress")) ? properties.getProperty("AdminEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //auxiliary billing info addParam(new BasicNameValuePair("AuxBillingFirstName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingFirstName")) ? properties.getProperty("AuxBillingFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AuxBillingLastName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingLastName")) ? properties.getProperty("AuxBillingLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AuxBillingAddress1", StringUtils.isNotEmpty(properties.getProperty("AuxBillingAddress1")) ? properties.getProperty("AuxBillingAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AuxBillingCity", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCity")) ? properties.getProperty("AuxBillingCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AuxBillingStateProvince", StringUtils.isNotEmpty(properties.getProperty("AuxBillingStateProvince")) ? properties.getProperty("AuxBillingStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AuxBillingPostalCode", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPostalCode")) ? properties.getProperty("AuxBillingPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AuxBillingCountry", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCountry")) ? properties.getProperty("AuxBillingCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AuxBillingPhone", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPhone")) ? properties.getProperty("AuxBillingPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AuxBillingEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AuxBillingEmailAddress")) ? properties.getProperty("AuxBillingEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); String[] dls = getDomainLevels(domain.getName()); if (dls[dls.length-1].equals("ca")) { addParam(new BasicNameValuePair("CIRAAgreementVersion", "2.0")); addParam(new BasicNameValuePair("CIRAAgreementValue", "Y")); - addParam(new BasicNameValuePair("CIRAType", properties.getProperty("CIRAType"))); + addParam(new BasicNameValuePair("CIRALegalType", properties.getProperty("CIRALegalType"))); addParam(new BasicNameValuePair("CIRAWhoisDisplay", properties.getProperty("CIRAWhoisDisplay"))); + addParam(new BasicNameValuePair("CIRALanguage", properties.getProperty("CIRALanguage"))); } } @Override protected String getCommand() { return "namecheap.domains.create"; } }
false
true
public DomainCreateRequest(Domain domain, Properties properties) { super(properties); addParam(new BasicNameValuePair("DomainName", domain.getName())); addParam(new BasicNameValuePair("Years", "1")); //registrant addParam(new BasicNameValuePair("RegistrantFirstName", properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("RegistrantLastName", properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("RegistrantAddress1", properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("RegistrantCity", properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("RegistrantStateProvince", properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("RegistrantPostalCode", properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("RegistrantCountry", properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("RegistrantPhone", properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("RegistrantEmailAddress", properties.getProperty("RegistrantEmailAddress"))); //tech info addParam(new BasicNameValuePair("TechFirstName", StringUtils.isNotEmpty(properties.getProperty("TechFirstName")) ? properties.getProperty("TechFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("TechLastName", StringUtils.isNotEmpty(properties.getProperty("TechLastName")) ? properties.getProperty("TechLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("TechAddress1", StringUtils.isNotEmpty(properties.getProperty("TechAddress1")) ? properties.getProperty("TechAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("TechCity", StringUtils.isNotEmpty(properties.getProperty("TechCity")) ? properties.getProperty("TechCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("TechStateProvince", StringUtils.isNotEmpty(properties.getProperty("TechStateProvince")) ? properties.getProperty("TechStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("TechPostalCode", StringUtils.isNotEmpty(properties.getProperty("TechPostalCode")) ? properties.getProperty("TechPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("TechCountry", StringUtils.isNotEmpty(properties.getProperty("TechCountry")) ? properties.getProperty("TechCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("TechPhone", StringUtils.isNotEmpty(properties.getProperty("TechPhone")) ? properties.getProperty("TechPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("TechEmailAddress", StringUtils.isNotEmpty(properties.getProperty("TechEmailAddress")) ? properties.getProperty("TechEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //admin info addParam(new BasicNameValuePair("AdminFirstName", StringUtils.isNotEmpty(properties.getProperty("AdminFirstName")) ? properties.getProperty("AdminFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AdminLastName", StringUtils.isNotEmpty(properties.getProperty("AdminLastName")) ? properties.getProperty("AdminLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AdminAddress1", StringUtils.isNotEmpty(properties.getProperty("AdminAddress1")) ? properties.getProperty("AdminAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AdminCity", StringUtils.isNotEmpty(properties.getProperty("AdminCity")) ? properties.getProperty("AdminCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AdminStateProvince", StringUtils.isNotEmpty(properties.getProperty("AdminStateProvince")) ? properties.getProperty("AdminStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AdminPostalCode", StringUtils.isNotEmpty(properties.getProperty("AdminPostalCode")) ? properties.getProperty("AdminPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AdminCountry", StringUtils.isNotEmpty(properties.getProperty("AdminCountry")) ? properties.getProperty("AdminCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AdminPhone", StringUtils.isNotEmpty(properties.getProperty("AdminPhone")) ? properties.getProperty("AdminPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AdminEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AdminEmailAddress")) ? properties.getProperty("AdminEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //auxiliary billing info addParam(new BasicNameValuePair("AuxBillingFirstName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingFirstName")) ? properties.getProperty("AuxBillingFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AuxBillingLastName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingLastName")) ? properties.getProperty("AuxBillingLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AuxBillingAddress1", StringUtils.isNotEmpty(properties.getProperty("AuxBillingAddress1")) ? properties.getProperty("AuxBillingAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AuxBillingCity", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCity")) ? properties.getProperty("AuxBillingCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AuxBillingStateProvince", StringUtils.isNotEmpty(properties.getProperty("AuxBillingStateProvince")) ? properties.getProperty("AuxBillingStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AuxBillingPostalCode", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPostalCode")) ? properties.getProperty("AuxBillingPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AuxBillingCountry", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCountry")) ? properties.getProperty("AuxBillingCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AuxBillingPhone", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPhone")) ? properties.getProperty("AuxBillingPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AuxBillingEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AuxBillingEmailAddress")) ? properties.getProperty("AuxBillingEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); String[] dls = getDomainLevels(domain.getName()); if (dls[dls.length-1].equals("ca")) { addParam(new BasicNameValuePair("CIRAAgreementVersion", "2.0")); addParam(new BasicNameValuePair("CIRAAgreementValue", "Y")); addParam(new BasicNameValuePair("CIRAType", properties.getProperty("CIRAType"))); addParam(new BasicNameValuePair("CIRAWhoisDisplay", properties.getProperty("CIRAWhoisDisplay"))); } }
public DomainCreateRequest(Domain domain, Properties properties) { super(properties); addParam(new BasicNameValuePair("DomainName", domain.getName())); addParam(new BasicNameValuePair("Years", "1")); //registrant addParam(new BasicNameValuePair("RegistrantFirstName", properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("RegistrantLastName", properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("RegistrantAddress1", properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("RegistrantCity", properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("RegistrantStateProvince", properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("RegistrantPostalCode", properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("RegistrantCountry", properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("RegistrantPhone", properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("RegistrantEmailAddress", properties.getProperty("RegistrantEmailAddress"))); //tech info addParam(new BasicNameValuePair("TechFirstName", StringUtils.isNotEmpty(properties.getProperty("TechFirstName")) ? properties.getProperty("TechFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("TechLastName", StringUtils.isNotEmpty(properties.getProperty("TechLastName")) ? properties.getProperty("TechLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("TechAddress1", StringUtils.isNotEmpty(properties.getProperty("TechAddress1")) ? properties.getProperty("TechAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("TechCity", StringUtils.isNotEmpty(properties.getProperty("TechCity")) ? properties.getProperty("TechCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("TechStateProvince", StringUtils.isNotEmpty(properties.getProperty("TechStateProvince")) ? properties.getProperty("TechStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("TechPostalCode", StringUtils.isNotEmpty(properties.getProperty("TechPostalCode")) ? properties.getProperty("TechPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("TechCountry", StringUtils.isNotEmpty(properties.getProperty("TechCountry")) ? properties.getProperty("TechCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("TechPhone", StringUtils.isNotEmpty(properties.getProperty("TechPhone")) ? properties.getProperty("TechPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("TechEmailAddress", StringUtils.isNotEmpty(properties.getProperty("TechEmailAddress")) ? properties.getProperty("TechEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //admin info addParam(new BasicNameValuePair("AdminFirstName", StringUtils.isNotEmpty(properties.getProperty("AdminFirstName")) ? properties.getProperty("AdminFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AdminLastName", StringUtils.isNotEmpty(properties.getProperty("AdminLastName")) ? properties.getProperty("AdminLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AdminAddress1", StringUtils.isNotEmpty(properties.getProperty("AdminAddress1")) ? properties.getProperty("AdminAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AdminCity", StringUtils.isNotEmpty(properties.getProperty("AdminCity")) ? properties.getProperty("AdminCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AdminStateProvince", StringUtils.isNotEmpty(properties.getProperty("AdminStateProvince")) ? properties.getProperty("AdminStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AdminPostalCode", StringUtils.isNotEmpty(properties.getProperty("AdminPostalCode")) ? properties.getProperty("AdminPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AdminCountry", StringUtils.isNotEmpty(properties.getProperty("AdminCountry")) ? properties.getProperty("AdminCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AdminPhone", StringUtils.isNotEmpty(properties.getProperty("AdminPhone")) ? properties.getProperty("AdminPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AdminEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AdminEmailAddress")) ? properties.getProperty("AdminEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); //auxiliary billing info addParam(new BasicNameValuePair("AuxBillingFirstName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingFirstName")) ? properties.getProperty("AuxBillingFirstName") : properties.getProperty("RegistrantFirstName"))); addParam(new BasicNameValuePair("AuxBillingLastName", StringUtils.isNotEmpty(properties.getProperty("AuxBillingLastName")) ? properties.getProperty("AuxBillingLastName") : properties.getProperty("RegistrantLastName"))); addParam(new BasicNameValuePair("AuxBillingAddress1", StringUtils.isNotEmpty(properties.getProperty("AuxBillingAddress1")) ? properties.getProperty("AuxBillingAddress1") : properties.getProperty("RegistrantAddress1"))); addParam(new BasicNameValuePair("AuxBillingCity", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCity")) ? properties.getProperty("AuxBillingCity") : properties.getProperty("RegistrantCity"))); addParam(new BasicNameValuePair("AuxBillingStateProvince", StringUtils.isNotEmpty(properties.getProperty("AuxBillingStateProvince")) ? properties.getProperty("AuxBillingStateProvince") : properties.getProperty("RegistrantStateProvince"))); addParam(new BasicNameValuePair("AuxBillingPostalCode", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPostalCode")) ? properties.getProperty("AuxBillingPostalCode") : properties.getProperty("RegistrantPostalCode"))); addParam(new BasicNameValuePair("AuxBillingCountry", StringUtils.isNotEmpty(properties.getProperty("AuxBillingCountry")) ? properties.getProperty("AuxBillingCountry") : properties.getProperty("RegistrantCountry"))); addParam(new BasicNameValuePair("AuxBillingPhone", StringUtils.isNotEmpty(properties.getProperty("AuxBillingPhone")) ? properties.getProperty("AuxBillingPhone") : properties.getProperty("RegistrantPhone"))); addParam(new BasicNameValuePair("AuxBillingEmailAddress", StringUtils.isNotEmpty(properties.getProperty("AuxBillingEmailAddress")) ? properties.getProperty("AuxBillingEmailAddress") : properties.getProperty("RegistrantEmailAddress"))); String[] dls = getDomainLevels(domain.getName()); if (dls[dls.length-1].equals("ca")) { addParam(new BasicNameValuePair("CIRAAgreementVersion", "2.0")); addParam(new BasicNameValuePair("CIRAAgreementValue", "Y")); addParam(new BasicNameValuePair("CIRALegalType", properties.getProperty("CIRALegalType"))); addParam(new BasicNameValuePair("CIRAWhoisDisplay", properties.getProperty("CIRAWhoisDisplay"))); addParam(new BasicNameValuePair("CIRALanguage", properties.getProperty("CIRALanguage"))); } }
diff --git a/src/main/java/org/agmip/translators/dssat/DssatBatchFileOutput.java b/src/main/java/org/agmip/translators/dssat/DssatBatchFileOutput.java index 2398a3c..9fb8e74 100644 --- a/src/main/java/org/agmip/translators/dssat/DssatBatchFileOutput.java +++ b/src/main/java/org/agmip/translators/dssat/DssatBatchFileOutput.java @@ -1,275 +1,275 @@ package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.agmip.util.MapUtil.*; /** * DSSAT Batch File I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatBatchFileOutput extends DssatCommonOutput { /** * DSSAT Batch File Output method * * @param arg0 file output path * @param results array of data holder object */ public void writeFile(String arg0, ArrayList<HashMap> results) { // Initial variables HashMap result; // Data holder for summary data BufferedWriter bwB; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output try { // Set default value for missing data setDefVal(); // Get Data from input holder if (results.isEmpty()) { return; } result = results.get(0); // Initial BufferedWriter arg0 = revisePath(arg0); outputFile = new File(arg0 + "DSSBatch.v45"); bwB = new BufferedWriter(new FileWriter(outputFile)); // Output Batch File // Titel Section String crop = getCropName(result); String dssatPath = "C:\\DSSAT45\\"; String exFileName = getFileName(result, "X"); int dssatVersion; int expNo = results.size(); // Get version number try { String cropVersion = getObjectOr(result, "crop_model_version", "").replaceAll("\\D", ""); dssatVersion = Integer.parseInt(cropVersion); } catch (Exception e) { dssatVersion = 45; } // Write title section sbData.append("$BATCH(").append(crop.toUpperCase()).append(")\r\n!\r\n"); sbData.append(String.format("! Command Line : %1$sDSCSM%2$03d.EXE B DSSBatch.v%2$02d\r\n", dssatPath, dssatVersion)); sbData.append("! Crop : ").append(crop).append("\r\n"); sbData.append("! Experiment : ").append(exFileName).append("\r\n"); sbData.append("! ExpNo : ").append(expNo).append("\r\n"); sbData.append(String.format("! Debug : %1$sDSCSM%2$03d.EXE \" B DSSBatch.v%2$02d\"\r\n!\r\n", dssatPath, dssatVersion)); // Body Section sbData.append("@FILEX TRTNO RP SQ OP CO\r\n"); for (int i = 0; i < results.size(); i++) { result = results.get(i); exFileName = getFileName(result, "X"); String folderPath = getObjectOr(result, "exname", "Experiment_" + i); folderPath += File.separator; // Get DSSAT Sequence info HashMap dssatSeqData = getObjectOr(result, "dssat_sequence", new HashMap()); ArrayList<HashMap> dssatSeqArr = getObjectOr(dssatSeqData, "data", new ArrayList<HashMap>()); // If missing, set default value if (dssatSeqArr.isEmpty()) { HashMap tmp = new HashMap(); tmp.put("sq", "1"); tmp.put("op", "1"); tmp.put("co", "0"); dssatSeqArr.add(tmp); } // Output all info for (int j = 0; j < dssatSeqArr.size(); j++) { sbData.append(String.format("%1$-92s %2$6s %3$6s %4$6s %5$6s %6$6s\r\n", - folderPath + exFileName, + exFileName, "1", "1", getObjectOr(dssatSeqArr.get(j), "sq", "1"), getObjectOr(dssatSeqArr.get(j), "op", "1"), getObjectOr(dssatSeqArr.get(j), "co", "0"))); } } // Output finish bwB.write(sbError.toString()); bwB.write(sbData.toString()); bwB.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * DSSAT Batch File Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables BufferedWriter bwB; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output try { // Set default value for missing data setDefVal(); // Initial BufferedWriter arg0 = revisePath(arg0); outputFile = new File(arg0 + "DSSBatch.v45"); bwB = new BufferedWriter(new FileWriter(outputFile)); // Output Batch File // Titel Section String crop = getCropName(result); String dssatPath = "C:\\DSSAT45\\"; String exFileName = getFileName(result, "X"); int dssatVersion; int expNo = 1; // Get version number try { String cropVersion = getObjectOr(result, "crop_model_version", "").replaceAll("\\D", ""); dssatVersion = Integer.parseInt(cropVersion); } catch (Exception e) { dssatVersion = 45; } // Write title section sbData.append("$BATCH(").append(crop).append(")\r\n!\r\n"); sbData.append(String.format("! Command Line : %1$sDSCSM%2$03d.EXE B DSSBatch.v%2$02d\r\n", dssatPath, dssatVersion)); sbData.append("! Crop : ").append(crop).append("\r\n"); sbData.append("! Experiment : ").append(exFileName).append("\r\n"); sbData.append("! ExpNo : ").append(expNo).append("\r\n"); sbData.append(String.format("! Debug : %1$sDSCSM%2$03d.EXE \" B DSSBatch.v%2$02d\"\r\n!\r\n", dssatPath, dssatVersion)); // Body Section sbData.append("@FILEX TRTNO RP SQ OP CO\r\n"); // Get DSSAT Sequence info HashMap dssatSeqData = getObjectOr(result, "dssat_sequence", new HashMap()); ArrayList<HashMap> dssatSeqArr = getObjectOr(dssatSeqData, "data", new ArrayList<HashMap>()); // If missing, set default value if (dssatSeqArr.isEmpty()) { HashMap tmp = new HashMap(); tmp.put("sq", "1"); tmp.put("op", "1"); tmp.put("co", "0"); dssatSeqArr.add(tmp); } // Output all info for (int i = 0; i < dssatSeqArr.size(); i++) { sbData.append(String.format("%1$-92s %2$6s %3$6s %4$6s %5$6s %6$6s", exFileName, "1", "1", getObjectOr(dssatSeqArr.get(i), "sq", "1"), getObjectOr(dssatSeqArr.get(i), "op", "1"), getObjectOr(dssatSeqArr.get(i), "co", "0"))); } // Output finish bwB.write(sbError.toString()); bwB.write(sbData.toString()); bwB.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Get crop name string * * @param result experiment data holder * @return */ private String getCropName(Map result) { String ret; String crid = null; // Get crop id crid = getCrid(result); // Get crop name string if ("BH".equals(crid)) { ret = "Bahia"; } else if ("BA".equals(crid)) { ret = "Barley"; } else if ("BR".equals(crid)) { ret = "Brachiaria"; } else if ("CB".equals(crid)) { ret = "Cabbage"; } else if ("CS".equals(crid)) { ret = "Cassava"; } else if ("CH".equals(crid)) { ret = "Chickpea"; } else if ("CO".equals(crid)) { ret = "Cotton"; } else if ("CP".equals(crid)) { ret = "Cowpea"; } else if ("BN".equals(crid)) { ret = "Drybean"; } else if ("FB".equals(crid)) { ret = "FabaBean"; } else if ("FA".equals(crid)) { ret = "Fallow"; } else if ("GB".equals(crid)) { ret = "GreenBean"; } else if ("MZ".equals(crid)) { ret = "Maize"; } else if ("ML".equals(crid)) { ret = "Millet"; } else if ("PN".equals(crid)) { ret = "Peanut"; } else if ("PR".equals(crid)) { ret = "Pepper"; } else if ("PI".equals(crid)) { ret = "PineApple"; } else if ("PT".equals(crid)) { ret = "Potato"; } else if ("RI".equals(crid)) { ret = "Rice"; } else if ("SG".equals(crid)) { ret = "Sorghum"; } else if ("SB".equals(crid)) { ret = "Soybean"; } else if ("SC".equals(crid)) { ret = "Sugarcane"; } else if ("SU".equals(crid)) { ret = "Sunflower"; } else if ("SW".equals(crid)) { ret = "SweetCorn"; } else if ("TN".equals(crid)) { ret = "Tanier"; } else if ("TR".equals(crid)) { ret = "Taro"; } else if ("TM".equals(crid)) { ret = "Tomato"; } else if ("VB".equals(crid)) { ret = "Velvetbean"; } else if ("WH".equals(crid)) { ret = "Wheat"; } else if ("SQ".equals(crid)) { ret = "Sequence"; } else { ret = "Unkown"; sbError.append("! Warning: Undefined crop id: [").append(crid).append("]\r\n"); } return ret; } }
true
true
public void writeFile(String arg0, ArrayList<HashMap> results) { // Initial variables HashMap result; // Data holder for summary data BufferedWriter bwB; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output try { // Set default value for missing data setDefVal(); // Get Data from input holder if (results.isEmpty()) { return; } result = results.get(0); // Initial BufferedWriter arg0 = revisePath(arg0); outputFile = new File(arg0 + "DSSBatch.v45"); bwB = new BufferedWriter(new FileWriter(outputFile)); // Output Batch File // Titel Section String crop = getCropName(result); String dssatPath = "C:\\DSSAT45\\"; String exFileName = getFileName(result, "X"); int dssatVersion; int expNo = results.size(); // Get version number try { String cropVersion = getObjectOr(result, "crop_model_version", "").replaceAll("\\D", ""); dssatVersion = Integer.parseInt(cropVersion); } catch (Exception e) { dssatVersion = 45; } // Write title section sbData.append("$BATCH(").append(crop.toUpperCase()).append(")\r\n!\r\n"); sbData.append(String.format("! Command Line : %1$sDSCSM%2$03d.EXE B DSSBatch.v%2$02d\r\n", dssatPath, dssatVersion)); sbData.append("! Crop : ").append(crop).append("\r\n"); sbData.append("! Experiment : ").append(exFileName).append("\r\n"); sbData.append("! ExpNo : ").append(expNo).append("\r\n"); sbData.append(String.format("! Debug : %1$sDSCSM%2$03d.EXE \" B DSSBatch.v%2$02d\"\r\n!\r\n", dssatPath, dssatVersion)); // Body Section sbData.append("@FILEX TRTNO RP SQ OP CO\r\n"); for (int i = 0; i < results.size(); i++) { result = results.get(i); exFileName = getFileName(result, "X"); String folderPath = getObjectOr(result, "exname", "Experiment_" + i); folderPath += File.separator; // Get DSSAT Sequence info HashMap dssatSeqData = getObjectOr(result, "dssat_sequence", new HashMap()); ArrayList<HashMap> dssatSeqArr = getObjectOr(dssatSeqData, "data", new ArrayList<HashMap>()); // If missing, set default value if (dssatSeqArr.isEmpty()) { HashMap tmp = new HashMap(); tmp.put("sq", "1"); tmp.put("op", "1"); tmp.put("co", "0"); dssatSeqArr.add(tmp); } // Output all info for (int j = 0; j < dssatSeqArr.size(); j++) { sbData.append(String.format("%1$-92s %2$6s %3$6s %4$6s %5$6s %6$6s\r\n", folderPath + exFileName, "1", "1", getObjectOr(dssatSeqArr.get(j), "sq", "1"), getObjectOr(dssatSeqArr.get(j), "op", "1"), getObjectOr(dssatSeqArr.get(j), "co", "0"))); } } // Output finish bwB.write(sbError.toString()); bwB.write(sbData.toString()); bwB.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void writeFile(String arg0, ArrayList<HashMap> results) { // Initial variables HashMap result; // Data holder for summary data BufferedWriter bwB; // output object StringBuilder sbData = new StringBuilder(); // construct the data info in the output try { // Set default value for missing data setDefVal(); // Get Data from input holder if (results.isEmpty()) { return; } result = results.get(0); // Initial BufferedWriter arg0 = revisePath(arg0); outputFile = new File(arg0 + "DSSBatch.v45"); bwB = new BufferedWriter(new FileWriter(outputFile)); // Output Batch File // Titel Section String crop = getCropName(result); String dssatPath = "C:\\DSSAT45\\"; String exFileName = getFileName(result, "X"); int dssatVersion; int expNo = results.size(); // Get version number try { String cropVersion = getObjectOr(result, "crop_model_version", "").replaceAll("\\D", ""); dssatVersion = Integer.parseInt(cropVersion); } catch (Exception e) { dssatVersion = 45; } // Write title section sbData.append("$BATCH(").append(crop.toUpperCase()).append(")\r\n!\r\n"); sbData.append(String.format("! Command Line : %1$sDSCSM%2$03d.EXE B DSSBatch.v%2$02d\r\n", dssatPath, dssatVersion)); sbData.append("! Crop : ").append(crop).append("\r\n"); sbData.append("! Experiment : ").append(exFileName).append("\r\n"); sbData.append("! ExpNo : ").append(expNo).append("\r\n"); sbData.append(String.format("! Debug : %1$sDSCSM%2$03d.EXE \" B DSSBatch.v%2$02d\"\r\n!\r\n", dssatPath, dssatVersion)); // Body Section sbData.append("@FILEX TRTNO RP SQ OP CO\r\n"); for (int i = 0; i < results.size(); i++) { result = results.get(i); exFileName = getFileName(result, "X"); String folderPath = getObjectOr(result, "exname", "Experiment_" + i); folderPath += File.separator; // Get DSSAT Sequence info HashMap dssatSeqData = getObjectOr(result, "dssat_sequence", new HashMap()); ArrayList<HashMap> dssatSeqArr = getObjectOr(dssatSeqData, "data", new ArrayList<HashMap>()); // If missing, set default value if (dssatSeqArr.isEmpty()) { HashMap tmp = new HashMap(); tmp.put("sq", "1"); tmp.put("op", "1"); tmp.put("co", "0"); dssatSeqArr.add(tmp); } // Output all info for (int j = 0; j < dssatSeqArr.size(); j++) { sbData.append(String.format("%1$-92s %2$6s %3$6s %4$6s %5$6s %6$6s\r\n", exFileName, "1", "1", getObjectOr(dssatSeqArr.get(j), "sq", "1"), getObjectOr(dssatSeqArr.get(j), "op", "1"), getObjectOr(dssatSeqArr.get(j), "co", "0"))); } } // Output finish bwB.write(sbError.toString()); bwB.write(sbData.toString()); bwB.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/cruisecontrol/contrib/distributed/src/net/sourceforge/cruisecontrol/distributed/BuildAgent.java b/cruisecontrol/contrib/distributed/src/net/sourceforge/cruisecontrol/distributed/BuildAgent.java index 18fb60bc..719b33c8 100644 --- a/cruisecontrol/contrib/distributed/src/net/sourceforge/cruisecontrol/distributed/BuildAgent.java +++ b/cruisecontrol/contrib/distributed/src/net/sourceforge/cruisecontrol/distributed/BuildAgent.java @@ -1,419 +1,420 @@ /**************************************************************************** * CruiseControl, a Continuous Integration Toolkit * Copyright (c) 2001, ThoughtWorks, Inc. * 200 E. Randolph, 25th Floor * Chicago, IL 60601 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.distributed; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.ExportException; import java.util.Iterator; import java.util.Properties; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import net.jini.core.entry.Entry; import net.jini.core.lookup.ServiceID; import net.jini.core.lookup.ServiceRegistrar; import net.jini.core.discovery.LookupLocator; import net.jini.discovery.DiscoveryEvent; import net.jini.discovery.DiscoveryListener; import net.jini.discovery.LookupLocatorDiscovery; import net.jini.lookup.ServiceIDListener; import net.jini.lookup.JoinManager; import net.jini.export.Exporter; import net.jini.jeri.BasicILFactory; import net.jini.jeri.BasicJeriExporter; import net.jini.jeri.tcp.TcpServerEndpoint; import net.sourceforge.cruisecontrol.distributed.core.PropertiesHelper; import net.sourceforge.cruisecontrol.distributed.core.ReggieUtil; import net.sourceforge.cruisecontrol.distributed.core.CCDistVersion; import net.sourceforge.cruisecontrol.util.MainArgs; import org.apache.log4j.Logger; public class BuildAgent implements DiscoveryListener, ServiceIDListener { static final String MAIN_ARG_AGENT_PROPS = "agentprops"; static final String MAIN_ARG_USER_PROPS = "userprops"; static final String MAIN_ARG_SKIP_UI = "skipUI"; // package visible to allow BuildAgentUI console logger access to this Logger static final Logger LOG = Logger.getLogger(BuildAgent.class); public static final String JAVA_SECURITY_POLICY = "java.security.policy"; private static final String JINI_POLICY_FILE = "jini.policy.file"; /** Optional unicast Lookup Registry URL. * A Unicast Lookup Locater is useful if multicast isn't working. */ private static final String REGISTRY_URL = "registry.url"; private final BuildAgentServiceImpl serviceImpl; private final Entry[] entries; private final Exporter exporter; private final JoinManager joinManager; private ServiceID serviceID; private final Remote proxy; private Properties entryProperties; private Properties configProperties; private final BuildAgentUI ui; static interface LUSCountListener { public void lusCountChanged(final int newLUSCount); } private final List lusCountListeners = new ArrayList(); void addLUSCountListener(final LUSCountListener listener) { lusCountListeners.add(listener); } void removeLUSCountListener(final LUSCountListener listener) { lusCountListeners.remove(listener); } private int registrarCount = 0; private void fireLUSCountChanged() { for (int i = 0; i < lusCountListeners.size(); i++) { ((LUSCountListener) lusCountListeners.get(i)).lusCountChanged(registrarCount); } } private synchronized void setRegCount(final int regCount) { registrarCount = regCount; LOG.info("Lookup Services found: " + registrarCount); fireLUSCountChanged(); } /** * @param propsFile the agent properties file * @param userDefinedPropertiesFilename the user defined properties file * @param isSkipUI if true, do not show the build agent UI. */ public BuildAgent(final String propsFile, final String userDefinedPropertiesFilename, final boolean isSkipUI) { loadProperties(propsFile, userDefinedPropertiesFilename); serviceImpl = new BuildAgentServiceImpl(); serviceImpl.setAgentPropertiesFilename(propsFile); entries = SearchablePropertyEntries.getPropertiesAsEntryArray(entryProperties); if (!isSkipUI) { LOG.info("Loading Build Agent UI (use param -" + MAIN_ARG_SKIP_UI + " to bypass)."); ui = new BuildAgentUI(this); //ui.updateAgentInfoUI(getService()); } else { LOG.info("Bypassing Build Agent UI."); ui = null; } exporter = new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory(), false, true); try { proxy = exporter.export(getService()); } catch (ExportException e) { final String message = "Error exporting service"; LOG.error(message, e); throw new RuntimeException(message, e); } - // Use a comma separated list of Unicast Lookup Locaters (URL's) if defined. Useful if multicast isn't working. - // @todo It also could have a virtual url called "multicast", - // to make the property file more readable and understandable + // Use a comma separated list of Unicast Lookup Locaters (URL's) if defined in agent.properties. + // Useful if multicast isn't working. final String registryURLList = configProperties.getProperty(REGISTRY_URL); final LookupLocatorDiscovery lld; if (registryURLList == null) { lld = null; } else { final String[] registryURLs = registryURLList.split(","); final LookupLocator[] lookups = new LookupLocator[registryURLs.length]; for (int i = 0; i < registryURLs.length; i++) { try { lookups[i] = new LookupLocator(registryURLs[i]); } catch (MalformedURLException e) { - final String message = "Error creating unicast lookup locator: " + registryURLs[i]; + final String message = "Error creating unicast lookup locator: " + registryURLs[i] + + "; " + e.getMessage(); LOG.error(message, e); throw new RuntimeException(message, e); } + LOG.info("Using Unicast LookupLocator URL: " + registryURLs[i]); } lld = new LookupLocatorDiscovery(lookups); } try { joinManager = new JoinManager(getProxy(), entries, this, lld, null); } catch (IOException e) { final String message = "Error starting discovery"; LOG.error(message, e); throw new RuntimeException(message, e); } getJoinManager().getDiscoveryManager().addDiscoveryListener(this); } /** * @param propsFile path to config properties file * @param userDefinedPropertiesFilename path to user properties file */ private void loadProperties(final String propsFile, final String userDefinedPropertiesFilename) { configProperties = (Properties) PropertiesHelper.loadRequiredProperties(propsFile); entryProperties = new SearchablePropertyEntries(userDefinedPropertiesFilename).getProperties(); final String policyFileValue = configProperties.getProperty(JINI_POLICY_FILE); LOG.info("policyFileValue: " + policyFileValue); // resource loading technique below dies in webstart //URL policyFile = ClassLoader.getSystemClassLoader().getResource(policyFileValue); final URL policyFile = BuildAgent.class.getClassLoader().getResource(policyFileValue); LOG.info("policyFile: " + policyFile); System.setProperty(JAVA_SECURITY_POLICY, policyFile.toExternalForm()); ReggieUtil.setupRMISecurityManager(); } private Exporter getExporter() { return exporter; } private JoinManager getJoinManager() { return joinManager; } Entry[] getEntries() { return entries; } void addAgentStatusListener(final BuildAgent.AgentStatusListener listener) { serviceImpl.addAgentStatusListener(listener); } void removeAgentStatusListener(final BuildAgent.AgentStatusListener listener) { serviceImpl.removeAgentStatusListener(listener); } public void terminate() { LOG.info("Terminating build agent."); getExporter().unexport(true); getJoinManager().terminate(); // allow some time for cleanup try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.warn("Sleep interrupted during terminate", e); } if (ui != null) { ui.dispose(); LOG.info("UI disposed"); } } private Remote getProxy() { return proxy; } public synchronized BuildAgentService getService() { return serviceImpl; } public synchronized void serviceIDNotify(final ServiceID serviceID) { // @todo technically, should serviceID be stored permanently and reused?.... this.serviceID = serviceID; LOG.info("ServiceID assigned: " + this.serviceID); if (ui != null) { ui.updateAgentInfoUI(getService()); } } synchronized ServiceID getServiceID() { return serviceID; } private void logRegistration(final ServiceRegistrar registrar) { String host = null; try { host = registrar.getLocator().getHost(); } catch (RemoteException e) { LOG.warn("Failed to get registrar's hostname"); } LOG.info("Registering BuildAgentService with Registrar: " + host); final String machineName = (String) entryProperties.get("hostname"); LOG.debug("Registered machineName: " + machineName); LOG.debug("Entries: "); for (Iterator iter = entryProperties.keySet().iterator(); iter.hasNext();) { final String key = (String) iter.next(); LOG.debug(" " + key + " = " + entryProperties.get(key)); } } private boolean isNotFirstDiscovery; public void discovered(final DiscoveryEvent evt) { final ServiceRegistrar[] registrarsArray = evt.getRegistrars(); ServiceRegistrar registrar; for (int n = 0; n < registrarsArray.length; n++) { registrar = registrarsArray[n]; logRegistration(registrar); LOG.debug("Registered with registrar: " + registrar.getServiceID()); } if (!isNotFirstDiscovery) { LOG.info("BuildAgentService open for business..."); isNotFirstDiscovery = true; } setRegCount(getJoinManager().getDiscoveryManager().getRegistrars().length); } public void discarded(final DiscoveryEvent evt) { final ServiceRegistrar[] registrarsArray = evt.getRegistrars(); ServiceRegistrar registrar; for (int n = 0; n < registrarsArray.length; n++) { registrar = registrarsArray[n]; LOG.debug("Discarded registrar: " + registrar.getServiceID()); } setRegCount(getJoinManager().getDiscoveryManager().getRegistrars().length); } private static final Object KEEP_ALIVE = new Object(); private static Thread mainThread; private static synchronized void setMainThread(final Thread newMainThread) { mainThread = newMainThread; } static synchronized Thread getMainThread() { return mainThread; } public static void main(final String[] args) { LOG.info("Starting agent...args: " + Arrays.asList(args).toString()); CCDistVersion.printCCDistVersion(); if (shouldPrintUsage(args)) { printUsage(); } final BuildAgent buildAgent = new BuildAgent( MainArgs.parseArgument(args, MAIN_ARG_AGENT_PROPS, BuildAgentServiceImpl.DEFAULT_AGENT_PROPERTIES_FILE, BuildAgentServiceImpl.DEFAULT_AGENT_PROPERTIES_FILE), MainArgs.parseArgument(args, MAIN_ARG_USER_PROPS, BuildAgentServiceImpl.DEFAULT_USER_DEFINED_PROPERTIES_FILE, BuildAgentServiceImpl.DEFAULT_USER_DEFINED_PROPERTIES_FILE), MainArgs.argumentPresent(args, MAIN_ARG_SKIP_UI) ); setMainThread(Thread.currentThread()); // stay around forever synchronized (KEEP_ALIVE) { try { KEEP_ALIVE.wait(); } catch (InterruptedException e) { LOG.error("Keep Alive wait interrupted", e); } finally { buildAgent.terminate(); } } } private static boolean shouldPrintUsage(String[] args) { return MainArgs.findIndex(args, "?") != MainArgs.NOT_FOUND || MainArgs.findIndex(args, "help") != MainArgs.NOT_FOUND; } private static void printUsage() { System.out.println(""); System.out.println("Usage:"); System.out.println(""); System.out.println("Starts a distributed Build Agent"); System.out.println(""); System.out.println(BuildAgent.class.getName() + " [options]"); System.out.println(""); System.out.println("Build Agent options are:"); System.out.println(""); System.out.println(" -" + MAIN_ARG_AGENT_PROPS + " file agent properties file; default " + BuildAgentServiceImpl.DEFAULT_AGENT_PROPERTIES_FILE); System.out.println(" -" + MAIN_ARG_USER_PROPS + " file user defined properties file; default " + BuildAgentServiceImpl.DEFAULT_USER_DEFINED_PROPERTIES_FILE); System.out.println(" -" + MAIN_ARG_SKIP_UI + " run in headless mode"); System.out.println(" -? or -help print this usage message"); System.out.println(""); } public static void kill() { final Thread main = getMainThread(); if (main != null) { main.interrupt(); LOG.info("Waiting for main thread to finish."); try { main.join(30 * 1000); //main.join(); } catch (InterruptedException e) { LOG.error("Error during waiting from Agent to die.", e); } if (main.isAlive()) { main.interrupt(); // how can this happen? LOG.error("Main thread should have died."); } setMainThread(null); } else { LOG.info("WARNING: Kill called, MainThread is null. Doing nothing. Acceptable only in Unit Tests."); } } static interface AgentStatusListener { public void statusChanged(BuildAgentService buildAgentServiceImpl); } }
false
true
public BuildAgent(final String propsFile, final String userDefinedPropertiesFilename, final boolean isSkipUI) { loadProperties(propsFile, userDefinedPropertiesFilename); serviceImpl = new BuildAgentServiceImpl(); serviceImpl.setAgentPropertiesFilename(propsFile); entries = SearchablePropertyEntries.getPropertiesAsEntryArray(entryProperties); if (!isSkipUI) { LOG.info("Loading Build Agent UI (use param -" + MAIN_ARG_SKIP_UI + " to bypass)."); ui = new BuildAgentUI(this); //ui.updateAgentInfoUI(getService()); } else { LOG.info("Bypassing Build Agent UI."); ui = null; } exporter = new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory(), false, true); try { proxy = exporter.export(getService()); } catch (ExportException e) { final String message = "Error exporting service"; LOG.error(message, e); throw new RuntimeException(message, e); } // Use a comma separated list of Unicast Lookup Locaters (URL's) if defined. Useful if multicast isn't working. // @todo It also could have a virtual url called "multicast", // to make the property file more readable and understandable final String registryURLList = configProperties.getProperty(REGISTRY_URL); final LookupLocatorDiscovery lld; if (registryURLList == null) { lld = null; } else { final String[] registryURLs = registryURLList.split(","); final LookupLocator[] lookups = new LookupLocator[registryURLs.length]; for (int i = 0; i < registryURLs.length; i++) { try { lookups[i] = new LookupLocator(registryURLs[i]); } catch (MalformedURLException e) { final String message = "Error creating unicast lookup locator: " + registryURLs[i]; LOG.error(message, e); throw new RuntimeException(message, e); } } lld = new LookupLocatorDiscovery(lookups); } try { joinManager = new JoinManager(getProxy(), entries, this, lld, null); } catch (IOException e) { final String message = "Error starting discovery"; LOG.error(message, e); throw new RuntimeException(message, e); } getJoinManager().getDiscoveryManager().addDiscoveryListener(this); }
public BuildAgent(final String propsFile, final String userDefinedPropertiesFilename, final boolean isSkipUI) { loadProperties(propsFile, userDefinedPropertiesFilename); serviceImpl = new BuildAgentServiceImpl(); serviceImpl.setAgentPropertiesFilename(propsFile); entries = SearchablePropertyEntries.getPropertiesAsEntryArray(entryProperties); if (!isSkipUI) { LOG.info("Loading Build Agent UI (use param -" + MAIN_ARG_SKIP_UI + " to bypass)."); ui = new BuildAgentUI(this); //ui.updateAgentInfoUI(getService()); } else { LOG.info("Bypassing Build Agent UI."); ui = null; } exporter = new BasicJeriExporter(TcpServerEndpoint.getInstance(0), new BasicILFactory(), false, true); try { proxy = exporter.export(getService()); } catch (ExportException e) { final String message = "Error exporting service"; LOG.error(message, e); throw new RuntimeException(message, e); } // Use a comma separated list of Unicast Lookup Locaters (URL's) if defined in agent.properties. // Useful if multicast isn't working. final String registryURLList = configProperties.getProperty(REGISTRY_URL); final LookupLocatorDiscovery lld; if (registryURLList == null) { lld = null; } else { final String[] registryURLs = registryURLList.split(","); final LookupLocator[] lookups = new LookupLocator[registryURLs.length]; for (int i = 0; i < registryURLs.length; i++) { try { lookups[i] = new LookupLocator(registryURLs[i]); } catch (MalformedURLException e) { final String message = "Error creating unicast lookup locator: " + registryURLs[i] + "; " + e.getMessage(); LOG.error(message, e); throw new RuntimeException(message, e); } LOG.info("Using Unicast LookupLocator URL: " + registryURLs[i]); } lld = new LookupLocatorDiscovery(lookups); } try { joinManager = new JoinManager(getProxy(), entries, this, lld, null); } catch (IOException e) { final String message = "Error starting discovery"; LOG.error(message, e); throw new RuntimeException(message, e); } getJoinManager().getDiscoveryManager().addDiscoveryListener(this); }
diff --git a/libdexter/dexter_aux/src/main/java/uk/ac/cam/db538/dexter/aux/struct/Assigner.java b/libdexter/dexter_aux/src/main/java/uk/ac/cam/db538/dexter/aux/struct/Assigner.java index df8c2666..f3c88086 100644 --- a/libdexter/dexter_aux/src/main/java/uk/ac/cam/db538/dexter/aux/struct/Assigner.java +++ b/libdexter/dexter_aux/src/main/java/uk/ac/cam/db538/dexter/aux/struct/Assigner.java @@ -1,196 +1,196 @@ package uk.ac.cam.db538.dexter.aux.struct; import uk.ac.cam.db538.dexter.aux.RuntimeUtils; import uk.ac.cam.db538.dexter.aux.TaintConstants; public final class Assigner { private Assigner() { } public static final TaintExternal newExternal(Object obj, int initialTaint) { TaintExternal tobj = newExternal_Undefined(obj.getClass()); defineExternal(obj, tobj, initialTaint); return tobj; } public static final TaintExternal newExternal_NULL(int initialTaint) { return new TaintImmutable(initialTaint); } public static final TaintExternal newExternal_Undefined(Class<?> objClass) { if (TaintConstants.isImmutableType(objClass)) return new TaintImmutable(); else return new TaintExternal(); } public static final TaintInternal newInternal_NULL(int taint) { TaintExternal t_super = newExternal_NULL(taint); return new TaintInternal(null, t_super); } public static final TaintInternal newInternal_Undefined() { return new TaintInternal(null, null); } public static final void defineExternal(Object obj, TaintExternal tobj, int taint) { taint = TaintConstants.sinkTaint(obj, taint); tobj.define(obj, taint); Cache.insert(obj, tobj); } public static final TaintArrayPrimitive newArrayPrimitive(Object obj, int length, int lengthTaint) { TaintArrayPrimitive tobj = new TaintArrayPrimitive(obj, length, lengthTaint); if (obj != null) Cache.insert(obj, tobj); return tobj; } public static final TaintArrayReference newArrayReference(Object obj, int length, int lengthTaint) { TaintArrayReference tobj = new TaintArrayReference((Object[]) obj, lengthTaint); if (obj != null) Cache.insert(obj, tobj); return tobj; } public static final TaintExternal lookupExternal(Object obj, int taint) { taint = TaintConstants.sinkTaint(obj, taint); if (TaintConstants.isImmutable(obj)) return new TaintImmutable(taint); TaintExternal tobj = (TaintExternal) Cache.get(obj); if (tobj == null) { tobj = new TaintExternal(taint); Cache.insert(obj, tobj); } else if (taint != TaintConstants.EMPTY.value) tobj.set(taint); return tobj; } public static final TaintInternal lookupInternal(Object obj, int taint) { if (obj == null) RuntimeUtils.die("Cannot lookup internal taint of NULL"); else if (!(obj instanceof InternalDataStructure)) RuntimeUtils.die("Given object is not internal"); taint = TaintConstants.sinkTaint(obj, taint); TaintInternal tobj = (TaintInternal) Cache.get(obj); if (tobj == null) { UndefinedObject undef = getConstructedSuperTaint(); if (undef == null) RuntimeUtils.die("Internal object is not initialized"); // define the object tobj = undef.t_obj; tobj.define((InternalDataStructure) obj, new TaintExternal(undef.t_init)); Cache.insert(obj, tobj); } if (taint != TaintConstants.EMPTY.value) { TaintInternal.clearVisited(); tobj.set(taint); } return tobj; } public static final Taint lookupUndecidable(Object obj, int taint) { if (obj == null) return new TaintImmutable(taint); else if (obj instanceof InternalDataStructure) return lookupInternal((InternalDataStructure) obj, taint); else if (obj instanceof Object[]) return lookupArrayReference(obj, taint); else if (obj.getClass().isArray()) return lookupArrayPrimitive(obj, taint); else return lookupExternal(obj, taint); } public static final TaintArrayPrimitive lookupArrayPrimitive(Object obj, int taint) { if (obj == null) return new TaintArrayPrimitive(obj, 0, taint); TaintArrayPrimitive tobj = (TaintArrayPrimitive) Cache.get(obj); if (tobj == null) { int length; if (obj instanceof int[]) length = ((int[]) obj).length; else if (obj instanceof boolean[]) length = ((boolean[]) obj).length; else if (obj instanceof byte[]) length = ((byte[]) obj).length; else if (obj instanceof char[]) length = ((char[]) obj).length; else if (obj instanceof double[]) length = ((double[]) obj).length; else if (obj instanceof float[]) length = ((float[]) obj).length; else if (obj instanceof long[]) length = ((long[]) obj).length; else if (obj instanceof short[]) length = ((short[]) obj).length; else { RuntimeUtils.die("Object is not of a primitive array type"); /* will never get executed */ length = 0; } - tobj = new TaintArrayPrimitive(length, taint, taint); + tobj = new TaintArrayPrimitive(obj, length, taint, taint); Cache.insert(obj, tobj); } else tobj.set(taint); return tobj; } public static final TaintArrayReference lookupArrayReference(Object obj, int taint) { if (obj == null) return new TaintArrayReference(null, taint); TaintArrayReference tobj = (TaintArrayReference) Cache.get(obj); if (tobj == null) { tobj = new TaintArrayReference((Object[]) obj, taint); Cache.insert(obj, tobj); } else tobj.set(taint); return tobj; } private static class UndefinedObject { public TaintInternal t_obj; public int t_init; UndefinedObject(TaintInternal t_obj, int t_init) { this.t_obj = t_obj; this.t_init = t_init; } } private static ThreadLocal<UndefinedObject> T_UNDEF; static { T_UNDEF = new ThreadLocal<UndefinedObject>(); } public static final void eraseConstructedSuperTaint() { T_UNDEF.set(null); } public static final void setConstructedSuperTaint(TaintInternal t_obj, int t_init) { if (T_UNDEF.get() != null) RuntimeUtils.die("Simultaneous construction of two objects"); else T_UNDEF.set(new UndefinedObject(t_obj, t_init)); } private static final UndefinedObject getConstructedSuperTaint() { UndefinedObject result = T_UNDEF.get(); if (result != null) T_UNDEF.set(null); return result; } }
true
true
public static final TaintArrayPrimitive lookupArrayPrimitive(Object obj, int taint) { if (obj == null) return new TaintArrayPrimitive(obj, 0, taint); TaintArrayPrimitive tobj = (TaintArrayPrimitive) Cache.get(obj); if (tobj == null) { int length; if (obj instanceof int[]) length = ((int[]) obj).length; else if (obj instanceof boolean[]) length = ((boolean[]) obj).length; else if (obj instanceof byte[]) length = ((byte[]) obj).length; else if (obj instanceof char[]) length = ((char[]) obj).length; else if (obj instanceof double[]) length = ((double[]) obj).length; else if (obj instanceof float[]) length = ((float[]) obj).length; else if (obj instanceof long[]) length = ((long[]) obj).length; else if (obj instanceof short[]) length = ((short[]) obj).length; else { RuntimeUtils.die("Object is not of a primitive array type"); /* will never get executed */ length = 0; } tobj = new TaintArrayPrimitive(length, taint, taint); Cache.insert(obj, tobj); } else tobj.set(taint); return tobj; }
public static final TaintArrayPrimitive lookupArrayPrimitive(Object obj, int taint) { if (obj == null) return new TaintArrayPrimitive(obj, 0, taint); TaintArrayPrimitive tobj = (TaintArrayPrimitive) Cache.get(obj); if (tobj == null) { int length; if (obj instanceof int[]) length = ((int[]) obj).length; else if (obj instanceof boolean[]) length = ((boolean[]) obj).length; else if (obj instanceof byte[]) length = ((byte[]) obj).length; else if (obj instanceof char[]) length = ((char[]) obj).length; else if (obj instanceof double[]) length = ((double[]) obj).length; else if (obj instanceof float[]) length = ((float[]) obj).length; else if (obj instanceof long[]) length = ((long[]) obj).length; else if (obj instanceof short[]) length = ((short[]) obj).length; else { RuntimeUtils.die("Object is not of a primitive array type"); /* will never get executed */ length = 0; } tobj = new TaintArrayPrimitive(obj, length, taint, taint); Cache.insert(obj, tobj); } else tobj.set(taint); return tobj; }
diff --git a/main/src/main/java/org/vfny/geoserver/global/DataStoreInfo.java b/main/src/main/java/org/vfny/geoserver/global/DataStoreInfo.java index e76b0c2d12..1c7e6706d0 100644 --- a/main/src/main/java/org/vfny/geoserver/global/DataStoreInfo.java +++ b/main/src/main/java/org/vfny/geoserver/global/DataStoreInfo.java @@ -1,494 +1,495 @@ /* 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.global; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.geotools.catalog.Catalog; import org.geotools.catalog.Resolve; import org.geotools.catalog.ResolveChangeEvent; import org.geotools.catalog.ResolveChangeListener; import org.geotools.catalog.Service; import org.geotools.catalog.ServiceInfo; import org.geotools.catalog.defaults.DefaultServiceInfo; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.util.ProgressListener; import org.vfny.geoserver.global.dto.DataStoreInfoDTO; /** * This is the configuration iformation for one DataStore. This class can also * generate real datastores. * <p> * This class implements {@link org.geotools.catalog.Service} interface as a * link to a catalog. * </p> * @author Gabriel Rold?n * @author dzwiers * @author Justin Deoliveira * @version $Id: DataStoreInfo.java,v 1.14 2004/06/26 19:51:24 jive Exp $ */ public class DataStoreInfo extends GlobalLayerSupertype implements Service { /** DataStoreInfo we are representing */ private DataStore dataStore = null; /** ref to the parent class's collection */ private Data data; private String id; private String nameSpaceId; private boolean enabled; private String title; private String _abstract; private Map connectionParams; /** Storage for metadata */ private Map meta; /** * Catalog */ private Catalog catalog; /** * Directory associated with this DataStore. * * <p> * This directory may be used for File based relative paths. * </p> */ File baseDir; /** * URL associated with this DataStore. * * <p> * This directory may be used for URL based relative paths. * </p> */ URL baseURL; /** * DataStoreInfo constructor. * * <p> * Stores the specified data for later use. * </p> * * @param config DataStoreInfoDTO the current configuration to use. * @param data Data a ref to use later to look up related informtion */ public DataStoreInfo(DataStoreInfoDTO config, Data data) { this.data = data; meta = new HashMap(); connectionParams = config.getConnectionParams(); enabled = config.isEnabled(); id = config.getId(); nameSpaceId = config.getNameSpaceId(); title = config.getTitle(); _abstract = config.getAbstract(); catalog = data.getCatalog(); } /** * toDTO purpose. * * <p> * This method is package visible only, and returns a reference to the * GeoServerDTO. This method is unsafe, and should only be used with * extreme caution. * </p> * * @return DataStoreInfoDTO the generated object */ Object toDTO() { DataStoreInfoDTO dto = new DataStoreInfoDTO(); dto.setAbstract(_abstract); dto.setConnectionParams(connectionParams); dto.setEnabled(enabled); dto.setId(id); dto.setNameSpaceId(nameSpaceId); dto.setTitle(title); return dto; } /** * getId purpose. * * <p> * Returns the dataStore's id. * </p> * * @return String the id. */ public String getId() { return id; } protected Map getParams() { Map params = new HashMap(connectionParams); params.put("namespace", getNameSpace().getURI()); return getParams(params, data.getBaseDir().toString()); } /** * Get Connect params. * * <p> * This is used to smooth any relative path kind of issues for any file * URLS. This code should be expanded to deal with any other context * sensitve isses dataStores tend to have. * </p> * * @return DOCUMENT ME! * * @task REVISIT: cache these? */ public static Map getParams(Map m, String baseDir) { Map params = Collections.synchronizedMap(new HashMap(m)); for (Iterator i = params.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); try { //TODO: this code is a pretty big hack, using the name to // determine if the key is a url, could be named something else // and still be a url if (key != null && key.matches(".* *url") && value instanceof String) { String path = (String) value; LOGGER.finer("in string url"); if (path.startsWith("file:")) { path = path.substring(5); // remove 'file:' prefix - File file = new File(baseDir, path); + File file = new File(path); if(!file.exists()) - file = new File(baseDir, path.substring(5)); + file = new File(baseDir, path); entry.setValue(file.toURL().toExternalForm()); } - //Not sure about this } else if (value instanceof URL && ((URL) value).getProtocol().equals("file")) { LOGGER.finer("in URL url"); URL url = (URL) value; String path = url.getPath(); LOGGER.finer("path is " + path); - //if (path.startsWith("data/")){ - File file = new File(baseDir, path); + // try to understand wheter this is a path relative to the data directory + // of if it's an absolute path + File file = new File(path); + if(!file.exists()) + file = new File(baseDir, path); entry.setValue(file.toURL()); - //} } /*else if ("dbtype".equals(key) && value instanceof String) { String val = (String) value; if ((val != null) && val.equals("postgis")) { if (!params.containsKey("charset")) { params.put("charset", data.getGeoServer().getCharSet().toString()); } } } */ } catch (MalformedURLException ignore) { // ignore attempt to fix relative paths } } return params; } /** * By now just uses DataStoreFinder to find a new instance of a * DataStoreInfo capable of process <code>connectionParams</code>. In the * future we can see if it is better to cache or pool DataStores for * performance, but definitely we shouldn't maintain a single * DataStoreInfo as instance variable for synchronizing reassons * * <p> * JG: Umm we actually require a single DataStoreInfo for for locking & * transaction support to work. DataStoreInfo is expected to be thread * aware (that is why it has Transaction Support). * </p> * * @return DataStore * * @throws IllegalStateException if this DataStoreInfo is disabled by * configuration * @throws NoSuchElementException if no DataStoreInfo is found */ public synchronized DataStore getDataStore() throws IllegalStateException, NoSuchElementException { if (!isEnabled()) { throw new IllegalStateException( "this datastore is not enabled, check your configuration"); } Map m = getParams(); if (dataStore == null) { try { dataStore = DataStoreFinder.getDataStore(m); LOGGER.fine("connection established by " + toString()); } catch (Throwable ex) { throw new IllegalStateException("can't create the datastore " + getId() + ": " + ex.getClass().getName() + ": " + ex.getMessage() + "\n" + ex.toString()); } if (dataStore == null) { // If datastore is not present, then disable it // (although no change in config). enabled=false; LOGGER.fine("failed to establish connection with " + toString()); throw new NoSuchElementException( "No datastore found capable of managing " + toString()); } } return dataStore; } /** * getTitle purpose. * * <p> * Returns the dataStore's title. * </p> * * @return String the title. */ public String getTitle() { return title; } /** * getAbstract purpose. * * <p> * Returns the dataStore's abstract. * </p> * * @return String the abstract. */ public String getAbstract() { return _abstract; } /** * isEnabled purpose. * * <p> * Returns true when the data store is enabled. * </p> * * @return true when the data store is enabled. */ public boolean isEnabled() { return enabled; } /** * getNameSpace purpose. * * <p> * Returns the namespace for this datastore. * </p> * * @return NameSpaceInfo the namespace for this datastore. */ public NameSpaceInfo getNameSpace() { return (NameSpaceInfo) data.getNameSpace(getNamesSpacePrefix()); } /** * Access namespace id * * @return DOCUMENT ME! */ public String getNamesSpacePrefix() { return nameSpaceId; } /** * Implement toString. * * @return String * * @see java.lang.Object#toString() */ public String toString() { return new StringBuffer("DataStoreConfig[namespace=").append(getNameSpace() .getPrefix()) .append(", enabled=") .append(isEnabled()) .append(", abstract=") .append(getAbstract()) .append(", connection parameters=") .append(getParams()) .append("]") .toString(); } /** * Implement containsMetaData. * * @param key * * @return * * @see org.geotools.data.MetaData#containsMetaData(java.lang.String) */ public boolean containsMetaData(String key) { return meta.containsKey(key); } /** * Implement putMetaData. * * @param key * @param value * * @see org.geotools.data.MetaData#putMetaData(java.lang.String, * java.lang.Object) */ public void putMetaData(String key, Object value) { meta.put(key, value); } /** * Implement getMetaData. * * @param key * * @return * * @see org.geotools.data.MetaData#getMetaData(java.lang.String) */ public Object getMetaData(String key) { return meta.get(key); } //catalog methods List/*<FeatureTypeInfo>*/ members = new ArrayList(); ServiceInfo info; public void addMember( FeatureTypeInfo ftInfo ) { members.add( ftInfo ); } public List members(ProgressListener monitor) throws IOException { return members; } public boolean canResolve(Class adaptee) { return DataStore.class.isAssignableFrom( adaptee ) || List.class.isAssignableFrom( adaptee ) || ServiceInfo.class.isAssignableFrom( adaptee ); } public Object resolve(Class adaptee, ProgressListener monitor) throws IOException { if ( DataStore.class.isAssignableFrom( adaptee ) ) { return getDataStore(); } if ( List.class.isAssignableFrom( adaptee ) ) { return members( monitor ); } if ( ServiceInfo.class.isAssignableFrom( adaptee ) ) { return getInfo( monitor ); } return null; } public Map getConnectionParams() { return getParams(); } public ServiceInfo getInfo(ProgressListener monitor) throws IOException { if ( info == null ) { synchronized ( this ) { if ( info == null ) { info = new DefaultServiceInfo( getTitle(), null, getAbstract(), null, null, null, null, null ); } } } return info; } public Resolve parent(ProgressListener monitor) throws IOException { return catalog; } public Status getStatus() { if ( isEnabled() ) { return Status.CONNECTED; } return Status.NOTCONNECTED; } public Throwable getMessage() { return null; } public URI getIdentifier() { try { URI uri = new URI( getNameSpace().getURI() ); String path = uri.getPath(); if ( path == null ) { path = getId(); } else { if ( !path.endsWith( "/") ) { path += "/"; } path += getId(); } return new URI( uri.getScheme(), uri.getHost(), path ); } catch (URISyntaxException e) { return null; } } public void addListener(ResolveChangeListener listener) throws UnsupportedOperationException { //events not supported throw new UnsupportedOperationException(); } public void removeListener(ResolveChangeListener listener) { //events not supported } public void fire(ResolveChangeEvent event) { //events not supported } }
false
true
public static Map getParams(Map m, String baseDir) { Map params = Collections.synchronizedMap(new HashMap(m)); for (Iterator i = params.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); try { //TODO: this code is a pretty big hack, using the name to // determine if the key is a url, could be named something else // and still be a url if (key != null && key.matches(".* *url") && value instanceof String) { String path = (String) value; LOGGER.finer("in string url"); if (path.startsWith("file:")) { path = path.substring(5); // remove 'file:' prefix File file = new File(baseDir, path); if(!file.exists()) file = new File(baseDir, path.substring(5)); entry.setValue(file.toURL().toExternalForm()); } //Not sure about this } else if (value instanceof URL && ((URL) value).getProtocol().equals("file")) { LOGGER.finer("in URL url"); URL url = (URL) value; String path = url.getPath(); LOGGER.finer("path is " + path); //if (path.startsWith("data/")){ File file = new File(baseDir, path); entry.setValue(file.toURL()); //} } /*else if ("dbtype".equals(key) && value instanceof String) { String val = (String) value; if ((val != null) && val.equals("postgis")) { if (!params.containsKey("charset")) { params.put("charset", data.getGeoServer().getCharSet().toString()); } } } */ } catch (MalformedURLException ignore) { // ignore attempt to fix relative paths } } return params; }
public static Map getParams(Map m, String baseDir) { Map params = Collections.synchronizedMap(new HashMap(m)); for (Iterator i = params.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); try { //TODO: this code is a pretty big hack, using the name to // determine if the key is a url, could be named something else // and still be a url if (key != null && key.matches(".* *url") && value instanceof String) { String path = (String) value; LOGGER.finer("in string url"); if (path.startsWith("file:")) { path = path.substring(5); // remove 'file:' prefix File file = new File(path); if(!file.exists()) file = new File(baseDir, path); entry.setValue(file.toURL().toExternalForm()); } } else if (value instanceof URL && ((URL) value).getProtocol().equals("file")) { LOGGER.finer("in URL url"); URL url = (URL) value; String path = url.getPath(); LOGGER.finer("path is " + path); // try to understand wheter this is a path relative to the data directory // of if it's an absolute path File file = new File(path); if(!file.exists()) file = new File(baseDir, path); entry.setValue(file.toURL()); } /*else if ("dbtype".equals(key) && value instanceof String) { String val = (String) value; if ((val != null) && val.equals("postgis")) { if (!params.containsKey("charset")) { params.put("charset", data.getGeoServer().getCharSet().toString()); } } } */ } catch (MalformedURLException ignore) { // ignore attempt to fix relative paths } } return params; }
diff --git a/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java b/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java index dfe9a223..722e8f5b 100644 --- a/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java +++ b/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java @@ -1,625 +1,629 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.util; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Stack; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.exceptions.WrappedIOException; import org.apache.pdfbox.exceptions.LoggingObject; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.graphics.PDGraphicsState; import org.apache.pdfbox.util.operator.OperatorProcessor; /** * This class will run through a PDF content stream and execute certain operations * and provide a callback interface for clients that want to do things with the stream. * See the PDFTextStripper class for an example of how to use this class. * * @author <a href="mailto:[email protected]">Ben Litchfield</a> * @version $Revision: 1.38 $ */ public class PDFStreamEngine extends LoggingObject { private static final byte[] SPACE_BYTES = { (byte)32 }; private PDGraphicsState graphicsState = null; private Matrix textMatrix = null; private Matrix textLineMatrix = null; private Stack graphicsStack = new Stack(); //private PDResources resources = null; private Map operators = new HashMap(); private Stack streamResourcesStack = new Stack(); private PDPage page; private Map documentFontCache = new HashMap(); /** * This is a simple internal class used by the Stream engine to handle the * resources stack. */ private static class StreamResources { private Map fonts; private Map colorSpaces; private Map xobjects; private Map graphicsStates; private PDResources resources; } /** * Constructor. */ public PDFStreamEngine() { //default constructor } /** * Constructor with engine properties. The property keys are all * PDF operators, the values are class names used to execute those * operators. * * @param properties The engine properties. * * @throws IOException If there is an error setting the engine properties. */ public PDFStreamEngine( Properties properties ) throws IOException { if( properties == null ) { throw new NullPointerException( "properties cannot be null" ); } try { Iterator keys = properties.keySet().iterator(); while( keys.hasNext() ) { String operator = (String)keys.next(); String operatorClass = properties.getProperty( operator ); OperatorProcessor op = (OperatorProcessor)Class.forName( operatorClass ).newInstance(); registerOperatorProcessor(operator, op); } } catch( Exception e ) { throw new WrappedIOException( e ); } } /** * Register a custom operator processor with the engine. * * @param operator The operator as a string. * @param op Processor instance. */ public void registerOperatorProcessor( String operator, OperatorProcessor op ) { op.setContext( this ); operators.put( operator, op ); } /** * This method must be called between processing documents. The * PDFStreamEngine caches information for the document between pages * and this will release the cached information. This only needs * to be called if processing a new document. * */ public void resetEngine() { documentFontCache.clear(); } /** * This will process the contents of the stream. * * @param aPage The page. * @param resources The location to retrieve resources. * @param cosStream the Stream to execute. * * * @throws IOException if there is an error accessing the stream. */ public void processStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException { graphicsState = new PDGraphicsState(); textMatrix = null; textLineMatrix = null; graphicsStack.clear(); streamResourcesStack.clear(); processSubStream( aPage, resources, cosStream ); } /** * Process a sub stream of the current stream. * * @param aPage The page used for drawing. * @param resources The resources used when processing the stream. * @param cosStream The stream to process. * * @throws IOException If there is an exception while processing the stream. */ public void processSubStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException { page = aPage; if( resources != null ) { StreamResources sr = new StreamResources(); sr.fonts = resources.getFonts( documentFontCache ); sr.colorSpaces = resources.getColorSpaces(); sr.xobjects = resources.getXObjects(); sr.graphicsStates = resources.getGraphicsStates(); sr.resources = resources; streamResourcesStack.push(sr); } try { List arguments = new ArrayList(); List tokens = cosStream.getStreamTokens(); if( tokens != null ) { Iterator iter = tokens.iterator(); while( iter.hasNext() ) { Object next = iter.next(); if( next instanceof COSObject ) { arguments.add( ((COSObject)next).getObject() ); } else if( next instanceof PDFOperator ) { processOperator( (PDFOperator)next, arguments ); arguments = new ArrayList(); } else { arguments.add( next ); } logger().fine("token: " + next.toString()); } } } finally { if( resources != null ) { streamResourcesStack.pop(); } } } /** * A method provided as an event interface to allow a subclass to perform * some specific functionality when a character needs to be displayed. * * @param text The character to be displayed. */ protected void showCharacter( TextPosition text ) { //subclasses can override to provide specific functionality. } /** * You should override this method if you want to perform an action when a * string is being shown. * * @param string The string to display. * * @throws IOException If there is an error showing the string */ public void showString( byte[] string ) throws IOException { float[] individualWidths = new float[2048]; float spaceWidth = 0; float spacing = 0; StringBuffer stringResult = new StringBuffer(string.length); float characterHorizontalDisplacement = 0; float characterVerticalDisplacement = 0; float spaceDisplacement = 0; float fontSize = graphicsState.getTextState().getFontSize(); float horizontalScaling = graphicsState.getTextState().getHorizontalScalingPercent()/100f; float verticalScaling = horizontalScaling;//not sure if this is right but what else to do??? float rise = graphicsState.getTextState().getRise(); final float wordSpacing = graphicsState.getTextState().getWordSpacing(); final float characterSpacing = graphicsState.getTextState().getCharacterSpacing(); float wordSpacingDisplacement = 0; //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float averageWidth = font.getAverageFontWidth(); Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,rise); initialMatrix.setValue(2,2,1); //this int codeLength = 1; Matrix ctm = graphicsState.getCurrentTransformationMatrix(); //lets see what the space displacement should be spaceDisplacement = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); if( spaceDisplacement == 0 ) { spaceDisplacement = (averageWidth/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceDisplacement *= .80f; } int pageRotation = page.findRotation(); Matrix trm = initialMatrix.multiply( textMatrix ).multiply( ctm ); float x = trm.getValue(2,0); float y = trm.getValue(2,1); if( pageRotation == 0 ) { trm.setValue( 2,1, -y + page.findMediaBox().getHeight() ); } else if( pageRotation == 90 || pageRotation == -270 ) { trm.setValue( 2,0, y ); trm.setValue( 2,1, x ); } else if( pageRotation == 270 || pageRotation == -90 ) { trm.setValue( 2,0, -y + page.findMediaBox().getHeight() ); trm.setValue( 2,1, x ); } float xScale = trm.getXScale(); float yScale = trm.getYScale(); float xPos = trm.getXPosition(); float yPos = trm.getYPosition(); spaceWidth = spaceDisplacement * xScale * fontSize; wordSpacingDisplacement = wordSpacing*xScale * fontSize; float totalStringWidth = 0; for( int i=0; i<string.length; i+=codeLength ) { codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement characterHorizontalDisplacement = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); characterVerticalDisplacement = Math.max( characterVerticalDisplacement, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // if( (string[i] == 0x20) && c != null && c.equals( " " ) ) { spacing = wordSpacing + characterSpacing; } else { spacing = characterSpacing; } // We want to update the textMatrix using the width, in text space units. // //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; //todo, need to compute the vertical displacement float ty = 0; float tx = ((characterHorizontalDisplacement-adjustment/glyphSpaceToTextSpaceFactor)*fontSize + spacing) *horizontalScaling; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); float xPosBefore = textMatrix.getXPosition(); float yPosBefore = textMatrix.getYPosition(); textMatrix = td.multiply( textMatrix ); float width = 0; if( pageRotation == 0 ) { width = (textMatrix.getXPosition() - xPosBefore); } else if( pageRotation == 90 || pageRotation == -270) { width = (textMatrix.getYPosition() - yPosBefore); } else if( pageRotation == 270 || pageRotation == -90 ) { width = (yPosBefore - textMatrix.getYPosition()); } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { float widthOfEachCharacterForCode = width/c.length(); for( int j=0; j<c.length(); j++) { if( stringResult.length()+j <individualWidths.length ) { if( c.equals("-")) { //System.out.println( "stringResult.length()+j=" + (widthOfEachCharacterForCode)); } individualWidths[stringResult.length()+j] = widthOfEachCharacterForCode; } } + } else { + // PDFBOX-373: Replace a null entry with "?" so it is + // not printed as "(null)" + c = "?"; } totalStringWidth += width; stringResult.append( c ); } float totalStringHeight = characterVerticalDisplacement * fontSize * yScale; String resultingString = stringResult.toString(); if( individualWidths.length != resultingString.length() ) { float[] tmp = new float[resultingString.length()]; System.arraycopy( individualWidths, 0, tmp, 0, Math.min( individualWidths.length, resultingString.length() )); individualWidths = tmp; if( resultingString.equals( "- " )) { //System.out.println( "EQUALS " + individualWidths[0] ); } } showCharacter( new TextPosition( xPos, yPos, xScale, yScale, totalStringWidth, individualWidths, totalStringHeight, spaceWidth, stringResult.toString(), font, fontSize, wordSpacingDisplacement )); } /** * This is used to handle an operation. * * @param operation The operation to perform. * @param arguments The list of arguments. * * @throws IOException If there is an error processing the operation. */ public void processOperator( String operation, List arguments ) throws IOException { try{ PDFOperator oper = PDFOperator.getOperator( operation ); processOperator( oper, arguments ); } catch (IOException e) { logger().warning (e.toString() + "\n at\n" + FullStackTrace(e)); } } /** * This is used to handle an operation. * * @param operator The operation to perform. * @param arguments The list of arguments. * * @throws IOException If there is an error processing the operation. */ protected void processOperator( PDFOperator operator, List arguments ) throws IOException { try{ String operation = operator.getOperation(); OperatorProcessor processor = (OperatorProcessor)operators.get( operation ); if( processor != null ) { processor.process( operator, arguments ); } } catch (Exception e) { logger().warning (e.toString() + "\n at\n" + FullStackTrace(e)); } } /** * @return Returns the colorSpaces. */ public Map getColorSpaces() { return ((StreamResources) streamResourcesStack.peek()).colorSpaces; } /** * @return Returns the colorSpaces. */ public Map getXObjects() { return ((StreamResources) streamResourcesStack.peek()).xobjects; } /** * @param value The colorSpaces to set. */ public void setColorSpaces(Map value) { ((StreamResources) streamResourcesStack.peek()).colorSpaces = value; } /** * @return Returns the fonts. */ public Map getFonts() { return ((StreamResources) streamResourcesStack.peek()).fonts; } /** * @param value The fonts to set. */ public void setFonts(Map value) { ((StreamResources) streamResourcesStack.peek()).fonts = value; } /** * @return Returns the graphicsStack. */ public Stack getGraphicsStack() { return graphicsStack; } /** * @param value The graphicsStack to set. */ public void setGraphicsStack(Stack value) { graphicsStack = value; } /** * @return Returns the graphicsState. */ public PDGraphicsState getGraphicsState() { return graphicsState; } /** * @param value The graphicsState to set. */ public void setGraphicsState(PDGraphicsState value) { graphicsState = value; } /** * @return Returns the graphicsStates. */ public Map getGraphicsStates() { return ((StreamResources) streamResourcesStack.peek()).graphicsStates; } /** * @param value The graphicsStates to set. */ public void setGraphicsStates(Map value) { ((StreamResources) streamResourcesStack.peek()).graphicsStates = value; } /** * @return Returns the textLineMatrix. */ public Matrix getTextLineMatrix() { return textLineMatrix; } /** * @param value The textLineMatrix to set. */ public void setTextLineMatrix(Matrix value) { textLineMatrix = value; } /** * @return Returns the textMatrix. */ public Matrix getTextMatrix() { return textMatrix; } /** * @param value The textMatrix to set. */ public void setTextMatrix(Matrix value) { textMatrix = value; } /** * @return Returns the resources. */ public PDResources getResources() { return ((StreamResources) streamResourcesStack.peek()).resources; } /** * Get the current page that is being processed. * * @return The page being processed. */ public PDPage getCurrentPage() { return page; } }
true
true
public void showString( byte[] string ) throws IOException { float[] individualWidths = new float[2048]; float spaceWidth = 0; float spacing = 0; StringBuffer stringResult = new StringBuffer(string.length); float characterHorizontalDisplacement = 0; float characterVerticalDisplacement = 0; float spaceDisplacement = 0; float fontSize = graphicsState.getTextState().getFontSize(); float horizontalScaling = graphicsState.getTextState().getHorizontalScalingPercent()/100f; float verticalScaling = horizontalScaling;//not sure if this is right but what else to do??? float rise = graphicsState.getTextState().getRise(); final float wordSpacing = graphicsState.getTextState().getWordSpacing(); final float characterSpacing = graphicsState.getTextState().getCharacterSpacing(); float wordSpacingDisplacement = 0; //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float averageWidth = font.getAverageFontWidth(); Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,rise); initialMatrix.setValue(2,2,1); //this int codeLength = 1; Matrix ctm = graphicsState.getCurrentTransformationMatrix(); //lets see what the space displacement should be spaceDisplacement = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); if( spaceDisplacement == 0 ) { spaceDisplacement = (averageWidth/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceDisplacement *= .80f; } int pageRotation = page.findRotation(); Matrix trm = initialMatrix.multiply( textMatrix ).multiply( ctm ); float x = trm.getValue(2,0); float y = trm.getValue(2,1); if( pageRotation == 0 ) { trm.setValue( 2,1, -y + page.findMediaBox().getHeight() ); } else if( pageRotation == 90 || pageRotation == -270 ) { trm.setValue( 2,0, y ); trm.setValue( 2,1, x ); } else if( pageRotation == 270 || pageRotation == -90 ) { trm.setValue( 2,0, -y + page.findMediaBox().getHeight() ); trm.setValue( 2,1, x ); } float xScale = trm.getXScale(); float yScale = trm.getYScale(); float xPos = trm.getXPosition(); float yPos = trm.getYPosition(); spaceWidth = spaceDisplacement * xScale * fontSize; wordSpacingDisplacement = wordSpacing*xScale * fontSize; float totalStringWidth = 0; for( int i=0; i<string.length; i+=codeLength ) { codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement characterHorizontalDisplacement = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); characterVerticalDisplacement = Math.max( characterVerticalDisplacement, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // if( (string[i] == 0x20) && c != null && c.equals( " " ) ) { spacing = wordSpacing + characterSpacing; } else { spacing = characterSpacing; } // We want to update the textMatrix using the width, in text space units. // //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; //todo, need to compute the vertical displacement float ty = 0; float tx = ((characterHorizontalDisplacement-adjustment/glyphSpaceToTextSpaceFactor)*fontSize + spacing) *horizontalScaling; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); float xPosBefore = textMatrix.getXPosition(); float yPosBefore = textMatrix.getYPosition(); textMatrix = td.multiply( textMatrix ); float width = 0; if( pageRotation == 0 ) { width = (textMatrix.getXPosition() - xPosBefore); } else if( pageRotation == 90 || pageRotation == -270) { width = (textMatrix.getYPosition() - yPosBefore); } else if( pageRotation == 270 || pageRotation == -90 ) { width = (yPosBefore - textMatrix.getYPosition()); } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { float widthOfEachCharacterForCode = width/c.length(); for( int j=0; j<c.length(); j++) { if( stringResult.length()+j <individualWidths.length ) { if( c.equals("-")) { //System.out.println( "stringResult.length()+j=" + (widthOfEachCharacterForCode)); } individualWidths[stringResult.length()+j] = widthOfEachCharacterForCode; } } } totalStringWidth += width; stringResult.append( c ); } float totalStringHeight = characterVerticalDisplacement * fontSize * yScale; String resultingString = stringResult.toString(); if( individualWidths.length != resultingString.length() ) { float[] tmp = new float[resultingString.length()]; System.arraycopy( individualWidths, 0, tmp, 0, Math.min( individualWidths.length, resultingString.length() )); individualWidths = tmp; if( resultingString.equals( "- " )) { //System.out.println( "EQUALS " + individualWidths[0] ); } } showCharacter( new TextPosition( xPos, yPos, xScale, yScale, totalStringWidth, individualWidths, totalStringHeight, spaceWidth, stringResult.toString(), font, fontSize, wordSpacingDisplacement )); }
public void showString( byte[] string ) throws IOException { float[] individualWidths = new float[2048]; float spaceWidth = 0; float spacing = 0; StringBuffer stringResult = new StringBuffer(string.length); float characterHorizontalDisplacement = 0; float characterVerticalDisplacement = 0; float spaceDisplacement = 0; float fontSize = graphicsState.getTextState().getFontSize(); float horizontalScaling = graphicsState.getTextState().getHorizontalScalingPercent()/100f; float verticalScaling = horizontalScaling;//not sure if this is right but what else to do??? float rise = graphicsState.getTextState().getRise(); final float wordSpacing = graphicsState.getTextState().getWordSpacing(); final float characterSpacing = graphicsState.getTextState().getCharacterSpacing(); float wordSpacingDisplacement = 0; //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float averageWidth = font.getAverageFontWidth(); Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,rise); initialMatrix.setValue(2,2,1); //this int codeLength = 1; Matrix ctm = graphicsState.getCurrentTransformationMatrix(); //lets see what the space displacement should be spaceDisplacement = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); if( spaceDisplacement == 0 ) { spaceDisplacement = (averageWidth/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceDisplacement *= .80f; } int pageRotation = page.findRotation(); Matrix trm = initialMatrix.multiply( textMatrix ).multiply( ctm ); float x = trm.getValue(2,0); float y = trm.getValue(2,1); if( pageRotation == 0 ) { trm.setValue( 2,1, -y + page.findMediaBox().getHeight() ); } else if( pageRotation == 90 || pageRotation == -270 ) { trm.setValue( 2,0, y ); trm.setValue( 2,1, x ); } else if( pageRotation == 270 || pageRotation == -90 ) { trm.setValue( 2,0, -y + page.findMediaBox().getHeight() ); trm.setValue( 2,1, x ); } float xScale = trm.getXScale(); float yScale = trm.getYScale(); float xPos = trm.getXPosition(); float yPos = trm.getYPosition(); spaceWidth = spaceDisplacement * xScale * fontSize; wordSpacingDisplacement = wordSpacing*xScale * fontSize; float totalStringWidth = 0; for( int i=0; i<string.length; i+=codeLength ) { codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement characterHorizontalDisplacement = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); characterVerticalDisplacement = Math.max( characterVerticalDisplacement, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // if( (string[i] == 0x20) && c != null && c.equals( " " ) ) { spacing = wordSpacing + characterSpacing; } else { spacing = characterSpacing; } // We want to update the textMatrix using the width, in text space units. // //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; //todo, need to compute the vertical displacement float ty = 0; float tx = ((characterHorizontalDisplacement-adjustment/glyphSpaceToTextSpaceFactor)*fontSize + spacing) *horizontalScaling; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); float xPosBefore = textMatrix.getXPosition(); float yPosBefore = textMatrix.getYPosition(); textMatrix = td.multiply( textMatrix ); float width = 0; if( pageRotation == 0 ) { width = (textMatrix.getXPosition() - xPosBefore); } else if( pageRotation == 90 || pageRotation == -270) { width = (textMatrix.getYPosition() - yPosBefore); } else if( pageRotation == 270 || pageRotation == -90 ) { width = (yPosBefore - textMatrix.getYPosition()); } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { float widthOfEachCharacterForCode = width/c.length(); for( int j=0; j<c.length(); j++) { if( stringResult.length()+j <individualWidths.length ) { if( c.equals("-")) { //System.out.println( "stringResult.length()+j=" + (widthOfEachCharacterForCode)); } individualWidths[stringResult.length()+j] = widthOfEachCharacterForCode; } } } else { // PDFBOX-373: Replace a null entry with "?" so it is // not printed as "(null)" c = "?"; } totalStringWidth += width; stringResult.append( c ); } float totalStringHeight = characterVerticalDisplacement * fontSize * yScale; String resultingString = stringResult.toString(); if( individualWidths.length != resultingString.length() ) { float[] tmp = new float[resultingString.length()]; System.arraycopy( individualWidths, 0, tmp, 0, Math.min( individualWidths.length, resultingString.length() )); individualWidths = tmp; if( resultingString.equals( "- " )) { //System.out.println( "EQUALS " + individualWidths[0] ); } } showCharacter( new TextPosition( xPos, yPos, xScale, yScale, totalStringWidth, individualWidths, totalStringHeight, spaceWidth, stringResult.toString(), font, fontSize, wordSpacingDisplacement )); }
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ConditionalPermissions.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ConditionalPermissions.java index 526fc62c..8c8ef58e 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ConditionalPermissions.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ConditionalPermissions.java @@ -1,234 +1,235 @@ /******************************************************************************* * Copyright (c) 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.osgi.framework.internal.core; import java.security.Permission; import java.security.PermissionCollection; import java.util.Enumeration; import java.util.Vector; import org.osgi.framework.FrameworkEvent; import org.osgi.service.condpermadmin.Condition; import org.osgi.service.condpermadmin.ConditionalPermissionAdmin; /** * * This class manages the Permissions for a given code source. It tracks the * permissions that have yet to be satisfied as well as conditions that are * already satisfied. */ public class ConditionalPermissions extends PermissionCollection { private static final long serialVersionUID = 3907215965749000496L; AbstractBundle bundle; /** * This is the list of satisfiedCPIs that we are waiting to process in bulk * when evaluating the satisfied permissions. Elements are of type * ConditionalPermissionInfoImpl. */ Vector satisfiedCPIs = new Vector(); /** * This is set contains that ConditionalPermissionInfos that are satisfied * and immutable. */ ConditionalPermissionSet satisfiedCPS = new ConditionalPermissionSet(new ConditionalPermissionInfoImpl[0], new Condition[0]); /** * These are the CPIs that may match this CodeSource. Elements are of type * ConditionalPermissionSet. */ Vector satisfiableCPSs = new Vector(); boolean empty; /** * Constructs a ConditionalPermission for the given bundle. * * @param bundle the bundle for which this ConditionalPermission tracks Permissions. */ public ConditionalPermissions(AbstractBundle bundle, ConditionalPermissionAdmin cpa) { this.bundle = bundle; Enumeration en = cpa.getConditionalPermissionInfos(); while (en.hasMoreElements()) { ConditionalPermissionInfoImpl cpi = (ConditionalPermissionInfoImpl) en.nextElement(); checkConditionalPermissionInfo(cpi); } } void checkConditionalPermissionInfo(ConditionalPermissionInfoImpl cpi) { try { // first remove the cpi incase of an update removeCPI(cpi); Condition conds[] = cpi.getConditions(bundle); if (conds == null) { /* Couldn't process the conditions, so we can't use them */ return; } boolean satisfied = true; for (int i = 0; i < conds.length; i++) { Condition cond = conds[i]; if (cond.isMutable()) { satisfied = false; } else if (!cond.isSatisfied()) {// Note: the RFC says if !mutable, evaluated must be true /* * We can just dump here since we have an immutable and * unsatisfied condition. */ return; } else { conds[i] = null; /* We can remove satisfied conditions */ } } if (satisfied) { satisfiedCPIs.add(cpi); } else { satisfiableCPSs.add(new ConditionalPermissionSet(new ConditionalPermissionInfoImpl[] {cpi}, conds)); } } catch (Exception e) { bundle.framework.publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e); } } private void removeCPI(ConditionalPermissionInfoImpl cpi) { satisfiedCPIs.remove(cpi); satisfiedCPS.remove(cpi); ConditionalPermissionSet cpsArray[] = (ConditionalPermissionSet[]) satisfiableCPSs.toArray(new ConditionalPermissionSet[0]); for (int i = 0; i < cpsArray.length; i++) if (cpsArray[i].remove(cpi)) satisfiableCPSs.remove(cpsArray[i]); } /** * This method is not implemented since this PermissionCollection should * only be used by the ConditionalPolicy which never calls this method. * * @see java.security.PermissionCollection#elements() */ public void add(Permission perm) { // do nothing } public boolean implies(Permission perm) { processPending(); boolean newEmpty = !satisfiedCPS.isNonEmpty(); if (!newEmpty && satisfiedCPS.implies(perm)) { this.empty = false; return true; } boolean satisfied = false; Vector unevalCondsSets = null; SecurityManager sm = System.getSecurityManager(); FrameworkSecurityManager fsm = null; if (sm instanceof FrameworkSecurityManager) { fsm = (FrameworkSecurityManager) sm; } ConditionalPermissionSet cpsArray[] = (ConditionalPermissionSet[]) satisfiableCPSs.toArray(new ConditionalPermissionSet[0]); cpsLoop: for (int i = 0; i < cpsArray.length; i++) { if (cpsArray[i].isNonEmpty()) { newEmpty = false; + Condition conds[] = cpsArray[i].getNeededConditions(); + // check mutable !isPostponed conditions first; + // note that !mutable conditions have already been evaluated + for (int j = 0; j < conds.length; j++) + if (conds[j] != null && !conds[j].isPostponed() && !conds[j].isSatisfied()) + continue cpsLoop; + // check the implies now if (cpsArray[i].implies(perm)) { - Condition conds[] = cpsArray[i].getNeededConditions(); + // the permission is implied; the only unevaluated conditions left are mutable postponed conditions + // postpone their evaluation until the end Vector unevaluatedConds = null; for (int j = 0; j < conds.length; j++) { - if (conds[j] == null) { - continue; - } - if (!conds[j].isPostponed() && !conds[j].isSatisfied()) { - continue cpsLoop; - } - if (conds[j].isPostponed()) { + if (conds[j] != null && conds[j].isPostponed()) { if (fsm == null) { // If there is no FrameworkSecurityManager, we must evaluate now - if (!conds[j].isSatisfied()) { + if (!conds[j].isSatisfied()) continue cpsLoop; - } } else { - if (unevaluatedConds == null) { + if (unevaluatedConds == null) unevaluatedConds = new Vector(); - } unevaluatedConds.add(conds[j]); } } } if (unevaluatedConds == null) { + // no postponed conditions exist return true now this.empty = false; return true; } if (unevalCondsSets == null) unevalCondsSets = new Vector(2); unevalCondsSets.add(unevaluatedConds.toArray(new Condition[0])); satisfied = true; } } else { - satisfiedCPIs.remove(cpsArray[i]); + satisfiableCPSs.remove(cpsArray[i]); } } this.empty = newEmpty; if (satisfied && fsm != null) { // There must be at least one set of Conditions to evaluate since // we didn't return right we we realized the permission was satisfied // so unevalCondsSets must be non-null. Condition[][] condArray = (Condition[][]) unevalCondsSets.toArray(new Condition[0][]); satisfied = fsm.addConditionsForDomain(condArray); } return satisfied; } /** * Process any satisfiedCPIs that have been added. */ private void processPending() { if (satisfiedCPIs.size() > 0) { synchronized (satisfiedCPIs) { for (int i = 0; i < satisfiedCPIs.size(); i++) { ConditionalPermissionInfoImpl cpi = (ConditionalPermissionInfoImpl) satisfiedCPIs.get(i); if (!cpi.isDeleted()) satisfiedCPS.addConditionalPermissionInfo(cpi); } satisfiedCPIs.clear(); } } } /** * This method is not implemented since this PermissionCollection should * only be used by the ConditionalPolicy which never calls this method. * * @return always returns null. * * @see java.security.PermissionCollection#elements() */ public Enumeration elements() { return null; } /** * This method returns true if there are no ConditionalPermissionInfos in * this PermissionCollection. The empty condition is only checked during the * implies method, it should only be checked after implies has been called. * * @return false if there are any Conditions that may provide permissions to * this bundle. */ boolean isEmpty() { return empty; } /** * @param refreshedBundles */ void unresolvePermissions(AbstractBundle[] refreshedBundles) { satisfiedCPS.unresolvePermissions(refreshedBundles); synchronized (satisfiableCPSs) { Enumeration en = satisfiableCPSs.elements(); while (en.hasMoreElements()) { ConditionalPermissionSet cs = (ConditionalPermissionSet) en.nextElement(); cs.unresolvePermissions(refreshedBundles); } } } }
false
true
public boolean implies(Permission perm) { processPending(); boolean newEmpty = !satisfiedCPS.isNonEmpty(); if (!newEmpty && satisfiedCPS.implies(perm)) { this.empty = false; return true; } boolean satisfied = false; Vector unevalCondsSets = null; SecurityManager sm = System.getSecurityManager(); FrameworkSecurityManager fsm = null; if (sm instanceof FrameworkSecurityManager) { fsm = (FrameworkSecurityManager) sm; } ConditionalPermissionSet cpsArray[] = (ConditionalPermissionSet[]) satisfiableCPSs.toArray(new ConditionalPermissionSet[0]); cpsLoop: for (int i = 0; i < cpsArray.length; i++) { if (cpsArray[i].isNonEmpty()) { newEmpty = false; if (cpsArray[i].implies(perm)) { Condition conds[] = cpsArray[i].getNeededConditions(); Vector unevaluatedConds = null; for (int j = 0; j < conds.length; j++) { if (conds[j] == null) { continue; } if (!conds[j].isPostponed() && !conds[j].isSatisfied()) { continue cpsLoop; } if (conds[j].isPostponed()) { if (fsm == null) { // If there is no FrameworkSecurityManager, we must evaluate now if (!conds[j].isSatisfied()) { continue cpsLoop; } } else { if (unevaluatedConds == null) { unevaluatedConds = new Vector(); } unevaluatedConds.add(conds[j]); } } } if (unevaluatedConds == null) { this.empty = false; return true; } if (unevalCondsSets == null) unevalCondsSets = new Vector(2); unevalCondsSets.add(unevaluatedConds.toArray(new Condition[0])); satisfied = true; } } else { satisfiedCPIs.remove(cpsArray[i]); } } this.empty = newEmpty; if (satisfied && fsm != null) { // There must be at least one set of Conditions to evaluate since // we didn't return right we we realized the permission was satisfied // so unevalCondsSets must be non-null. Condition[][] condArray = (Condition[][]) unevalCondsSets.toArray(new Condition[0][]); satisfied = fsm.addConditionsForDomain(condArray); } return satisfied; }
public boolean implies(Permission perm) { processPending(); boolean newEmpty = !satisfiedCPS.isNonEmpty(); if (!newEmpty && satisfiedCPS.implies(perm)) { this.empty = false; return true; } boolean satisfied = false; Vector unevalCondsSets = null; SecurityManager sm = System.getSecurityManager(); FrameworkSecurityManager fsm = null; if (sm instanceof FrameworkSecurityManager) { fsm = (FrameworkSecurityManager) sm; } ConditionalPermissionSet cpsArray[] = (ConditionalPermissionSet[]) satisfiableCPSs.toArray(new ConditionalPermissionSet[0]); cpsLoop: for (int i = 0; i < cpsArray.length; i++) { if (cpsArray[i].isNonEmpty()) { newEmpty = false; Condition conds[] = cpsArray[i].getNeededConditions(); // check mutable !isPostponed conditions first; // note that !mutable conditions have already been evaluated for (int j = 0; j < conds.length; j++) if (conds[j] != null && !conds[j].isPostponed() && !conds[j].isSatisfied()) continue cpsLoop; // check the implies now if (cpsArray[i].implies(perm)) { // the permission is implied; the only unevaluated conditions left are mutable postponed conditions // postpone their evaluation until the end Vector unevaluatedConds = null; for (int j = 0; j < conds.length; j++) { if (conds[j] != null && conds[j].isPostponed()) { if (fsm == null) { // If there is no FrameworkSecurityManager, we must evaluate now if (!conds[j].isSatisfied()) continue cpsLoop; } else { if (unevaluatedConds == null) unevaluatedConds = new Vector(); unevaluatedConds.add(conds[j]); } } } if (unevaluatedConds == null) { // no postponed conditions exist return true now this.empty = false; return true; } if (unevalCondsSets == null) unevalCondsSets = new Vector(2); unevalCondsSets.add(unevaluatedConds.toArray(new Condition[0])); satisfied = true; } } else { satisfiableCPSs.remove(cpsArray[i]); } } this.empty = newEmpty; if (satisfied && fsm != null) { // There must be at least one set of Conditions to evaluate since // we didn't return right we we realized the permission was satisfied // so unevalCondsSets must be non-null. Condition[][] condArray = (Condition[][]) unevalCondsSets.toArray(new Condition[0][]); satisfied = fsm.addConditionsForDomain(condArray); } return satisfied; }
diff --git a/src/org/startsmall/openalarm/preference/RingtonePreference.java b/src/org/startsmall/openalarm/preference/RingtonePreference.java index 1077c7d..eae1d0b 100644 --- a/src/org/startsmall/openalarm/preference/RingtonePreference.java +++ b/src/org/startsmall/openalarm/preference/RingtonePreference.java @@ -1,53 +1,55 @@ package org.startsmall.openalarm; import android.content.Context; import android.net.Uri; import android.media.Ringtone; import android.media.RingtoneManager; import android.text.TextUtils; interface IRingtoneChangedListener { public void onRingtoneChanged(Uri uri); } class RingtonePreference extends android.preference.RingtonePreference { IRingtoneChangedListener mRingtoneChangedListener; public RingtonePreference(Context context) { super(context); setShowDefault(true); setShowSilent(true); } @SuppressWarnings("unused") public void setRingtoneChangedListener(IRingtoneChangedListener listener) { mRingtoneChangedListener = listener; } public Uri getRingtoneUri() { String uriString = getPersistedString(""); return TextUtils.isEmpty(uriString) ? null : Uri.parse(uriString); } public void setRingtoneUri(Uri ringtoneUri) { super.onSaveRingtone(ringtoneUri); if (ringtoneUri != null) { Ringtone ringtone = RingtoneManager.getRingtone(getContext(), ringtoneUri); - setSummary(ringtone.getTitle(getContext())); + if (ringtone != null) { + setSummary(ringtone.getTitle(getContext())); + } } } @Override protected void onSaveRingtone(Uri ringtoneUri) { setRingtoneUri(ringtoneUri); if(mRingtoneChangedListener != null) { mRingtoneChangedListener.onRingtoneChanged(ringtoneUri); } } @Override protected Uri onRestoreRingtone() { return getRingtoneUri(); } }
true
true
public void setRingtoneUri(Uri ringtoneUri) { super.onSaveRingtone(ringtoneUri); if (ringtoneUri != null) { Ringtone ringtone = RingtoneManager.getRingtone(getContext(), ringtoneUri); setSummary(ringtone.getTitle(getContext())); } }
public void setRingtoneUri(Uri ringtoneUri) { super.onSaveRingtone(ringtoneUri); if (ringtoneUri != null) { Ringtone ringtone = RingtoneManager.getRingtone(getContext(), ringtoneUri); if (ringtone != null) { setSummary(ringtone.getTitle(getContext())); } } }
diff --git a/E-Adventure/src/es/eucm/eadventure/engine/core/gui/hud/contextualhud/ActionButtons.java b/E-Adventure/src/es/eucm/eadventure/engine/core/gui/hud/contextualhud/ActionButtons.java index 91f74fb4..78db1bb0 100644 --- a/E-Adventure/src/es/eucm/eadventure/engine/core/gui/hud/contextualhud/ActionButtons.java +++ b/E-Adventure/src/es/eucm/eadventure/engine/core/gui/hud/contextualhud/ActionButtons.java @@ -1,530 +1,530 @@ /******************************************************************************* * <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM> * research group. * * Copyright 2005-2010 <e-UCM> research group. * * You can access a list of all the contributors to <e-Adventure> at: * http://e-adventure.e-ucm.es/contributors * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of <e-Adventure>, version 1.2. * * <e-Adventure> 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. * * <e-Adventure> 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 <e-Adventure>. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package es.eucm.eadventure.engine.core.gui.hud.contextualhud; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import es.eucm.eadventure.common.data.chapter.Action; import es.eucm.eadventure.common.data.chapter.CustomAction; import es.eucm.eadventure.common.gui.TC; import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalElement; import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalItem; import es.eucm.eadventure.engine.core.control.functionaldata.FunctionalNPC; import es.eucm.eadventure.engine.core.gui.GUI; /** * This class contains all the graphical information about the action buttons */ public class ActionButtons { /** * Hand index action button */ public static final int ACTIONBUTTON_HAND = 0; /** * Eye index action button */ public static final int ACTIONBUTTON_EYE = 1; /** * Mouth index action button */ public static final int ACTIONBUTTON_MOUTH = 2; /** * Drag index action button */ public static final int ACTIONBUTTON_DRAG = 3; /** * Custom index action button */ public static final int ACTIONBUTTON_CUSTOM = 4; public static final int MAX_BUTTON_WIDTH = 50; public static final int MAX_BUTTON_HEIGHT = 50; public static final int MIN_BUTTON_WIDTH = 35; public static final int MIN_BUTTON_HEIGHT = 35; private double radius = 50; /** * X coordinate of the center of the action buttons */ private int centerX; /** * Y coordinate of the center of the action buttons */ private int centerY; /** * Index of the overed action button */ private ActionButton buttonOver; /** * Index of the pressed action button */ private ActionButton buttonPressed; private List<ActionButton> buttons; /* * Default action buttons, so they don't have to be generated each time */ private ActionButton handButton; private ActionButton mouthButton; private ActionButton eyeButton; private long appearedTime = Long.MAX_VALUE; private static long appearingTime = 600L; /** * Constructor of the class. Requires that the MultimediaManager class is * loaded. * * @param customized * True if the graphics of the HUD are customized, false * otherwise */ public ActionButtons( boolean customized ) { buttons = new ArrayList<ActionButton>( ); //No action button is overed or pressed buttonOver = null; buttonPressed = null; handButton = new ActionButton( ActionButton.HAND_BUTTON ); mouthButton = new ActionButton( ActionButton.MOUTH_BUTTON ); eyeButton = new ActionButton( ActionButton.EYE_BUTTON ); } /** * Recreates the list of action buttons, depending of the type of the * element. * * @param functionalElement */ public void recreate( int posX, int posY, FunctionalElement functionalElement ) { centerX = posX; centerY = posY; buttons.clear( ); if( functionalElement instanceof FunctionalItem ) { FunctionalItem item = (FunctionalItem) functionalElement; addDefaultObjectButtons( item ); addCustomActionButtons( ( (FunctionalItem) functionalElement ).getItem( ).getActions( ), functionalElement ); } if( functionalElement instanceof FunctionalNPC ) { addDefaultCharacterButtons( ( (FunctionalNPC) functionalElement ) ); addCustomActionButtons( ( (FunctionalNPC) functionalElement ).getNPC( ).getActions( ), functionalElement ); } recalculateButtonsPositions( ); clearButtons( ); appearedTime = System.currentTimeMillis( ); } /** * Method that adds the necessary custom action buttons to the list of * buttons. The number of buttons is limited to 8 (including the default * ones) * * @param actions * the actions of the element * @param functionalElement * the functional element with the actions */ private void addCustomActionButtons( List<Action> actions, FunctionalElement functionalElement ) { List<CustomAction> added = new ArrayList<CustomAction>( ); boolean drag_to = false; for( Action action : actions ) { if( buttons.size( ) >= 8 ) return; if( action.getType( ) == Action.DRAG_TO && !drag_to&&!functionalElement.isInInventory( )) { boolean add = functionalElement.getFirstValidAction( Action.DRAG_TO ) != null; if( add ) { buttons.add( new ActionButton(ActionButton.DRAG_BUTTON) ); drag_to = true; } } if( action.getType( ) == Action.CUSTOM ) { boolean add = functionalElement.getFirstValidCustomAction( ( (CustomAction) action ).getName( ) ) != null; for( CustomAction customAction : added ) { if( customAction.getName( ).equals( ( (CustomAction) action ).getName( ) ) ) add = false; } if( add ) { buttons.add( new ActionButton( (CustomAction) action ) ); added.add( (CustomAction) action ); } } else if( action.getType( ) == Action.CUSTOM_INTERACT /*&& functionalElement.isInInventory( )*/ ) { boolean add = functionalElement.getFirstValidCustomInteraction( ( (CustomAction) action ).getName( ) ) != null; for( CustomAction customAction : added ) { if( customAction.getName( ).equals( ( (CustomAction) action ).getName( ) ) ) add = false; } if( add ) { buttons.add( new ActionButton( (CustomAction) action ) ); added.add( (CustomAction) action ); } } } } /** * Clear buttons of any pressed or over information */ private void clearButtons( ) { for( ActionButton ab : buttons ) { ab.setPressed( false ); ab.setOver( false ); } buttonOver = null; buttonPressed = null; } /** * Recalculate the buttons positions, acording to their size and place on * the screen */ private void recalculateButtonsPositions( ) { double degreeIncrement = Math.PI / ( buttons.size( ) - 1 ); double angle = Math.PI; int newCenterY = centerY; int newCenterX = centerX; // TODO check the radius recalculation to get an appropiate distribution radius = 20 * buttons.size( ); if( centerY > GUI.WINDOW_HEIGHT / 2 ) { if( centerY > GUI.WINDOW_HEIGHT - MAX_BUTTON_HEIGHT / 2 ) newCenterY = GUI.WINDOW_HEIGHT - MAX_BUTTON_HEIGHT / 2; degreeIncrement = -degreeIncrement; } else { if( centerY < MAX_BUTTON_HEIGHT / 2 ) newCenterY = MAX_BUTTON_HEIGHT / 2; } if( centerX > GUI.WINDOW_WIDTH - MAX_BUTTON_WIDTH / 2 ) newCenterX = GUI.WINDOW_WIDTH - MAX_BUTTON_WIDTH / 2; if( centerX < MAX_BUTTON_WIDTH ) newCenterX = MAX_BUTTON_WIDTH; if( newCenterX < ( radius + MAX_BUTTON_WIDTH / 2 ) ) { if( newCenterY - radius < MAX_BUTTON_HEIGHT ) { angle = angle / 2; degreeIncrement = degreeIncrement / 2; radius = radius * 1.5; } else if( newCenterY + radius > GUI.WINDOW_HEIGHT - MAX_BUTTON_HEIGHT / 2 ) { angle = angle + angle / 2; degreeIncrement = degreeIncrement / 2; radius = radius * 1.5; } else { if( centerY > GUI.WINDOW_HEIGHT / 2 ) degreeIncrement = -degreeIncrement; angle = angle / 2; } } else if( newCenterX > ( GUI.WINDOW_WIDTH - radius - MAX_BUTTON_WIDTH / 2 ) ) { if( newCenterY - radius < MAX_BUTTON_HEIGHT ) { angle = angle / 2; degreeIncrement = -degreeIncrement / 2; radius = radius * 1.5; } else if( newCenterY + radius > GUI.WINDOW_HEIGHT - MAX_BUTTON_HEIGHT / 2 ) { angle = angle + angle / 2; degreeIncrement = -degreeIncrement / 2; radius = radius * 1.5; } else { if( centerY > GUI.WINDOW_HEIGHT / 2 ) degreeIncrement = -degreeIncrement; angle = -angle / 2; } } for( ActionButton ab : buttons ) { ab.setPosX( (int) ( Math.cos( angle ) * radius + newCenterX ) ); ab.setPosY( (int) ( Math.sin( angle ) * radius + newCenterY ) ); angle -= degreeIncrement; } } /** * Adds the default buttons for a character element * * @param functionalNPC */ private void addDefaultCharacterButtons( FunctionalNPC functionalNPC ) { buttons.add( eyeButton ); buttons.add( mouthButton ); boolean use = functionalNPC.getFirstValidAction( Action.USE ) != null; if( use ) { handButton.setName( TC.get( "ActionButton.Use" ) ); buttons.add( handButton ); } } /** * Adds the default buttons for non-character elements */ private void addDefaultObjectButtons( FunctionalItem item ) { buttons.add( eyeButton ); boolean addHandButton = false; if( !item.isInInventory( ) ) { handButton.setName( TC.get( "ActionButton.Grab" ) ); Action grabAction = item.getFirstValidAction( Action.GRAB ); Action useAction = item.getFirstValidAction( Action.USE ); if ( grabAction != null) addHandButton = true; if( useAction != null ) { //if the conditions of useAction are not met and the conditions of grab action are met, the handButton //name must be "grabAction" - if (grabAction != null && (useAction.isConditionsAreMeet( ) || !grabAction.isConditionsAreMeet( ) ) ) + if ( (useAction.isConditionsAreMeet( ) || (grabAction != null && !grabAction.isConditionsAreMeet( )) ) ) handButton.setName( TC.get( "ActionButton.Use" ) ); addHandButton = true; } } else { /* * Change the next lines of code to distinguish between give to/ use with * * * // check if can be use alone and the action "use" don't meet the conditions // this way, check if useWith, giveTo or both meet the conditions to show this actions in the hud Action giveToAction = item.getFirstValidAction( Action.GIVE_TO ); Action useWithAction = item.getFirstValidAction( Action.USE_WITH ); Action useAction = item.getFirstValidAction( Action.USE ); boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = giveToAction != null; boolean useWith = useWithAction != null; addHandButton = useAlone || giveTo || useWith; boolean useActionNotMeetConditions = useAction!=null && !useAction.isConditionsAreMeet( ); boolean giveToConditionsAreMet = giveToAction.isConditionsAreMeet( ); boolean useWithConditionsAreMet = useWithAction.isConditionsAreMeet( ); if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( (!useAlone || (useActionNotMeetConditions && giveToConditionsAreMet)) && giveTo && (!useWith || !useWithConditionsAreMet )) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( (!useAlone || (useActionNotMeetConditions && useWithConditionsAreMet )) && (!giveTo && !giveToConditionsAreMet) && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( (!useAlone || (useActionNotMeetConditions && (useWithConditionsAreMet && giveToConditionsAreMet) )) && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } */ boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = item.getFirstValidAction( Action.GIVE_TO ) != null; boolean useWith = item.getFirstValidAction( Action.USE_WITH ) != null; addHandButton = useAlone || giveTo || useWith; if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( !useAlone && giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( !useAlone && !giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( !useAlone && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } } if (addHandButton) buttons.add( handButton ); } /** * There has been a mouse moved over the action buttons * * @param x * int coordinate * @param y * int coordinate */ public void mouseMoved( MouseEvent e ) { clearButtons( ); if( e != null ) { ActionButton ab = getButton( e.getX( ), e.getY( ) ); if( ab != null ) { ab.setOver( true ); buttonOver = ab; } } } /** * There has been a click in the action buttons * * @param x * int coordinate * @param y * int coordinate */ public void mouseClicked( MouseEvent e ) { clearButtons( ); if( e != null ) { ActionButton ab = getButton( e.getX( ), e.getY( ) ); if( ab != null ) { ab.setPressed( true ); buttonPressed = ab; } } } /** * Draw the action buttons given a Graphics2D * * @param g * Graphics2D to be used */ public void draw( Graphics2D g ) { //For each action button float percent = (float) ( System.currentTimeMillis( ) - appearedTime ) / (float) appearingTime; //System.out.println("" + System.currentTimeMillis() + " " + appearedTime + " " + percent); if( percent > 1 ) percent = 1; Composite original = g.getComposite( ); g.setColor( Color.RED ); Composite alphaComposite = AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.4f ); g.setComposite( alphaComposite ); g.fillOval( centerX - 8, centerY - 8, 16, 16 ); for( ActionButton ab : buttons ) { g.setComposite( alphaComposite ); g.setColor( Color.RED ); int posX = (int) ( ( ab.getPosX( ) - centerX ) * percent + centerX ); int posY = (int) ( ( ab.getPosY( ) - centerY ) * percent + centerY ); if( ab.isOver( ) ) { Stroke temp = g.getStroke( ); g.setStroke( new BasicStroke( 3.0f ) ); g.drawLine( centerX, centerY, ab.getPosX( ), ab.getPosY( ) ); g.setStroke( temp ); } else { g.drawLine( centerX, centerY, posX, posY ); } g.setComposite( original ); ab.draw( g, percent, posX, posY ); } if( buttonOver != null ) { buttonOver.drawName( g ); } } /** * Get the current button pressed * * @return button pressed */ public ActionButton getButtonPressed( ) { return buttonPressed; } /** * Get the current button pressed * * @return button pressed */ public ActionButton getButtonOver( ) { return buttonOver; } /** * Returns the button at the given coordinates * * @param x * the x-axis value * @param y * the y-axis value * @return the button in that place */ public ActionButton getButton( int x, int y ) { for( ActionButton ab : buttons ) { if( ab.isInside( x, y ) ) { return ab; } } return null; } }
true
true
private void addDefaultObjectButtons( FunctionalItem item ) { buttons.add( eyeButton ); boolean addHandButton = false; if( !item.isInInventory( ) ) { handButton.setName( TC.get( "ActionButton.Grab" ) ); Action grabAction = item.getFirstValidAction( Action.GRAB ); Action useAction = item.getFirstValidAction( Action.USE ); if ( grabAction != null) addHandButton = true; if( useAction != null ) { //if the conditions of useAction are not met and the conditions of grab action are met, the handButton //name must be "grabAction" if (grabAction != null && (useAction.isConditionsAreMeet( ) || !grabAction.isConditionsAreMeet( ) ) ) handButton.setName( TC.get( "ActionButton.Use" ) ); addHandButton = true; } } else { /* * Change the next lines of code to distinguish between give to/ use with * * * // check if can be use alone and the action "use" don't meet the conditions // this way, check if useWith, giveTo or both meet the conditions to show this actions in the hud Action giveToAction = item.getFirstValidAction( Action.GIVE_TO ); Action useWithAction = item.getFirstValidAction( Action.USE_WITH ); Action useAction = item.getFirstValidAction( Action.USE ); boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = giveToAction != null; boolean useWith = useWithAction != null; addHandButton = useAlone || giveTo || useWith; boolean useActionNotMeetConditions = useAction!=null && !useAction.isConditionsAreMeet( ); boolean giveToConditionsAreMet = giveToAction.isConditionsAreMeet( ); boolean useWithConditionsAreMet = useWithAction.isConditionsAreMeet( ); if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( (!useAlone || (useActionNotMeetConditions && giveToConditionsAreMet)) && giveTo && (!useWith || !useWithConditionsAreMet )) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( (!useAlone || (useActionNotMeetConditions && useWithConditionsAreMet )) && (!giveTo && !giveToConditionsAreMet) && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( (!useAlone || (useActionNotMeetConditions && (useWithConditionsAreMet && giveToConditionsAreMet) )) && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } */ boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = item.getFirstValidAction( Action.GIVE_TO ) != null; boolean useWith = item.getFirstValidAction( Action.USE_WITH ) != null; addHandButton = useAlone || giveTo || useWith; if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( !useAlone && giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( !useAlone && !giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( !useAlone && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } } if (addHandButton) buttons.add( handButton ); }
private void addDefaultObjectButtons( FunctionalItem item ) { buttons.add( eyeButton ); boolean addHandButton = false; if( !item.isInInventory( ) ) { handButton.setName( TC.get( "ActionButton.Grab" ) ); Action grabAction = item.getFirstValidAction( Action.GRAB ); Action useAction = item.getFirstValidAction( Action.USE ); if ( grabAction != null) addHandButton = true; if( useAction != null ) { //if the conditions of useAction are not met and the conditions of grab action are met, the handButton //name must be "grabAction" if ( (useAction.isConditionsAreMeet( ) || (grabAction != null && !grabAction.isConditionsAreMeet( )) ) ) handButton.setName( TC.get( "ActionButton.Use" ) ); addHandButton = true; } } else { /* * Change the next lines of code to distinguish between give to/ use with * * * // check if can be use alone and the action "use" don't meet the conditions // this way, check if useWith, giveTo or both meet the conditions to show this actions in the hud Action giveToAction = item.getFirstValidAction( Action.GIVE_TO ); Action useWithAction = item.getFirstValidAction( Action.USE_WITH ); Action useAction = item.getFirstValidAction( Action.USE ); boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = giveToAction != null; boolean useWith = useWithAction != null; addHandButton = useAlone || giveTo || useWith; boolean useActionNotMeetConditions = useAction!=null && !useAction.isConditionsAreMeet( ); boolean giveToConditionsAreMet = giveToAction.isConditionsAreMeet( ); boolean useWithConditionsAreMet = useWithAction.isConditionsAreMeet( ); if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( (!useAlone || (useActionNotMeetConditions && giveToConditionsAreMet)) && giveTo && (!useWith || !useWithConditionsAreMet )) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( (!useAlone || (useActionNotMeetConditions && useWithConditionsAreMet )) && (!giveTo && !giveToConditionsAreMet) && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( (!useAlone || (useActionNotMeetConditions && (useWithConditionsAreMet && giveToConditionsAreMet) )) && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } */ boolean useAlone = item.canBeUsedAlone( ); boolean giveTo = item.getFirstValidAction( Action.GIVE_TO ) != null; boolean useWith = item.getFirstValidAction( Action.USE_WITH ) != null; addHandButton = useAlone || giveTo || useWith; if( useAlone && !giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.Use" ) ); } else if( !useAlone && giveTo && !useWith ) { handButton.setName( TC.get( "ActionButton.GiveTo" ) ); } else if( !useAlone && !giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseWith" ) ); } else if( !useAlone && giveTo && useWith ) { handButton.setName( TC.get( "ActionButton.UseGive" ) ); } else { handButton.setName( TC.get( "ActionButton.Use" ) ); } } if (addHandButton) buttons.add( handButton ); }
diff --git a/Core/src/org/sleuthkit/autopsy/examples/SampleDataSourceIngestModule.java b/Core/src/org/sleuthkit/autopsy/examples/SampleDataSourceIngestModule.java index 60d0e98ca..e6061fdd7 100755 --- a/Core/src/org/sleuthkit/autopsy/examples/SampleDataSourceIngestModule.java +++ b/Core/src/org/sleuthkit/autopsy/examples/SampleDataSourceIngestModule.java @@ -1,125 +1,125 @@ /* * Sample module in the public domain. Feel free to use this as a template * for your modules. * * Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.sleuthkit.autopsy.examples; import java.util.List; import org.apache.log4j.Logger; import org.openide.util.Exceptions; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.services.FileManager; import org.sleuthkit.autopsy.casemodule.services.Services; import org.sleuthkit.autopsy.ingest.IngestDataSourceWorkerController; import org.sleuthkit.autopsy.ingest.IngestModuleDataSource; import org.sleuthkit.autopsy.ingest.IngestModuleInit; import org.sleuthkit.autopsy.ingest.PipelineContext; import org.sleuthkit.datamodel.AbstractFile; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.FsContent; import org.sleuthkit.datamodel.SleuthkitCase; import org.sleuthkit.datamodel.TskCoreException; /** * Sample DataSource-level ingest module that doesn't do much at all. * Just exists to show basic idea of these modules */ public class SampleDataSourceIngestModule extends org.sleuthkit.autopsy.ingest.IngestModuleDataSource { /* Data Source modules operate on a disk or set of logical files. They * are passed in teh data source refernce and query it for things they want. */ @Override public void process(PipelineContext<IngestModuleDataSource> pipelineContext, Content dataSource, IngestDataSourceWorkerController controller) { Case case1 = Case.getCurrentCase(); SleuthkitCase sleuthkitCase = case1.getSleuthkitCase(); Services services = new Services(sleuthkitCase); FileManager fm = services.getFileManager(); try { /* you can use the findFiles method in FileManager (or similar ones in * SleuthkitCase to find files based only on their name. This * one finds files that have a .doc extension. */ List<AbstractFile> docFiles = fm.findFiles(dataSource, "%.doc"); for (AbstractFile file : docFiles) { // do something with each doc file } /* We can also do more general queries with findFilesWhere, which * allows us to make our own WHERE clause in the database. */ long currentTime = System.currentTimeMillis()/1000; // go back 2 weeks long minTime = currentTime - (14 * 24 * 60 * 60); List<FsContent> otherFiles = sleuthkitCase.findFilesWhere("crtime > " + minTime); // do something with these files... } catch (TskCoreException ex) { Logger log = Logger.getLogger(SampleDataSourceIngestModule.class); - log.fatal("Error retrieving files from database: " + ex1.getLocalizedMessage()); + log.fatal("Error retrieving files from database: " + ex.getLocalizedMessage()); return; } } @Override public void init(IngestModuleInit initContext) { // do nothing } @Override public void complete() { // do nothing } @Override public void stop() { // do nothing } @Override public String getName() { return "SampleDataSourceIngestModule"; } @Override public String getVersion() { return "1.0"; } @Override public String getDescription() { return "Doesn't do much"; } @Override public boolean hasBackgroundJobsRunning() { return false; } }
true
true
public void process(PipelineContext<IngestModuleDataSource> pipelineContext, Content dataSource, IngestDataSourceWorkerController controller) { Case case1 = Case.getCurrentCase(); SleuthkitCase sleuthkitCase = case1.getSleuthkitCase(); Services services = new Services(sleuthkitCase); FileManager fm = services.getFileManager(); try { /* you can use the findFiles method in FileManager (or similar ones in * SleuthkitCase to find files based only on their name. This * one finds files that have a .doc extension. */ List<AbstractFile> docFiles = fm.findFiles(dataSource, "%.doc"); for (AbstractFile file : docFiles) { // do something with each doc file } /* We can also do more general queries with findFilesWhere, which * allows us to make our own WHERE clause in the database. */ long currentTime = System.currentTimeMillis()/1000; // go back 2 weeks long minTime = currentTime - (14 * 24 * 60 * 60); List<FsContent> otherFiles = sleuthkitCase.findFilesWhere("crtime > " + minTime); // do something with these files... } catch (TskCoreException ex) { Logger log = Logger.getLogger(SampleDataSourceIngestModule.class); log.fatal("Error retrieving files from database: " + ex1.getLocalizedMessage()); return; } }
public void process(PipelineContext<IngestModuleDataSource> pipelineContext, Content dataSource, IngestDataSourceWorkerController controller) { Case case1 = Case.getCurrentCase(); SleuthkitCase sleuthkitCase = case1.getSleuthkitCase(); Services services = new Services(sleuthkitCase); FileManager fm = services.getFileManager(); try { /* you can use the findFiles method in FileManager (or similar ones in * SleuthkitCase to find files based only on their name. This * one finds files that have a .doc extension. */ List<AbstractFile> docFiles = fm.findFiles(dataSource, "%.doc"); for (AbstractFile file : docFiles) { // do something with each doc file } /* We can also do more general queries with findFilesWhere, which * allows us to make our own WHERE clause in the database. */ long currentTime = System.currentTimeMillis()/1000; // go back 2 weeks long minTime = currentTime - (14 * 24 * 60 * 60); List<FsContent> otherFiles = sleuthkitCase.findFilesWhere("crtime > " + minTime); // do something with these files... } catch (TskCoreException ex) { Logger log = Logger.getLogger(SampleDataSourceIngestModule.class); log.fatal("Error retrieving files from database: " + ex.getLocalizedMessage()); return; } }
diff --git a/repose-aggregator/core/core-lib/src/main/java/com/rackspace/papi/service/proxy/httpcomponent/HttpComponentRequestProcessor.java b/repose-aggregator/core/core-lib/src/main/java/com/rackspace/papi/service/proxy/httpcomponent/HttpComponentRequestProcessor.java index d4ee4cb8ae..6e1d96aa7d 100644 --- a/repose-aggregator/core/core-lib/src/main/java/com/rackspace/papi/service/proxy/httpcomponent/HttpComponentRequestProcessor.java +++ b/repose-aggregator/core/core-lib/src/main/java/com/rackspace/papi/service/proxy/httpcomponent/HttpComponentRequestProcessor.java @@ -1,150 +1,153 @@ package com.rackspace.papi.service.proxy.httpcomponent; import com.rackspace.papi.commons.util.StringUtilities; import com.rackspace.papi.commons.util.http.CommonHttpHeader; import com.rackspace.papi.commons.util.servlet.http.MutableHttpServletRequest; import com.rackspace.papi.http.proxy.common.AbstractRequestProcessor; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.InputStreamEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.Enumeration; /** * Process a request to copy over header values, query string parameters, and * request body as necessary. */ class HttpComponentRequestProcessor extends AbstractRequestProcessor { private static final Logger LOG = LoggerFactory.getLogger(HttpComponentRequestProcessor.class); private static final String ENCODING = "UTF-8"; private final HttpServletRequest sourceRequest; private final URI targetHost; private final boolean rewriteHostHeader; private boolean isConfiguredChunked; public HttpComponentRequestProcessor(HttpServletRequest request, URI host, boolean rewriteHostHeader, boolean isConfiguredChunked) { this.sourceRequest = request; this.targetHost = host; this.rewriteHostHeader = rewriteHostHeader; this.isConfiguredChunked = isConfiguredChunked; } private void setRequestParameters(URIBuilder builder) throws URISyntaxException { Enumeration<String> names = sourceRequest.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (StringUtilities.isBlank(name)) { continue; } String[] values = sourceRequest.getParameterValues(name); for (String value : values) { try { builder.addParameter(name, URLDecoder.decode(value, ENCODING)); + } catch (IllegalArgumentException iae) { + LOG.warn("URL parameter could not be decoded, passing it as-is.", iae); + builder.addParameter(name, value); } catch (UnsupportedEncodingException ex) { LOG.warn("URL parameter could not be decoded, passing it as-is.", ex); builder.addParameter(name, value); } } } } public URI getUri(String target) throws URISyntaxException { URIBuilder builder = new URIBuilder(target); setRequestParameters(builder); return builder.build(); } /** * Scan header values and manipulate as necessary. Host header, if provided, may need to be updated. * * @param headerName * @param headerValue * @return */ private String processHeaderValue(String headerName, String headerValue) { String result = headerValue; // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (rewriteHostHeader && headerName.equalsIgnoreCase(CommonHttpHeader.HOST.toString())) { result = targetHost.getHost() + ":" + targetHost.getPort(); } return result; } /** * Copy header values from source request to the http method. * * @param method */ private void setHeaders(HttpRequestBase method) { final Enumeration<String> headerNames = sourceRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (excludeHeader(headerName)) { continue; } final Enumeration<String> headerValues = sourceRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { String headerValue = headerValues.nextElement(); method.addHeader(headerName, processHeaderValue(headerName, headerValue)); } } } /** * Process a base http request. Base http methods will not contain a message body. * * @param method * @return */ public HttpRequestBase process(HttpRequestBase method) { setHeaders(method); return method; } /** * Process an entity enclosing http method. These methods can handle a request body. * * @param method * @return * @throws IOException */ public HttpRequestBase process(HttpEntityEnclosingRequestBase method) throws IOException { final int contentLength = getEntityLength(); setHeaders(method); method.setEntity(new InputStreamEntity(sourceRequest.getInputStream(), contentLength)); return method; } private int getEntityLength() throws IOException { if (StringUtilities.nullSafeEqualsIgnoreCase(sourceRequest.getHeader("transfer-encoding"), "chunked") || isConfiguredChunked) { return -1; } else { return ((MutableHttpServletRequest) sourceRequest).getRealBodyLength(); } } }
true
true
private void setRequestParameters(URIBuilder builder) throws URISyntaxException { Enumeration<String> names = sourceRequest.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (StringUtilities.isBlank(name)) { continue; } String[] values = sourceRequest.getParameterValues(name); for (String value : values) { try { builder.addParameter(name, URLDecoder.decode(value, ENCODING)); } catch (UnsupportedEncodingException ex) { LOG.warn("URL parameter could not be decoded, passing it as-is.", ex); builder.addParameter(name, value); } } } }
private void setRequestParameters(URIBuilder builder) throws URISyntaxException { Enumeration<String> names = sourceRequest.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (StringUtilities.isBlank(name)) { continue; } String[] values = sourceRequest.getParameterValues(name); for (String value : values) { try { builder.addParameter(name, URLDecoder.decode(value, ENCODING)); } catch (IllegalArgumentException iae) { LOG.warn("URL parameter could not be decoded, passing it as-is.", iae); builder.addParameter(name, value); } catch (UnsupportedEncodingException ex) { LOG.warn("URL parameter could not be decoded, passing it as-is.", ex); builder.addParameter(name, value); } } } }
diff --git a/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java b/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java index 7362bf686..455587d2c 100644 --- a/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java +++ b/annis-service/src/main/java/annis/sqlgen/ListDocumentsAnnotationsSqlHelper.java @@ -1,52 +1,52 @@ /* * Copyright 2009-2011 Collaborative Research Centre SFB 632 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.sqlgen; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import annis.model.Annotation; import static annis.sqlgen.SqlConstraints.sqlString; public class ListDocumentsAnnotationsSqlHelper implements ParameterizedRowMapper<Annotation> { public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + - "ON docs.pre=meta.corpus_ref \n" + + "ON docs.id=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; } @Override public Annotation mapRow(ResultSet rs, int rowNum) throws SQLException { String namespace = rs.getString("namespace"); String name = rs.getString("name"); String value = rs.getString("value"); return new Annotation(namespace, name, value); } }
true
true
public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + "ON docs.pre=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; }
public String createSqlQuery(String toplevelCorpusName) { String template = "SELECT DISTINCT meta.namespace, meta.name, meta.value \n" + "from corpus this, corpus docs \n" + "FULL JOIN corpus_annotation meta \n" + "ON docs.id=meta.corpus_ref \n" + "WHERE this.name = :toplevelname \n" + "AND docs.pre > this.pre \n" + "AND docs.post < this.post \n" + "AND meta.namespace is not null"; String sql = template.replaceAll(":toplevelname", sqlString(toplevelCorpusName)); return sql; }
diff --git a/src/nl/sense_os/commonsense/main/client/states/defaults/StateDefaultsController.java b/src/nl/sense_os/commonsense/main/client/states/defaults/StateDefaultsController.java index e063696a..ea265dd7 100755 --- a/src/nl/sense_os/commonsense/main/client/states/defaults/StateDefaultsController.java +++ b/src/nl/sense_os/commonsense/main/client/states/defaults/StateDefaultsController.java @@ -1,119 +1,119 @@ package nl.sense_os.commonsense.main.client.states.defaults; import java.util.List; import java.util.logging.Logger; import nl.sense_os.commonsense.common.client.communication.SessionManager; import nl.sense_os.commonsense.common.client.constant.Urls; import nl.sense_os.commonsense.main.client.ext.model.ExtDevice; import nl.sense_os.commonsense.main.client.ext.model.ExtSensor; import com.extjs.gxt.ui.client.Registry; import com.extjs.gxt.ui.client.event.EventType; import com.extjs.gxt.ui.client.mvc.AppEvent; import com.extjs.gxt.ui.client.mvc.Controller; import com.extjs.gxt.ui.client.mvc.Dispatcher; import com.extjs.gxt.ui.client.mvc.View; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestBuilder.Method; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.UrlBuilder; public class StateDefaultsController extends Controller { private static final Logger LOG = Logger.getLogger(StateDefaultsController.class.getName()); public StateDefaultsController() { registerEventTypes(StateDefaultsEvents.CheckDefaults, StateDefaultsEvents.CheckDefaultsRequest, StateDefaultsEvents.CheckDefaultsSuccess); } private void checkDefaults(List<ExtDevice> devices, boolean overwrite, final View source) { // prepare request properties final Method method = RequestBuilder.POST; final UrlBuilder urlBuilder = new UrlBuilder().setHost(Urls.HOST); - urlBuilder.setPath(Urls.PATH_STATES + "/default/check.json"); + urlBuilder.setPath(Urls.PATH_STATES + "/default.json"); final String url = urlBuilder.buildString(); final String sessionId = SessionManager.getSessionId(); // prepare body String body = "{\"sensors\":["; List<ExtSensor> sensors = Registry .get(nl.sense_os.commonsense.common.client.util.Constants.REG_SENSOR_LIST); for (ExtSensor sensor : sensors) { ExtDevice sensorDevice = sensor.getDevice(); if (sensorDevice != null && devices.contains(sensorDevice)) { body += "\"" + sensor.getId() + "\","; } } if (body.length() > 1) { body = body.substring(0, body.length() - 1); } body += "],"; body += "\"update\":\"" + (overwrite ? 1 : 0) + "\""; body += "}"; // prepare request callback RequestCallback reqCallback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { LOG.warning("POST default services onError callback: " + exception.getMessage()); onCheckDefaultsFailure(source); } @Override public void onResponseReceived(Request request, Response response) { LOG.finest("POST default services response received: " + response.getStatusText()); int statusCode = response.getStatusCode(); if (Response.SC_OK == statusCode) { onCheckDefaultsSuccess(response.getText(), source); } else { LOG.warning("POST default services returned incorrect status: " + statusCode); onCheckDefaultsFailure(source); } } }; // send request try { RequestBuilder builder = new RequestBuilder(method, url); builder.setHeader("X-SESSION_ID", sessionId); builder.setHeader("Content-Type", Urls.HEADER_JSON_TYPE); builder.sendRequest(body, reqCallback); } catch (Exception e) { LOG.warning("POST default services request threw exception: " + e.getMessage()); reqCallback.onError(null, e); } } @Override public void handleEvent(AppEvent event) { final EventType type = event.getType(); if (type.equals(StateDefaultsEvents.CheckDefaultsRequest)) { LOG.fine("CheckDefaultsRequest"); List<ExtDevice> devices = event.getData("devices"); boolean overwrite = event.getData("overwrite"); View source = (View) event.getSource(); checkDefaults(devices, overwrite, source); } else if (type.equals(StateDefaultsEvents.CheckDefaults)) { StateDefaultsView view = new StateDefaultsView(this); forwardToView(view, event); } } private void onCheckDefaultsFailure(View source) { forwardToView(source, new AppEvent(StateDefaultsEvents.CheckDefaultsFailure)); } private void onCheckDefaultsSuccess(String response, View source) { AppEvent event = new AppEvent(StateDefaultsEvents.CheckDefaultsSuccess); Dispatcher.forwardEvent(event); forwardToView(source, event); } }
true
true
private void checkDefaults(List<ExtDevice> devices, boolean overwrite, final View source) { // prepare request properties final Method method = RequestBuilder.POST; final UrlBuilder urlBuilder = new UrlBuilder().setHost(Urls.HOST); urlBuilder.setPath(Urls.PATH_STATES + "/default/check.json"); final String url = urlBuilder.buildString(); final String sessionId = SessionManager.getSessionId(); // prepare body String body = "{\"sensors\":["; List<ExtSensor> sensors = Registry .get(nl.sense_os.commonsense.common.client.util.Constants.REG_SENSOR_LIST); for (ExtSensor sensor : sensors) { ExtDevice sensorDevice = sensor.getDevice(); if (sensorDevice != null && devices.contains(sensorDevice)) { body += "\"" + sensor.getId() + "\","; } } if (body.length() > 1) { body = body.substring(0, body.length() - 1); } body += "],"; body += "\"update\":\"" + (overwrite ? 1 : 0) + "\""; body += "}"; // prepare request callback RequestCallback reqCallback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { LOG.warning("POST default services onError callback: " + exception.getMessage()); onCheckDefaultsFailure(source); } @Override public void onResponseReceived(Request request, Response response) { LOG.finest("POST default services response received: " + response.getStatusText()); int statusCode = response.getStatusCode(); if (Response.SC_OK == statusCode) { onCheckDefaultsSuccess(response.getText(), source); } else { LOG.warning("POST default services returned incorrect status: " + statusCode); onCheckDefaultsFailure(source); } } }; // send request try { RequestBuilder builder = new RequestBuilder(method, url); builder.setHeader("X-SESSION_ID", sessionId); builder.setHeader("Content-Type", Urls.HEADER_JSON_TYPE); builder.sendRequest(body, reqCallback); } catch (Exception e) { LOG.warning("POST default services request threw exception: " + e.getMessage()); reqCallback.onError(null, e); } }
private void checkDefaults(List<ExtDevice> devices, boolean overwrite, final View source) { // prepare request properties final Method method = RequestBuilder.POST; final UrlBuilder urlBuilder = new UrlBuilder().setHost(Urls.HOST); urlBuilder.setPath(Urls.PATH_STATES + "/default.json"); final String url = urlBuilder.buildString(); final String sessionId = SessionManager.getSessionId(); // prepare body String body = "{\"sensors\":["; List<ExtSensor> sensors = Registry .get(nl.sense_os.commonsense.common.client.util.Constants.REG_SENSOR_LIST); for (ExtSensor sensor : sensors) { ExtDevice sensorDevice = sensor.getDevice(); if (sensorDevice != null && devices.contains(sensorDevice)) { body += "\"" + sensor.getId() + "\","; } } if (body.length() > 1) { body = body.substring(0, body.length() - 1); } body += "],"; body += "\"update\":\"" + (overwrite ? 1 : 0) + "\""; body += "}"; // prepare request callback RequestCallback reqCallback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { LOG.warning("POST default services onError callback: " + exception.getMessage()); onCheckDefaultsFailure(source); } @Override public void onResponseReceived(Request request, Response response) { LOG.finest("POST default services response received: " + response.getStatusText()); int statusCode = response.getStatusCode(); if (Response.SC_OK == statusCode) { onCheckDefaultsSuccess(response.getText(), source); } else { LOG.warning("POST default services returned incorrect status: " + statusCode); onCheckDefaultsFailure(source); } } }; // send request try { RequestBuilder builder = new RequestBuilder(method, url); builder.setHeader("X-SESSION_ID", sessionId); builder.setHeader("Content-Type", Urls.HEADER_JSON_TYPE); builder.sendRequest(body, reqCallback); } catch (Exception e) { LOG.warning("POST default services request threw exception: " + e.getMessage()); reqCallback.onError(null, e); } }
diff --git a/src/test/java/ru/skalodrom_rf/ProfileTest.java b/src/test/java/ru/skalodrom_rf/ProfileTest.java index af5a187..27706a5 100644 --- a/src/test/java/ru/skalodrom_rf/ProfileTest.java +++ b/src/test/java/ru/skalodrom_rf/ProfileTest.java @@ -1,39 +1,39 @@ package ru.skalodrom_rf; import org.joda.time.LocalDate; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import ru.skalodrom_rf.dao.ProfileDao; import ru.skalodrom_rf.dao.SkalodromDao; import ru.skalodrom_rf.model.Profile; import ru.skalodrom_rf.model.Skalodrom; import ru.skalodrom_rf.model.Time; import javax.annotation.Resource; import java.util.List; /**.*/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class ProfileTest { @Resource ProfileDao profileDao; @Resource SkalodromDao skalodromDao; @Test @Transactional public void testConstraint(){ - final Skalodrom skalodrom = skalodromDao.findAll().get(0); + final Skalodrom skalodrom = skalodromDao.findAll().get(1); final List<Profile> profileList = profileDao.findByScalodromAndDate(skalodrom, new LocalDate(), Time.DAY); Assert.assertEquals(1,profileList.size()); } }
true
true
public void testConstraint(){ final Skalodrom skalodrom = skalodromDao.findAll().get(0); final List<Profile> profileList = profileDao.findByScalodromAndDate(skalodrom, new LocalDate(), Time.DAY); Assert.assertEquals(1,profileList.size()); }
public void testConstraint(){ final Skalodrom skalodrom = skalodromDao.findAll().get(1); final List<Profile> profileList = profileDao.findByScalodromAndDate(skalodrom, new LocalDate(), Time.DAY); Assert.assertEquals(1,profileList.size()); }
diff --git a/src/com/macbury/unamed/level/WorldBuilder.java b/src/com/macbury/unamed/level/WorldBuilder.java index c130ca7..7995f13 100644 --- a/src/com/macbury/unamed/level/WorldBuilder.java +++ b/src/com/macbury/unamed/level/WorldBuilder.java @@ -1,33 +1,33 @@ package com.macbury.unamed.level; import java.util.Random; import org.newdawn.slick.Color; import com.macbury.unamed.PerlinGen; public class WorldBuilder { public float world[][]; public int size; private Random rand_; public WorldBuilder(int size) { this.rand_ = new Random(); this.size = size; PerlinGen pg = new PerlinGen(0, 0); this.world = pg.generate(size, 8, 30); smoothResources(); } private void smoothResources() { float resourceCount = 1.0f / 5.0f; for (int x = 0; x < this.size; x++) { for (int y = 0; y < this.size; y++) { float val = this.world[x][y]; - this.world[x][y] = val / resourceCount; + this.world[x][y] = Math.round(Math.round(100.0f * val) / resourceCount) ; } } } }
true
true
private void smoothResources() { float resourceCount = 1.0f / 5.0f; for (int x = 0; x < this.size; x++) { for (int y = 0; y < this.size; y++) { float val = this.world[x][y]; this.world[x][y] = val / resourceCount; } } }
private void smoothResources() { float resourceCount = 1.0f / 5.0f; for (int x = 0; x < this.size; x++) { for (int y = 0; y < this.size; y++) { float val = this.world[x][y]; this.world[x][y] = Math.round(Math.round(100.0f * val) / resourceCount) ; } } }
diff --git a/src/main/java/de/downgra/jitertools/JIterTools.java b/src/main/java/de/downgra/jitertools/JIterTools.java index ebb5f2e..0385a06 100644 --- a/src/main/java/de/downgra/jitertools/JIterTools.java +++ b/src/main/java/de/downgra/jitertools/JIterTools.java @@ -1,905 +1,903 @@ package de.downgra.jitertools; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class JIterTools { private JIterTools() { /* don't mess with me */ } /** * Return a iterable which generate an arithmetic progression of integers * from 0 to stop - 1 in steps of 1. * * range(5) -> 0, 1, 2, 3, 4 * * @param stop stop value * @return iterable of integers */ public static Iterable<Integer> range(final int stop) { return range(0, stop, 1); } /** * Return a iterable which generate an arithmetic progression of integers * from start to stop -1 in steps of 1. * * range(7, 10) -> 7, 8, 9 * * @param start start value * @param stop stop value * @return iterable of integers */ public static Iterable<Integer> range(final int start, final int stop) { return range(start, stop, 1); } /** * Return a iterable which generate an arithmetic progression of integers * from start to stop - 1 in steps of step. * * step can be negative so a reversed list is returned. * * range(4, 9, 2) -> 4, 6, 8 range(9, 0, -2) -> 9, 7, 5, 3, 1 * * @param start start value * @param stop stop value * @param step increment or decrement * @return list of integers */ public static Iterable<Integer> range(final int start, final int stop, final int step) { assert step != 0; return new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int _current = start; @Override public boolean hasNext() { if (step < 0) { return _current > stop; } else { return _current < stop; } } @Override public Integer next() { int tmp = _current; _current += step; return tmp; } @Override public void remove() { } }; } }; } /** * Return the iterable where the function is applied to each element. * * @param <E> type of the returned iterable * @param <T> type of the given iterable * @param function the function * @param iterable an iterable of type T * @return iterable of type E */ public static <E, T> Iterable<E> map(final IFunctor<E, T> function, final Iterable<T> iterable) { return new Iterable<E>() { @Override public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<T> _iterator = iterable.iterator(); @Override public boolean hasNext() { return _iterator.hasNext(); } @Override public E next() { return function.call(_iterator.next()); } @Override public void remove() { } }; } }; } /** * Convert a iterable to a List. * * @param <T> the type * @param iterable of type T * @return List of type T */ public static <T> List<T> list(final Iterable<T> iterable) { // any better way? ArrayList<T> r = new ArrayList<T>(); for (T item : iterable) { r.add(item); } return r; } /** * Apply a function of two arguments cumulatively to the items of a sequence * from left to right. * * @param <T> type * @param function a functor of return type T and parameter type Pair&lt;T, * T&gt; * @param iterable an iterable of type T * @return the reduced value */ public static <T> T reduce(final IFunctor<T, Pair<T, T>> function, final Iterable<T> iterable) { Iterator<T> it = iterable.iterator(); T res = it.next(); while (it.hasNext()) { res = function.call(Pair.create(res, it.next())); } return res; } /** * Apply a function of two arguments cumulatively to the items of a sequence * from left to right. * * @param <T> type * @param function a functor of return type T and parameter type Pair&lt;T, * T&gt; * @param iterable an iterable of type T * @param initial is placed before the items in iterable * @return the reduced value */ public static <T> T reduce(final IFunctor<T, Pair<T, T>> function, final Iterable<T> iterable, final T initial) { T res = initial; for (T item : iterable) { res = function.call(Pair.create(res, item)); } return res; } /** * Return an iterable which returns elements from the first iterable until * it is exhausted, then elements from the next iterable, until all of the * iterables are exhausted. * * @param <T> type * @param iterables 1 to n Iterable&lt;T&gt; objects * @return one iterable of type T */ public static <T> Iterable<T> chain(final Iterable<T>... iterables) { return chain(Arrays.asList(iterables)); } /** * Return an iterable which returns elements from the first iterable until * it is exhausted, then elements from the next iterable, until all of the * iterables are exhausted. * * @param <T> type * @param iterables iterable of Iterable&lt;T&gt; objects * @return one iterable of type T */ public static <T> Iterable<T> chain(final Iterable<Iterable<T>> iterables) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private Iterator<Iterable<T>> _outer = iterables.iterator(); private Iterator<T> _current = _outer.hasNext() ? _outer.next().iterator() : new ArrayList<T>().iterator(); private void consume() { while (!_current.hasNext() && _outer.hasNext()) { _current = _outer.next().iterator(); } } @Override public boolean hasNext() { consume(); return _current.hasNext(); } @Override public T next() { consume(); return _current.next(); } @Override public void remove() { } }; } }; } /** * Return an iterable of consecutive integers starting from zero. * * @return iterable of consecutive integers */ public static Iterable<Integer> count() { return count(0); } /** * Return an iterable of consecutive integers starting from startval. * * @param startval first value to begin counting * @return iterable of consecutive integers */ public static Iterable<Integer> count(final int startval) { return new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { private int _i = startval; @Override public boolean hasNext() { return true; } @Override public Integer next() { return _i++; } @Override public void remove() { } }; } }; } /** * Return elements from the iterable until it is exhausted. Then repeat the * sequence indefinitely. * * Note, this function may require significant auxiliary storage (depending * on the length of the iterable). * * @param <T> type * @param iterable the iterable for cycling * @return indefinitely iterable of type T */ public static <T> Iterable<T> cycle(final Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private Iterator<T> _iterator = iterable.iterator(); private ArrayList<T> _saved = new ArrayList<T>(); private boolean _firstCycle = true; @Override public boolean hasNext() { return _iterator.hasNext(); } @Override public T next() { if (_iterator.hasNext() && _firstCycle) { T item = _iterator.next(); _saved.add(item); return item; } _firstCycle = false; if (!_iterator.hasNext()) { _iterator = _saved.iterator(); } return _iterator.next(); } @Override public void remove() { } }; } }; } /** * Drop items from the iterable while predicate(item) is true. Afterwards, * return every element until the iterable is exhausted. * * @param <T> type * @param predicate the predicate functor * @param iterable the iterable of type T * @return iterable of type T */ public static <T> Iterable<T> dropwhile(final IPredicate<T> predicate, final Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private Iterator<T> _iterator = iterable.iterator(); private T _first = null; private boolean _onFirst = false; private boolean consume() { if (_first == null) { while (_iterator.hasNext()) { _first = _iterator.next(); if (!predicate.call(_first)) { _onFirst = true; return true; } } } return false; } @Override public boolean hasNext() { return consume() || _iterator.hasNext(); } @Override public T next() { consume(); if (_onFirst) { _onFirst = false; return _first; } return _iterator.next(); } @Override public void remove() { } }; } }; } /** * Return an iterable with those items of sequence for which predicate(item) * is true. * * @param <T> type * @param predicate the predicate functor * @param iterable the iterable of type T * @return iterable of type T */ public static <T> Iterable<T> filter(final IPredicate<T> predicate, final Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private final Iterator<T> _iterator = iterable.iterator(); private T _last = null; private boolean consume() { if (_last == null) { while (_iterator.hasNext()) { _last = _iterator.next(); if (predicate.call(_last)) { return true; } } _last = null; } return false; } @Override public boolean hasNext() { return consume() || _iterator.hasNext(); } @Override public T next() { consume(); T tmp = _last; _last = null; return tmp; } @Override public void remove() { } }; } }; } /** * Return an iterable with those items of sequence for which predicate(item) * is false. * * @param <T> type * @param predicate the predicate functor * @param iterable the iterable of type T * @return iterable of type T */ public static <T> Iterable<T> filterfalse(final IPredicate<T> predicate, final Iterable<T> iterable) { return filter(new IPredicate<T>() { @Override public Boolean call(T object) { return !predicate.call(object); } }, iterable); } /** * Return successive entries from an iterable as long as the predicate * evaluates to true for each entry. * * @param <T> type * @param predicate the predicate functor * @param iterable the iterable of type T * @return iterable of type T */ public static <T> Iterable<T> takewhile(final IPredicate<T> predicate, final Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private final Iterator<T> _iterator = iterable.iterator(); private T _last = null; private boolean consume() { if (_last == null) { if (_iterator.hasNext()) { _last = _iterator.next(); if (predicate.call(_last)) { return true; } } } return false; } @Override public boolean hasNext() { return consume(); } @Override public T next() { consume(); T tmp = _last; _last = null; return tmp; } @Override public void remove() { } }; } }; } /** * Return an iterable that aggregates elements from each of the iterables. * Iteration continues until the shortest iterable is exhausted. All * trailing items of longer iterables are lost. * * @param <T> type * @param iterables 1 to n Iterable&lt;T&gt; objects * @return iterable of lists of type T */ public static <T> Iterable<List<T>> zip(final Iterable<T>... iterables) { return zip(Arrays.asList(iterables)); } /** * Return an iterable that aggregates elements from each of the iterables. * Iteration continues until the shortest iterable is exhausted. All * trailing items of longer iterables are lost. * * @param <T> type * @param iterables iterable of Iterable&lt;T&gt; objects * @return iterable of lists of type T */ public static <T> Iterable<List<T>> zip(final Iterable<Iterable<T>> iterables) { return new Iterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return new Iterator<List<T>>() { private List<Iterator<T>> _outer = list(map(new IteratorFunctor<T>(), iterables)); @Override public boolean hasNext() { for (Iterator<T> inner : _outer) { if (!inner.hasNext()) return false; } return true && _outer.size() != 0; } @Override public List<T> next() { ArrayList<T> ret = new ArrayList<T>(_outer.size()); for (Iterator<T> inner : _outer) { ret.add(inner.next()); } return ret; } @Override public void remove() { } }; } }; } /** * Return an iterable that aggregates elements from each of the iterables. * If the iterables are of uneven length, missing values are filled-in with * fillvalue. Iteration continues until the longest iterable is exhausted. * * @param <T> type * @param fillvalue value to fill in if iterable is exhausted * @param iterables 1 to n Iterable&lt;T&gt; objects * @return iterable of lists of type T */ public static <T> Iterable<List<T>> zip(final T fillvalue, final Iterable<T>... iterables) { return zip(fillvalue, Arrays.asList(iterables)); } /** * Return an iterable that aggregates elements from each of the iterables. * If the iterables are of uneven length, missing values are filled-in with * fillvalue. Iteration continues until the longest iterable is exhausted. * * @param <T> type * @param fillvalue value to fill in if iterable is exhausted * @param iterables iterable of Iterable&lt;T&gt; objects * @return iterable of lists of type T */ public static <T> Iterable<List<T>> zip(final T fillvalue, final Iterable<Iterable<T>> iterables) { return new Iterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return new Iterator<List<T>>() { private List<Iterator<T>> _outer = list(map(new IteratorFunctor<T>(), iterables)); @Override public boolean hasNext() { for (Iterator<T> inner : _outer) { if (inner.hasNext()) return true; } return false; } @Override public List<T> next() { ArrayList<T> ret = new ArrayList<T>(_outer.size()); for (Iterator<T> inner : _outer) { if (inner.hasNext()) { ret.add(inner.next()); } else { ret.add(fillvalue); } } return ret; } @Override public void remove() { } }; } }; } /** * Make an iterator that returns object over and over again. Runs * indefinitely. * * @param <T> type * @param object the object to repeat * @return iterable of type T */ public static <T> Iterable<T> repeat(final T object) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return true; } @Override public T next() { return object; } @Override public void remove() { } }; } }; } /** * Make an iterator that returns object over and over again. Runs * <b>times</b> times. * * @param <T> type * @param object the object to repeat * @return iterable of type T */ public static <T> Iterable<T> repeat(final T object, final int times) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private int _count = times; @Override public boolean hasNext() { return _count > 0; } @Override public T next() { _count--; return object; } @Override public void remove() { } }; } }; } /** * Return an iterable containing a pair which holds the count and value of * the original value from <b>iterable</b>. * * @param <T> type * @param iterable iterable of type T * @return iterable of type Pair&lt;Integer, T&gt; */ public static <T> Iterable<Pair<Integer, T>> enumerate(final Iterable<T> iterable) { return enumerate(iterable, 0); } /** * Return an iterable containing a pair which holds the count and value of * the original value from <b>iterable</b>. * * @param <T> type * @param iterable iterable of type T * @param start enumeration start value * @return iterable of type Pair&lt;Integer, T&gt; */ public static <T> Iterable<Pair<Integer, T>> enumerate(final Iterable<T> iterable, final int start) { return new Iterable<Pair<Integer, T>>() { @Override public Iterator<Pair<Integer, T>> iterator() { return new Iterator<Pair<Integer, T>>() { private Iterator<T> _iterator = iterable.iterator(); private int _counter = start; @Override public boolean hasNext() { return _iterator.hasNext(); } @Override public Pair<Integer, T> next() { return Pair.create(_counter++, _iterator.next()); } @Override public void remove() { } }; } }; } /** * Return true if predicate(x) is true for every element in iterable. * * @param <T> type * @param predicate the predicate functor * @param iterable iterable of type T * @return true if predicate(x) is true for every element in iterable */ public static <T> boolean all(final IPredicate<T> predicate, final Iterable<T> iterable) { for (@SuppressWarnings("unused") final T item : filterfalse(predicate, iterable)) { return false; } return true; } /** * Return true if predicate(x) is true for at least one element in iterable. * * @param <T> type * @param predicate the predicate functor * @param iterable iterable of type T * @return true if predicate(x) is true for at least one element in iterable */ public static <T> boolean any(final IPredicate<T> predicate, final Iterable<T> iterable) { for (@SuppressWarnings("unused") final T Item : filter(predicate, iterable)) { return true; } return false; } /** * Return true if predicate(x) is false for every element in iterable. * * @param <T> type * @param predicate the predicate functor * @param iterable iterable of type T * @return true if predicate(x) is false for every element in iterable */ public static <T> boolean no(final IPredicate<T> predicate, final Iterable<T> iterable) { for (@SuppressWarnings("unused") final T item : filter(predicate, iterable)) { return false; } return true; } /** * Returns all elements in iterable and then returns padding object * indefinitely. * * @param <T> type * @param iterable iterable of type T * @param padding the padding object * @return iterable of type T */ @SuppressWarnings("unchecked") public static <T> Iterable<T> pad(final Iterable<T> iterable, final T padding) { return chain(iterable, repeat(padding)); } /** * Count how many times the predicate is true in the iterable. * * @param <T> type * @param predicate the predicate functor * @param iterable iterable of type T * @return number of items where predicate(item) is true */ public static <T> int quantify(final IPredicate<T> predicate, final Iterable<T> iterable) { int count = 0; for (@SuppressWarnings("unused") final T Item : filter(predicate, iterable)) { count++; } return count; } /** * Returns the iterable n times. * * @param <T> type * @param iterable the iterable to repeat * @param n repeat how many times * * @return iterable of type T */ public static <T> Iterable<T> ncycles(final Iterable<T> iterable, final int n) { return chain(repeat(iterable, n)); } /** * Return an iterable that returns selected elements from <b>iterable</b> * which ranges from position 0 to <b>stop</b> and steps of 1. * * slice(range(10), 5) -> 0, 1, 2, 3, 4 * * @param <T> type * @param iterable iterable of type T * @param stop the last element * @return iterable of type T */ public static <T> Iterable<T> slice(final Iterable<T> iterable, final int stop) { return slice(iterable, 0, stop, 1); } /** * Return an iterable that returns selected elements from <b>iterable</b> * which ranges from position <b>start</b> to <b>stop</b> and steps of 1. * * slice(range(10), 2, 5) -> 2, 3, 4 * * @param <T> type * @param iterable iterable of type T * @param start the first element * @param stop the last element * @return iterable of type T */ public static <T> Iterable<T> slice(final Iterable<T> iterable, final int start, final int stop) { return slice(iterable, start, stop, 1); } /** * Return an iterable that returns selected elements from <b>iterable</b> * which ranges from position <b>start</b> to <b>stop</b> and steps of * <b>step</b>. * * slice(range(10), 2, 5) -> 2, 3, 4 * * @param <T> type * @param iterable iterable of type T * @param start the first element * @param stop the last element * @return iterable of type T */ public static <T> Iterable<T> slice(final Iterable<T> iterable, final int start, final int stop, final int step) { assert step > 0; return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { final Iterator<Integer> _counter = range(start, stop < 0 ? Integer.MAX_VALUE : stop, step).iterator(); final Iterator<Pair<Integer, T>> _iterator = enumerate(iterable).iterator(); Integer _current_counter = _counter.hasNext() ? _counter.next() : null; T _last = null; private final void consume() { if (_last == null) { while (_iterator.hasNext() && _current_counter != null) { Pair<Integer, T> p = _iterator.next(); if (p.getFirst() == _current_counter) { _last = p.getSecond(); - if (_counter.hasNext()) { - _current_counter = _counter.next(); - } + _current_counter = _counter.hasNext() ? _counter.next() : null; return; } } } } @Override public boolean hasNext() { consume(); return _last != null; } @Override public T next() { consume(); T ret = _last; _last = null; return ret; } @Override public void remove() { } }; } }; } }
true
true
public static <T> Iterable<T> slice(final Iterable<T> iterable, final int start, final int stop, final int step) { assert step > 0; return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { final Iterator<Integer> _counter = range(start, stop < 0 ? Integer.MAX_VALUE : stop, step).iterator(); final Iterator<Pair<Integer, T>> _iterator = enumerate(iterable).iterator(); Integer _current_counter = _counter.hasNext() ? _counter.next() : null; T _last = null; private final void consume() { if (_last == null) { while (_iterator.hasNext() && _current_counter != null) { Pair<Integer, T> p = _iterator.next(); if (p.getFirst() == _current_counter) { _last = p.getSecond(); if (_counter.hasNext()) { _current_counter = _counter.next(); } return; } } } } @Override public boolean hasNext() { consume(); return _last != null; } @Override public T next() { consume(); T ret = _last; _last = null; return ret; } @Override public void remove() { } }; } }; }
public static <T> Iterable<T> slice(final Iterable<T> iterable, final int start, final int stop, final int step) { assert step > 0; return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { final Iterator<Integer> _counter = range(start, stop < 0 ? Integer.MAX_VALUE : stop, step).iterator(); final Iterator<Pair<Integer, T>> _iterator = enumerate(iterable).iterator(); Integer _current_counter = _counter.hasNext() ? _counter.next() : null; T _last = null; private final void consume() { if (_last == null) { while (_iterator.hasNext() && _current_counter != null) { Pair<Integer, T> p = _iterator.next(); if (p.getFirst() == _current_counter) { _last = p.getSecond(); _current_counter = _counter.hasNext() ? _counter.next() : null; return; } } } } @Override public boolean hasNext() { consume(); return _last != null; } @Override public T next() { consume(); T ret = _last; _last = null; return ret; } @Override public void remove() { } }; } }; }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/OMElementUtils.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/OMElementUtils.java index 4eb311290..6b54fe492 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/OMElementUtils.java +++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/OMElementUtils.java @@ -1,110 +1,111 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.config.xml; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.xpath.AXIOMXPath; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseException; import org.jaxen.JaxenException; import java.util.Iterator; /** * Holds Axiom utility methods used by Synapse */ public class OMElementUtils { private static final Log log = LogFactory.getLog(OMElementUtils.class); /** * Return the namespace with the given prefix, using the given element * @param prefix the prefix looked up * @param elem the source element to use * @return the namespace which maps to the prefix or null */ public static String getNameSpaceWithPrefix(String prefix, OMElement elem) { if (prefix == null || elem == null) { log.warn("Searching for null NS prefix and/or using null OMElement"); return null; } OMElement currentElem = elem; while (true) { Iterator iter = currentElem.getAllDeclaredNamespaces(); while (iter.hasNext()) { OMNamespace ns = (OMNamespace) iter.next(); if (prefix.equals(ns.getPrefix())) { return ns.getNamespaceURI(); } } OMContainer parent = currentElem.getParent(); if (parent != null && parent instanceof OMElement) { currentElem = (OMElement)parent; } else { return null; } } } /** * Add all applicable xmlns NS declarations of element 'elem' into XPath expression * @param xpath xmlns:m0="http://services.samples/xsd" * @param elem * @param log */ public static void addNameSpaces(AXIOMXPath xpath, OMElement elem, Log log) { OMElement currentElem = elem; - while (currentElem != null) { + while (currentElem != null) { Iterator it = currentElem.getAllDeclaredNamespaces(); while (it.hasNext()) { OMNamespace n = (OMNamespace) it.next(); - if (n != null) { + // assume the behavior of attributes as unqualified from default + if (n != null && !"".equals(n.getPrefix())) { try { xpath.addNamespace(n.getPrefix(), n.getNamespaceURI()); } catch (JaxenException je) { String msg = "Error adding declared name space with prefix : " + n.getPrefix() + "and uri : " + n.getNamespaceURI() + " to the XPath : " + xpath; log.error(msg); throw new SynapseException(msg, je); } } } OMContainer parent = currentElem.getParent(); //if the parent is a document element or parent is null ,then return if (parent == null || parent instanceof OMDocument) { return; } if (parent instanceof OMElement) { currentElem = (OMElement) parent; } } } }
false
true
public static void addNameSpaces(AXIOMXPath xpath, OMElement elem, Log log) { OMElement currentElem = elem; while (currentElem != null) { Iterator it = currentElem.getAllDeclaredNamespaces(); while (it.hasNext()) { OMNamespace n = (OMNamespace) it.next(); if (n != null) { try { xpath.addNamespace(n.getPrefix(), n.getNamespaceURI()); } catch (JaxenException je) { String msg = "Error adding declared name space with prefix : " + n.getPrefix() + "and uri : " + n.getNamespaceURI() + " to the XPath : " + xpath; log.error(msg); throw new SynapseException(msg, je); } } } OMContainer parent = currentElem.getParent(); //if the parent is a document element or parent is null ,then return if (parent == null || parent instanceof OMDocument) { return; } if (parent instanceof OMElement) { currentElem = (OMElement) parent; } } }
public static void addNameSpaces(AXIOMXPath xpath, OMElement elem, Log log) { OMElement currentElem = elem; while (currentElem != null) { Iterator it = currentElem.getAllDeclaredNamespaces(); while (it.hasNext()) { OMNamespace n = (OMNamespace) it.next(); // assume the behavior of attributes as unqualified from default if (n != null && !"".equals(n.getPrefix())) { try { xpath.addNamespace(n.getPrefix(), n.getNamespaceURI()); } catch (JaxenException je) { String msg = "Error adding declared name space with prefix : " + n.getPrefix() + "and uri : " + n.getNamespaceURI() + " to the XPath : " + xpath; log.error(msg); throw new SynapseException(msg, je); } } } OMContainer parent = currentElem.getParent(); //if the parent is a document element or parent is null ,then return if (parent == null || parent instanceof OMDocument) { return; } if (parent instanceof OMElement) { currentElem = (OMElement) parent; } } }
diff --git a/src/org/jovislab/tools/hadoop/hadoopgrams/filters/Wp2TxtDump.java b/src/org/jovislab/tools/hadoop/hadoopgrams/filters/Wp2TxtDump.java index 215cae1..e824e8f 100644 --- a/src/org/jovislab/tools/hadoop/hadoopgrams/filters/Wp2TxtDump.java +++ b/src/org/jovislab/tools/hadoop/hadoopgrams/filters/Wp2TxtDump.java @@ -1,55 +1,77 @@ package org.jovislab.tools.hadoop.hadoopgrams.filters; import org.jovislab.tools.hadoop.hadoopgrams.Filter; /* This filter is to process Wikipedia dumps preprocessed with WP2TXT software */ /* Not just raw dumps in XML format */ public class Wp2TxtDump implements Filter { public String filter(String input) { if (input.startsWith("[[")) { // Remove title + if (input.length() - 4 < 1) + return ""; return input.substring(2, input.length() - 2); } if (input.startsWith("= ")) { // Remove header + if (input.length() - 4 < 1) + return ""; return input.substring(2, input.length() - 2); } if (input.startsWith("== ")) { // Remove header + if (input.length() - 6 < 1) + return ""; return input.substring(3, input.length() - 3); } if (input.startsWith("=== ")) { // Remove header + if (input.length() - 8 < 1) + return ""; return input.substring(4, input.length() - 4); } if (input.startsWith("==== ")) { // Remove header + if (input.length() - 10 < 1) + return ""; return input.substring(5, input.length() - 5); } if (input.startsWith("===== ")) { // Remove header + if (input.length() - 12 < 1) + return ""; return input.substring(6, input.length() - 6); } if (input.startsWith("====== ")) { // Remove header + if (input.length() - 14 < 1) + return ""; return input.substring(7, input.length() - 7); } if (input.startsWith("======= ")) { // Remove header + if (input.length() - 16 < 1) + return ""; return input.substring(8, input.length() - 8); } if (input.startsWith("======== ")) { // Remove header + if (input.length() - 18 < 1) + return ""; return input.substring(9, input.length() - 9); } if (input.startsWith("- ")) { // Remove list indicator + if (input.length() - 2 < 1) + return ""; return input.substring(2, input.length()); } if (input.startsWith("* ")) { // Remove list indicator + if (input.length() - 2 < 1) + return ""; return input.substring(2, input.length()); } return input; } }
false
true
public String filter(String input) { if (input.startsWith("[[")) { // Remove title return input.substring(2, input.length() - 2); } if (input.startsWith("= ")) { // Remove header return input.substring(2, input.length() - 2); } if (input.startsWith("== ")) { // Remove header return input.substring(3, input.length() - 3); } if (input.startsWith("=== ")) { // Remove header return input.substring(4, input.length() - 4); } if (input.startsWith("==== ")) { // Remove header return input.substring(5, input.length() - 5); } if (input.startsWith("===== ")) { // Remove header return input.substring(6, input.length() - 6); } if (input.startsWith("====== ")) { // Remove header return input.substring(7, input.length() - 7); } if (input.startsWith("======= ")) { // Remove header return input.substring(8, input.length() - 8); } if (input.startsWith("======== ")) { // Remove header return input.substring(9, input.length() - 9); } if (input.startsWith("- ")) { // Remove list indicator return input.substring(2, input.length()); } if (input.startsWith("* ")) { // Remove list indicator return input.substring(2, input.length()); } return input; }
public String filter(String input) { if (input.startsWith("[[")) { // Remove title if (input.length() - 4 < 1) return ""; return input.substring(2, input.length() - 2); } if (input.startsWith("= ")) { // Remove header if (input.length() - 4 < 1) return ""; return input.substring(2, input.length() - 2); } if (input.startsWith("== ")) { // Remove header if (input.length() - 6 < 1) return ""; return input.substring(3, input.length() - 3); } if (input.startsWith("=== ")) { // Remove header if (input.length() - 8 < 1) return ""; return input.substring(4, input.length() - 4); } if (input.startsWith("==== ")) { // Remove header if (input.length() - 10 < 1) return ""; return input.substring(5, input.length() - 5); } if (input.startsWith("===== ")) { // Remove header if (input.length() - 12 < 1) return ""; return input.substring(6, input.length() - 6); } if (input.startsWith("====== ")) { // Remove header if (input.length() - 14 < 1) return ""; return input.substring(7, input.length() - 7); } if (input.startsWith("======= ")) { // Remove header if (input.length() - 16 < 1) return ""; return input.substring(8, input.length() - 8); } if (input.startsWith("======== ")) { // Remove header if (input.length() - 18 < 1) return ""; return input.substring(9, input.length() - 9); } if (input.startsWith("- ")) { // Remove list indicator if (input.length() - 2 < 1) return ""; return input.substring(2, input.length()); } if (input.startsWith("* ")) { // Remove list indicator if (input.length() - 2 < 1) return ""; return input.substring(2, input.length()); } return input; }
diff --git a/MonTransit/src/org/montrealtransit/android/activity/SearchResult.java b/MonTransit/src/org/montrealtransit/android/activity/SearchResult.java index ac67906d..8bd95f06 100644 --- a/MonTransit/src/org/montrealtransit/android/activity/SearchResult.java +++ b/MonTransit/src/org/montrealtransit/android/activity/SearchResult.java @@ -1,181 +1,179 @@ package org.montrealtransit.android.activity; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.BusUtils; import org.montrealtransit.android.MenuUtils; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.provider.StmManager; import org.montrealtransit.android.provider.StmStore; import org.montrealtransit.android.provider.StmStore.BusStop; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.RelativeLayout; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * This activity shows the search results. * @author Mathieu Méa */ public class SearchResult extends ListActivity { /** * The log tag. */ private static final String TAG = SearchResult.class.getSimpleName(); /** * The tracker tag. */ private static final String TRACKER_TAG = "/SearchResult"; /** * The bus line number index in the the view. */ private static final int LINE_NUMBER_VIEW_INDEX = 1; @Override protected void onCreate(Bundle savedInstanceState) { MyLog.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); // set the UI setContentView(R.layout.search_result); getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { MyLog.v(TAG, "onItemClick(%s, %s, %s, %s)", l.getId(), v.getId(), position, id); if (id > 0) { Intent intent = new Intent(SearchResult.this, BusStopInfo.class); TextView lineNumberTextView = (TextView) ((RelativeLayout) v).getChildAt(LINE_NUMBER_VIEW_INDEX); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, lineNumberTextView.getText().toString()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, String.valueOf(id)); startActivity(intent); } } }); processIntent(); } @Override protected void onNewIntent(Intent intent) { MyLog.v(TAG, "onNewIntent()"); setIntent(intent); processIntent(); super.onNewIntent(intent); } @Override protected void onResume() { MyLog.v(TAG, "onResume()"); AnalyticsUtils.trackPageView(this, TRACKER_TAG); super.onResume(); } /** * Process the intent of the activity. */ private void processIntent() { if (getIntent() != null) { if (Intent.ACTION_VIEW.equals(getIntent().getAction())) { // MyLog.d(TAG, "ACTION_VIEW"); // from click on search results showBusStop(getIntent().getData().getPathSegments().get(0)); finish(); } else if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) { // MyLog.d(TAG, "ACTION_SEARCH"); // an actual search String searchTerm = getIntent().getStringExtra(SearchManager.QUERY); // MyLog.d(TAG, "search: " + searchTerm); setTitle(getString(R.string.search_result_for_and_keyword, searchTerm)); // setListAdapter(getAdapter(searchTerm)); getListView().setAdapter(null); new LoadSearchResultTask().execute(searchTerm); } } } /** * This task create load the search results cursor. * @author Mathieu Méa */ private class LoadSearchResultTask extends AsyncTask<String, String, Cursor> { @Override protected Cursor doInBackground(String... arg0) { return StmManager.searchResult(SearchResult.this.getContentResolver(), arg0[0]); } @Override protected void onPostExecute(Cursor result) { setAdapter(result); super.onPostExecute(result); } } /** * Set the list view adapter. * @param cursor the cursor used to create the adapter */ private void setAdapter(Cursor cursor) { - String[] from = new String[] { StmStore.BusStop.STOP_CODE, StmStore.BusStop.STOP_PLACE, - StmStore.BusStop.STOP_LINE_NUMBER, StmStore.BusStop.LINE_NAME, StmStore.BusStop.STOP_DIRECTION_ID }; + String[] from = new String[] { StmStore.BusStop.STOP_CODE, StmStore.BusStop.STOP_PLACE, StmStore.BusStop.STOP_LINE_NUMBER, StmStore.BusStop.LINE_NAME, + StmStore.BusStop.STOP_DIRECTION_ID }; int[] to = new int[] { R.id.stop_code, R.id.label, R.id.line_number, R.id.line_name, R.id.line_direction }; - @SuppressWarnings("deprecation") //TODO use {@link android.app.LoaderManager} with a {@link android.content.CursorLoader} - SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.search_result_bus_stop_item, cursor, from, - to); + SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.search_result_bus_stop_item, cursor, from, to, 0); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { switch (view.getId()) { case R.id.line_direction: String simpleDirectionId = cursor.getString(columnIndex); ((TextView) view).setText(BusUtils.getBusLineSimpleDirection(simpleDirectionId)); return true; case R.id.label: String busStopPlace = cursor.getString(cursor.getColumnIndex(StmStore.BusStop.STOP_PLACE)); ((TextView) view).setText(BusUtils.cleanBusStopPlace(busStopPlace)); return true; default: return false; } } }); getListView().setAdapter(adapter); } /** * Launch the view bus stop info activity. * @param selectedSearchResultId the selected search result */ private void showBusStop(String selectedSearchResultId) { MyLog.v(TAG, "showBusStop(%s)", selectedSearchResultId); String busStopCode = BusStop.getCodeFromUID(selectedSearchResultId); String busLineNumber = BusStop.getLineNumberFromUID(selectedSearchResultId); if (busStopCode != null && busLineNumber != null) { Intent intent = new Intent(this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busLineNumber); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStopCode); startActivity(intent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { return MenuUtils.createMainMenu(this, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.handleCommonMenuActions(this, item); } }
false
true
private void setAdapter(Cursor cursor) { String[] from = new String[] { StmStore.BusStop.STOP_CODE, StmStore.BusStop.STOP_PLACE, StmStore.BusStop.STOP_LINE_NUMBER, StmStore.BusStop.LINE_NAME, StmStore.BusStop.STOP_DIRECTION_ID }; int[] to = new int[] { R.id.stop_code, R.id.label, R.id.line_number, R.id.line_name, R.id.line_direction }; @SuppressWarnings("deprecation") //TODO use {@link android.app.LoaderManager} with a {@link android.content.CursorLoader} SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.search_result_bus_stop_item, cursor, from, to); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { switch (view.getId()) { case R.id.line_direction: String simpleDirectionId = cursor.getString(columnIndex); ((TextView) view).setText(BusUtils.getBusLineSimpleDirection(simpleDirectionId)); return true; case R.id.label: String busStopPlace = cursor.getString(cursor.getColumnIndex(StmStore.BusStop.STOP_PLACE)); ((TextView) view).setText(BusUtils.cleanBusStopPlace(busStopPlace)); return true; default: return false; } } }); getListView().setAdapter(adapter); }
private void setAdapter(Cursor cursor) { String[] from = new String[] { StmStore.BusStop.STOP_CODE, StmStore.BusStop.STOP_PLACE, StmStore.BusStop.STOP_LINE_NUMBER, StmStore.BusStop.LINE_NAME, StmStore.BusStop.STOP_DIRECTION_ID }; int[] to = new int[] { R.id.stop_code, R.id.label, R.id.line_number, R.id.line_name, R.id.line_direction }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.search_result_bus_stop_item, cursor, from, to, 0); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { switch (view.getId()) { case R.id.line_direction: String simpleDirectionId = cursor.getString(columnIndex); ((TextView) view).setText(BusUtils.getBusLineSimpleDirection(simpleDirectionId)); return true; case R.id.label: String busStopPlace = cursor.getString(cursor.getColumnIndex(StmStore.BusStop.STOP_PLACE)); ((TextView) view).setText(BusUtils.cleanBusStopPlace(busStopPlace)); return true; default: return false; } } }); getListView().setAdapter(adapter); }
diff --git a/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java b/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java index a54a5d6..08153dc 100644 --- a/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java +++ b/src/main/java/org/dasein/cloud/cloudstack/compute/Volumes.java @@ -1,909 +1,909 @@ /** * Copyright (C) 2009-2013 enstratius, 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.dasein.cloud.cloudstack.compute; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.log4j.Logger; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.cloudstack.CSCloud; import org.dasein.cloud.cloudstack.CSException; import org.dasein.cloud.cloudstack.CSMethod; import org.dasein.cloud.cloudstack.CSServiceProvider; import org.dasein.cloud.cloudstack.CSVersion; import org.dasein.cloud.cloudstack.Param; import org.dasein.cloud.compute.AbstractVolumeSupport; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.Snapshot; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VmState; import org.dasein.cloud.compute.Volume; import org.dasein.cloud.compute.VolumeCreateOptions; import org.dasein.cloud.compute.VolumeFormat; import org.dasein.cloud.compute.VolumeProduct; import org.dasein.cloud.compute.VolumeState; import org.dasein.cloud.compute.VolumeType; import org.dasein.cloud.util.APITrace; import org.dasein.cloud.util.Cache; import org.dasein.cloud.util.CacheLevel; import org.dasein.util.CalendarWrapper; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Volumes extends AbstractVolumeSupport { static private final Logger logger = Logger.getLogger(Volumes.class); static private final String ATTACH_VOLUME = "attachVolume"; static private final String CREATE_VOLUME = "createVolume"; static private final String DELETE_VOLUME = "deleteVolume"; static private final String DETACH_VOLUME = "detachVolume"; static private final String LIST_DISK_OFFERINGS = "listDiskOfferings"; static private final String LIST_VOLUMES = "listVolumes"; static public class DiskOffering { public String id; public long diskSize; public String name; public String description; public String type; public String toString() {return "DiskOffering ["+id+"] of size "+diskSize;} } private CSCloud provider; Volumes(CSCloud provider) { super(provider); this.provider = provider; } @Override public void attach(@Nonnull String volumeId, @Nonnull String serverId, @Nullable String deviceId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.attach"); try { Param[] params; if( logger.isInfoEnabled() ) { logger.info("attaching " + volumeId + " to " + serverId + " as " + deviceId); } VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId); if( vm == null ) { throw new CloudException("No such virtual machine: " + serverId); } long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L); while( timeout > System.currentTimeMillis() ) { if( VmState.RUNNING.equals(vm.getCurrentState()) || VmState.STOPPED.equals(vm.getCurrentState()) ) { break; } try { Thread.sleep(15000L); } catch( InterruptedException ignore ) { } try { vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(serverId); } catch( Throwable ignore ) { } if( vm == null ) { throw new CloudException("Virtual machine " + serverId + " disappeared waiting for it to enter an attachable state"); } } if( deviceId == null ) { params = new Param[] { new Param("id", volumeId), new Param("virtualMachineId", serverId) }; } else { deviceId = toDeviceNumber(deviceId); if( logger.isDebugEnabled() ) { logger.debug("Device mapping is: " + deviceId); } params = new Param[] { new Param("id", volumeId), new Param("virtualMachineId", serverId), new Param("deviceId", deviceId) }; } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(ATTACH_VOLUME, params), ATTACH_VOLUME); if( doc == null ) { throw new CloudException("No such volume or server"); } provider.waitForJob(doc, "Attach Volume"); } finally { APITrace.end(); } } @Override public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.createVolume"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was provided for this request"); } if( options.getFormat().equals(VolumeFormat.NFS) ) { throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName()); } String snapshotId = options.getSnapshotId(); String productId = options.getVolumeProductId(); VolumeProduct product = null; if( productId != null ) { for( VolumeProduct prd : listVolumeProducts() ) { if( productId.equals(prd.getProviderProductId()) ) { product = prd; break; } } } Storage<Gigabyte> size; if( snapshotId == null ) { if( product == null ) { size = options.getVolumeSize(); if( size.intValue() < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } Iterable<VolumeProduct> products = listVolumeProducts(); VolumeProduct best = null; VolumeProduct custom = null; for( VolumeProduct p : products ) { Storage<Gigabyte> s = p.getVolumeSize(); if( s == null || s.intValue() == 0 ) { if (custom == null) { custom = p; } continue; } long currentSize = s.getQuantity().longValue(); s = (best == null ? null : best.getVolumeSize()); long bestSize = (s == null ? 0L : s.getQuantity().longValue()); if( size.longValue() > 0L && size.longValue() == currentSize ) { product = p; break; } if( best == null ) { best = p; } else if( bestSize > 0L || currentSize > 0L ) { if( size.longValue() > 0L ) { - if( bestSize < size.longValue() && bestSize >0L && currentSize > size.longValue() ) { + if( bestSize < size.longValue() && bestSize >0L && (currentSize > size.longValue() || currentSize > bestSize) ) { best = p; } else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) { best = p; } } else if( currentSize > 0L && currentSize < bestSize ) { best = p; } } } if( product == null ) { if (custom != null) { product = custom; } else { product = best; } } } else { size = product.getVolumeSize(); if( size == null || size.intValue() < 1 ) { size = options.getVolumeSize(); } } if( product == null && size.longValue() < 1L ) { throw new CloudException("No offering matching " + options.getVolumeProductId()); } } else { Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId); if( snapshot == null ) { throw new CloudException("No such snapshot: " + snapshotId); } int s = snapshot.getSizeInGb(); if( s < 1 || s < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } else { size = new Storage<Gigabyte>(s, Storage.GIGABYTE); } } Param[] params; if( product == null && snapshotId == null ) { /*params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("size", String.valueOf(size.longValue())) }; */ throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request"); } else if( snapshotId != null ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("snapshotId", snapshotId), new Param("size", String.valueOf(size.longValue())) }; } else { Storage<Gigabyte> s = product.getVolumeSize(); if( s == null || s.intValue() < 1 ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()), new Param("size", String.valueOf(size.longValue())) }; } else { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()) }; } } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME); NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1 String volumeId = null; if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } if( volumeId == null ) { matches = doc.getElementsByTagName("id"); // v2.2 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { matches = doc.getElementsByTagName("jobid"); // v4.1 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { throw new CloudException("Failed to create volume"); } Document responseDoc = provider.waitForJob(doc, "Create Volume"); if (responseDoc != null){ NodeList nodeList = responseDoc.getElementsByTagName("volume"); if (nodeList.getLength() > 0) { Node volume = nodeList.item(0); NodeList attributes = volume.getChildNodes(); for (int i = 0; i<attributes.getLength(); i++) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if (name.equalsIgnoreCase("id")) { volumeId = value; break; } } } } return volumeId; } finally { APITrace.end(); } } @Override public void detach(@Nonnull String volumeId, boolean force) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.detach"); try { CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(DETACH_VOLUME, new Param("id", volumeId)), DETACH_VOLUME); provider.waitForJob(doc, "Detach Volume"); } finally { APITrace.end(); } } @Override public int getMaximumVolumeCount() throws InternalException, CloudException { return -2; } @Override public @Nonnull Storage<Gigabyte> getMaximumVolumeSize() throws InternalException, CloudException { return new Storage<Gigabyte>(5000, Storage.GIGABYTE); } @Override public @Nonnull Storage<Gigabyte> getMinimumVolumeSize() throws InternalException, CloudException { return new Storage<Gigabyte>(1, Storage.GIGABYTE); } @Nonnull Collection<DiskOffering> getDiskOfferings() throws InternalException, CloudException { CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_DISK_OFFERINGS), LIST_DISK_OFFERINGS); ArrayList<DiskOffering> offerings = new ArrayList<DiskOffering>(); NodeList matches = doc.getElementsByTagName("diskoffering"); for( int i=0; i<matches.getLength(); i++ ) { DiskOffering offering = new DiskOffering(); Node node = matches.item(i); NodeList attributes; attributes = node.getChildNodes(); for( int j=0; j<attributes.getLength(); j++ ) { Node n = attributes.item(j); String value; if( n.getChildNodes().getLength() > 0 ) { value = n.getFirstChild().getNodeValue(); } else { value = null; } if( n.getNodeName().equals("id") ) { offering.id = value; } else if( n.getNodeName().equals("disksize") ) { offering.diskSize = Long.parseLong(value); } else if( n.getNodeName().equalsIgnoreCase("name") ) { offering.name = value; } else if( n.getNodeName().equalsIgnoreCase("displayText") ) { offering.description = value; } else if( n.getNodeName().equalsIgnoreCase("storagetype") ) { offering.type = value; } } if( offering.id != null ) { if( offering.name == null ) { if( offering.diskSize > 0 ) { offering.name = offering.diskSize + " GB"; } else { offering.name = "Custom #" + offering.id; } } if( offering.description == null ) { offering.description = offering.name; } offerings.add(offering); } } return offerings; } @Override public @Nonnull String getProviderTermForVolume(@Nonnull Locale locale) { return "volume"; } @Nullable String getRootVolumeId(@Nonnull String serverId) throws InternalException, CloudException { Volume volume = getRootVolume(serverId); return (volume == null ? null : volume.getProviderVolumeId()); } private @Nullable Volume getRootVolume(@Nonnull String serverId) throws InternalException, CloudException { CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("virtualMachineId", serverId)), LIST_VOLUMES); NodeList matches = doc.getElementsByTagName("volume"); for( int i=0; i<matches.getLength(); i++ ) { Node v = matches.item(i); if( v != null ) { Volume volume = toVolume(v, true); if( volume != null ) { return volume; } } } return null; } @Override public @Nullable Volume getVolume(@Nonnull String volumeId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.getVolume"); try { try { CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("id", volumeId), new Param("zoneId", getContext().getRegionId())), LIST_VOLUMES); NodeList matches = doc.getElementsByTagName("volume"); for( int i=0; i<matches.getLength(); i++ ) { Node v = matches.item(i); if( v != null ) { return toVolume(v, false); } } return null; } catch( CSException e ) { if( e.getHttpCode() == 431 ) { return null; } throw e; } } finally { APITrace.end(); } } @Override public @Nonnull Requirement getVolumeProductRequirement() throws InternalException, CloudException { return Requirement.OPTIONAL; } @Override public boolean isVolumeSizeDeterminedByProduct() throws InternalException, CloudException { return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { APITrace.begin(getProvider(), "Volume.isSubscribed"); try { return provider.getComputeServices().getVirtualMachineSupport().isSubscribed(); } finally { APITrace.end(); } } @Override public @Nonnull Iterable<String> listPossibleDeviceIds(@Nonnull Platform platform) throws InternalException, CloudException { Cache<String> cache; if( platform.isWindows() ) { cache = Cache.getInstance(getProvider(), "windowsDeviceIds", String.class, CacheLevel.CLOUD); } else { cache = Cache.getInstance(getProvider(), "unixDeviceIds", String.class, CacheLevel.CLOUD); } Iterable<String> ids = cache.get(getContext()); if( ids == null ) { ArrayList<String> list = new ArrayList<String>(); if( platform.isWindows() ) { list.add("hde"); list.add("hdf"); list.add("hdg"); list.add("hdh"); list.add("hdi"); list.add("hdj"); } else { list.add("/dev/xvdc"); list.add("/dev/xvde"); list.add("/dev/xvdf"); list.add("/dev/xvdg"); list.add("/dev/xvdh"); list.add("/dev/xvdi"); list.add("/dev/xvdj"); } ids = Collections.unmodifiableList(list); cache.put(getContext(), ids); } return ids; } @Override public @Nonnull Iterable<VolumeFormat> listSupportedFormats() throws InternalException, CloudException { return Collections.singletonList(VolumeFormat.BLOCK); } @Override public @Nonnull Iterable<VolumeProduct> listVolumeProducts() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumeProducts"); try { Cache<VolumeProduct> cache = Cache.getInstance(getProvider(), "volumeProducts", VolumeProduct.class, CacheLevel.REGION_ACCOUNT); Iterable<VolumeProduct> products = cache.get(getContext()); if( products == null ) { ArrayList<VolumeProduct> list = new ArrayList<VolumeProduct>(); for( DiskOffering offering : getDiskOfferings() ) { VolumeProduct p = toProduct(offering); if( p != null && (!provider.getServiceProvider().equals(CSServiceProvider.DEMOCLOUD) || "local".equals(offering.type)) ) { list.add(p); } } products = Collections.unmodifiableList(list); cache.put(getContext(), products); } return products; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listVolumeStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumeStatus"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("zoneId", ctx.getRegionId())), LIST_VOLUMES); ArrayList<ResourceStatus> volumes = new ArrayList<ResourceStatus>(); NodeList matches = doc.getElementsByTagName("volume"); for( int i=0; i<matches.getLength(); i++ ) { Node v = matches.item(i); if( v != null ) { ResourceStatus volume = toStatus(v); if( volume != null ) { volumes.add(volume); } } } return volumes; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<Volume> listVolumes() throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.listVolumes"); try { return listVolumes(false); } finally { APITrace.end(); } } private @Nonnull Collection<Volume> listVolumes(boolean rootOnly) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was specified for this request"); } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(LIST_VOLUMES, new Param("zoneId", ctx.getRegionId())), LIST_VOLUMES); ArrayList<Volume> volumes = new ArrayList<Volume>(); NodeList matches = doc.getElementsByTagName("volume"); for( int i=0; i<matches.getLength(); i++ ) { Node v = matches.item(i); if( v != null ) { Volume volume = toVolume(v, rootOnly); if( volume != null ) { volumes.add(volume); } } } return volumes; } @Override public void remove(@Nonnull String volumeId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.remove"); try { CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(DELETE_VOLUME, new Param("id", volumeId)), DELETE_VOLUME); provider.waitForJob(doc, "Delete Volume"); } finally { APITrace.end(); } } private @Nonnull String toDeviceNumber(@Nonnull String deviceId) { if( !deviceId.startsWith("/dev/") && !deviceId.startsWith("hd") ) { deviceId = "/dev/" + deviceId; } if( deviceId.equals("/dev/xvda") ) { return "0"; } else if( deviceId.equals("/dev/xvdb") ) { return "1"; } else if( deviceId.equals("/dev/xvdc") ) { return "2"; } else if( deviceId.equals("/dev/xvde") ) { return "4"; } else if( deviceId.equals("/dev/xvdf") ) { return "5"; } else if( deviceId.equals("/dev/xvdg") ) { return "6"; } else if( deviceId.equals("/dev/xvdh") ) { return "7"; } else if( deviceId.equals("/dev/xvdi") ) { return "8"; } else if( deviceId.equals("/dev/xvdj") ) { return "9"; } else if( deviceId.equals("hda") ) { return "0"; } else if( deviceId.equals("hdb") ) { return "1"; } else if( deviceId.equals("hdc") ) { return "2"; } else if( deviceId.equals("hdd") ) { return "3"; } else if( deviceId.equals("hde") ) { return "4"; } else if( deviceId.equals("hdf") ) { return "5"; } else if( deviceId.equals("hdg") ) { return "6"; } else if( deviceId.equals("hdh") ) { return "7"; } else if( deviceId.equals("hdi") ) { return "8"; } else if( deviceId.equals("hdj") ) { return "9"; } else { return "9"; } } private @Nonnull String toDeviceID(@Nonnull String deviceNumber, boolean isWindows) { if (deviceNumber == null){ return null; } if (!isWindows){ if( deviceNumber.equals("0") ) { return "/dev/xvda"; } else if( deviceNumber.equals("1") ) { return "/dev/xvdb"; } else if( deviceNumber.equals("2") ) { return "/dev/xvdc"; } else if( deviceNumber.equals("4") ) { return "/dev/xvde"; } else if( deviceNumber.equals("5") ) { return "/dev/xvdf"; } else if( deviceNumber.equals("6") ) { return "/dev/xvdg"; } else if( deviceNumber.equals("7") ) { return "/dev/xvdh"; } else if( deviceNumber.equals("8") ) { return "/dev/xvdi"; } else if( deviceNumber.equals("9") ) { return "/dev/xvdj"; } else { return "/dev/xvdj"; } } else{ if( deviceNumber.equals("0") ) { return "hda"; } else if( deviceNumber.equals("1") ) { return "hdb"; } else if( deviceNumber.equals("2") ) { return "hdc"; } else if( deviceNumber.equals("3") ) { return "hdd"; } else if( deviceNumber.equals("4") ) { return "hde"; } else if( deviceNumber.equals("5") ) { return "hdf"; } else if( deviceNumber.equals("6") ) { return "hdg"; } else if( deviceNumber.equals("7") ) { return "hdh"; } else if( deviceNumber.equals("8") ) { return "hdi"; } else if( deviceNumber.equals("9") ) { return "hdj"; } else { return "hdj"; } } } private @Nullable VolumeProduct toProduct(@Nullable DiskOffering offering) throws InternalException, CloudException { if( offering == null ) { return null; } if( offering.diskSize < 1 ) { return VolumeProduct.getInstance(offering.id, offering.name, offering.description, VolumeType.HDD); } else { return VolumeProduct.getInstance(offering.id, offering.name, offering.description, VolumeType.HDD, new Storage<Gigabyte>(offering.diskSize, Storage.GIGABYTE)); } } private @Nullable ResourceStatus toStatus(@Nullable Node node) throws InternalException, CloudException { if( node == null ) { return null; } NodeList attributes = node.getChildNodes(); VolumeState volumeState = null; String volumeId = null; for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute != null ) { String name = attribute.getNodeName(); if( name.equals("id") ) { volumeId = attribute.getFirstChild().getNodeValue().trim(); } else if( name.equals("state") && attribute.hasChildNodes() ) { String state = attribute.getFirstChild().getNodeValue(); if( state == null ) { volumeState = VolumeState.PENDING; } else if( state.equalsIgnoreCase("created") || state.equalsIgnoreCase("ready") || state.equalsIgnoreCase("allocated") ) { volumeState = VolumeState.AVAILABLE; } else { logger.warn("DEBUG: Unknown state for CloudStack volume: " + state); volumeState = VolumeState.PENDING; } } if( volumeId != null && volumeState != null ) { break; } } } if( volumeId == null ) { return null; } if( volumeState == null ) { volumeState = VolumeState.PENDING; } return new ResourceStatus(volumeId, volumeState); } private @Nullable Volume toVolume(@Nullable Node node, boolean rootOnly) throws InternalException, CloudException { if( node == null ) { return null; } Volume volume = new Volume(); String offeringId = null; NodeList attributes = node.getChildNodes(); String volumeName = null, description = null; boolean root = false; String deviceNumber = null; volume.setFormat(VolumeFormat.BLOCK); for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if( attribute != null ) { String name = attribute.getNodeName(); if( name.equals("id") ) { volume.setProviderVolumeId(attribute.getFirstChild().getNodeValue().trim()); } if( name.equals("zoneid") ) { String zid = attribute.getFirstChild().getNodeValue().trim(); if( !provider.getContext().getRegionId().equals(zid) ) { System.out.println("Zone mismatch: " + provider.getContext().getRegionId()); System.out.println(" " + zid); return null; } } else if( name.equals("type") && attribute.hasChildNodes() ) { if( attribute.getFirstChild().getNodeValue().equalsIgnoreCase("root") ) { root = true; } } else if( name.equals("diskofferingid") && attribute.hasChildNodes() ) { offeringId = attribute.getFirstChild().getNodeValue().trim(); } else if( name.equals("name") && attribute.hasChildNodes() ) { volumeName = attribute.getFirstChild().getNodeValue().trim(); } else if ( name.equals("deviceid") && attribute.hasChildNodes()){ deviceNumber = attribute.getFirstChild().getNodeValue().trim(); } else if( name.equalsIgnoreCase("virtualmachineid") && attribute.hasChildNodes() ) { volume.setProviderVirtualMachineId(attribute.getFirstChild().getNodeValue()); } else if( name.equals("displayname") && attribute.hasChildNodes() ) { description = attribute.getFirstChild().getNodeValue().trim(); } else if( name.equals("size") && attribute.hasChildNodes() ) { long size = (Long.parseLong(attribute.getFirstChild().getNodeValue())/1024000000L); volume.setSize(new Storage<Gigabyte>(size, Storage.GIGABYTE)); } else if( name.equals("state") && attribute.hasChildNodes() ) { String state = attribute.getFirstChild().getNodeValue(); if( state == null ) { volume.setCurrentState(VolumeState.PENDING); } else if( state.equalsIgnoreCase("created") || state.equalsIgnoreCase("ready") || state.equalsIgnoreCase("allocated") || state.equalsIgnoreCase("uploaded")) { volume.setCurrentState(VolumeState.AVAILABLE); } else { logger.warn("DEBUG: Unknown state for CloudStack volume: " + state); volume.setCurrentState(VolumeState.PENDING); } } else if( name.equals("created") && attribute.hasChildNodes() ) { String date = attribute.getFirstChild().getNodeValue(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278 try { volume.setCreationTimestamp(df.parse(date).getTime()); } catch( ParseException e ) { volume.setCreationTimestamp(0L); } } } } if( !root && rootOnly ) { return null; } if( volume.getProviderVolumeId() == null ) { return null; } if( volumeName == null ) { volume.setName(volume.getProviderVolumeId()); } else { volume.setName(volumeName); } if( description == null ) { volume.setDescription(volume.getName()); } else { volume.setDescription(description); } if( offeringId != null ) { volume.setProviderProductId(offeringId); } volume.setProviderRegionId(provider.getContext().getRegionId()); volume.setProviderDataCenterId(provider.getContext().getRegionId()); if( volume.getProviderVirtualMachineId() != null ) { VirtualMachine vm = null; try { vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(volume.getProviderVirtualMachineId()); if( vm == null ) { logger.warn("Could not find Virtual machine " + volume.getProviderVirtualMachineId() + " for root volume " + volume.getProviderVolumeId() + " ."); } else{ volume.setDeviceId(toDeviceID(deviceNumber, vm.getPlatform().isWindows())); } } catch( Exception e ) { if(logger.isDebugEnabled()){ logger.warn("Error trying to determine device id for a volume : " + e.getMessage(),e); } else{ logger.warn("Error trying to determine device id for a volume : " + e.getMessage()); } } } volume.setRootVolume(root); volume.setType(VolumeType.HDD); if( root ) { volume.setGuestOperatingSystem(Platform.guess(volume.getName() + " " + volume.getDescription())); } return volume; } }
true
true
public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.createVolume"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was provided for this request"); } if( options.getFormat().equals(VolumeFormat.NFS) ) { throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName()); } String snapshotId = options.getSnapshotId(); String productId = options.getVolumeProductId(); VolumeProduct product = null; if( productId != null ) { for( VolumeProduct prd : listVolumeProducts() ) { if( productId.equals(prd.getProviderProductId()) ) { product = prd; break; } } } Storage<Gigabyte> size; if( snapshotId == null ) { if( product == null ) { size = options.getVolumeSize(); if( size.intValue() < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } Iterable<VolumeProduct> products = listVolumeProducts(); VolumeProduct best = null; VolumeProduct custom = null; for( VolumeProduct p : products ) { Storage<Gigabyte> s = p.getVolumeSize(); if( s == null || s.intValue() == 0 ) { if (custom == null) { custom = p; } continue; } long currentSize = s.getQuantity().longValue(); s = (best == null ? null : best.getVolumeSize()); long bestSize = (s == null ? 0L : s.getQuantity().longValue()); if( size.longValue() > 0L && size.longValue() == currentSize ) { product = p; break; } if( best == null ) { best = p; } else if( bestSize > 0L || currentSize > 0L ) { if( size.longValue() > 0L ) { if( bestSize < size.longValue() && bestSize >0L && currentSize > size.longValue() ) { best = p; } else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) { best = p; } } else if( currentSize > 0L && currentSize < bestSize ) { best = p; } } } if( product == null ) { if (custom != null) { product = custom; } else { product = best; } } } else { size = product.getVolumeSize(); if( size == null || size.intValue() < 1 ) { size = options.getVolumeSize(); } } if( product == null && size.longValue() < 1L ) { throw new CloudException("No offering matching " + options.getVolumeProductId()); } } else { Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId); if( snapshot == null ) { throw new CloudException("No such snapshot: " + snapshotId); } int s = snapshot.getSizeInGb(); if( s < 1 || s < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } else { size = new Storage<Gigabyte>(s, Storage.GIGABYTE); } } Param[] params; if( product == null && snapshotId == null ) { /*params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("size", String.valueOf(size.longValue())) }; */ throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request"); } else if( snapshotId != null ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("snapshotId", snapshotId), new Param("size", String.valueOf(size.longValue())) }; } else { Storage<Gigabyte> s = product.getVolumeSize(); if( s == null || s.intValue() < 1 ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()), new Param("size", String.valueOf(size.longValue())) }; } else { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()) }; } } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME); NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1 String volumeId = null; if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } if( volumeId == null ) { matches = doc.getElementsByTagName("id"); // v2.2 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { matches = doc.getElementsByTagName("jobid"); // v4.1 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { throw new CloudException("Failed to create volume"); } Document responseDoc = provider.waitForJob(doc, "Create Volume"); if (responseDoc != null){ NodeList nodeList = responseDoc.getElementsByTagName("volume"); if (nodeList.getLength() > 0) { Node volume = nodeList.item(0); NodeList attributes = volume.getChildNodes(); for (int i = 0; i<attributes.getLength(); i++) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if (name.equalsIgnoreCase("id")) { volumeId = value; break; } } } } return volumeId; }
public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Volume.createVolume"); try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new CloudException("No context was provided for this request"); } if( options.getFormat().equals(VolumeFormat.NFS) ) { throw new OperationNotSupportedException("NFS volumes are not currently supported in " + getProvider().getCloudName()); } String snapshotId = options.getSnapshotId(); String productId = options.getVolumeProductId(); VolumeProduct product = null; if( productId != null ) { for( VolumeProduct prd : listVolumeProducts() ) { if( productId.equals(prd.getProviderProductId()) ) { product = prd; break; } } } Storage<Gigabyte> size; if( snapshotId == null ) { if( product == null ) { size = options.getVolumeSize(); if( size.intValue() < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } Iterable<VolumeProduct> products = listVolumeProducts(); VolumeProduct best = null; VolumeProduct custom = null; for( VolumeProduct p : products ) { Storage<Gigabyte> s = p.getVolumeSize(); if( s == null || s.intValue() == 0 ) { if (custom == null) { custom = p; } continue; } long currentSize = s.getQuantity().longValue(); s = (best == null ? null : best.getVolumeSize()); long bestSize = (s == null ? 0L : s.getQuantity().longValue()); if( size.longValue() > 0L && size.longValue() == currentSize ) { product = p; break; } if( best == null ) { best = p; } else if( bestSize > 0L || currentSize > 0L ) { if( size.longValue() > 0L ) { if( bestSize < size.longValue() && bestSize >0L && (currentSize > size.longValue() || currentSize > bestSize) ) { best = p; } else if( bestSize > size.longValue() && currentSize > size.longValue() && currentSize < bestSize ) { best = p; } } else if( currentSize > 0L && currentSize < bestSize ) { best = p; } } } if( product == null ) { if (custom != null) { product = custom; } else { product = best; } } } else { size = product.getVolumeSize(); if( size == null || size.intValue() < 1 ) { size = options.getVolumeSize(); } } if( product == null && size.longValue() < 1L ) { throw new CloudException("No offering matching " + options.getVolumeProductId()); } } else { Snapshot snapshot = provider.getComputeServices().getSnapshotSupport().getSnapshot(snapshotId); if( snapshot == null ) { throw new CloudException("No such snapshot: " + snapshotId); } int s = snapshot.getSizeInGb(); if( s < 1 || s < getMinimumVolumeSize().intValue() ) { size = getMinimumVolumeSize(); } else { size = new Storage<Gigabyte>(s, Storage.GIGABYTE); } } Param[] params; if( product == null && snapshotId == null ) { /*params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("size", String.valueOf(size.longValue())) }; */ throw new CloudException("A suitable snapshot or disk offering could not be found to pass to CloudStack createVolume request"); } else if( snapshotId != null ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("snapshotId", snapshotId), new Param("size", String.valueOf(size.longValue())) }; } else { Storage<Gigabyte> s = product.getVolumeSize(); if( s == null || s.intValue() < 1 ) { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()), new Param("size", String.valueOf(size.longValue())) }; } else { params = new Param[] { new Param("name", options.getName()), new Param("zoneId", ctx.getRegionId()), new Param("diskOfferingId", product.getProviderProductId()) }; } } CSMethod method = new CSMethod(provider); Document doc = method.get(method.buildUrl(CREATE_VOLUME, params), CREATE_VOLUME); NodeList matches = doc.getElementsByTagName("volumeid"); // v2.1 String volumeId = null; if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } if( volumeId == null ) { matches = doc.getElementsByTagName("id"); // v2.2 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { matches = doc.getElementsByTagName("jobid"); // v4.1 if( matches.getLength() > 0 ) { volumeId = matches.item(0).getFirstChild().getNodeValue(); } } if( volumeId == null ) { throw new CloudException("Failed to create volume"); } Document responseDoc = provider.waitForJob(doc, "Create Volume"); if (responseDoc != null){ NodeList nodeList = responseDoc.getElementsByTagName("volume"); if (nodeList.getLength() > 0) { Node volume = nodeList.item(0); NodeList attributes = volume.getChildNodes(); for (int i = 0; i<attributes.getLength(); i++) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if( attribute.getChildNodes().getLength() > 0 ) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if (name.equalsIgnoreCase("id")) { volumeId = value; break; } } } } return volumeId; }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/endpoints/DynamicLoadbalanceEndpoint.java b/java/modules/core/src/main/java/org/apache/synapse/endpoints/DynamicLoadbalanceEndpoint.java index 9e09d9950..f21b8e7c3 100755 --- a/java/modules/core/src/main/java/org/apache/synapse/endpoints/DynamicLoadbalanceEndpoint.java +++ b/java/modules/core/src/main/java/org/apache/synapse/endpoints/DynamicLoadbalanceEndpoint.java @@ -1,173 +1,174 @@ /* * 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.synapse.endpoints; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.clustering.Member; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.FaultHandler; import org.apache.synapse.MessageContext; import org.apache.synapse.SynapseException; import org.apache.synapse.SynapseConstants; import org.apache.synapse.core.LoadBalanceMembershipHandler; import org.apache.synapse.core.SynapseEnvironment; import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.core.axis2.Axis2SynapseEnvironment; import org.apache.synapse.endpoints.algorithms.AlgorithmContext; import java.net.MalformedURLException; import java.net.URL; /** * Represents a dynamic load balance endpoint. The application membership is not static, but discovered * through some mechanism such as using a GCF */ public class DynamicLoadbalanceEndpoint extends LoadbalanceEndpoint { private static final Log log = LogFactory.getLog(DynamicLoadbalanceEndpoint.class); /** * The algorithm context , place holder for keep any runtime states related to the load balance * algorithm */ private AlgorithmContext algorithmContext; @Override public void init(SynapseEnvironment synapseEnvironment) { ConfigurationContext cc = ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext(); if (!initialized) { super.init(synapseEnvironment); if (algorithmContext == null) { algorithmContext = new AlgorithmContext(isClusteringEnabled, cc, getName()); } } log.info("Dynamic load balance endpoint initialized"); } private LoadBalanceMembershipHandler lbMembershipHandler; public DynamicLoadbalanceEndpoint() { } public void setLoadBalanceMembershipHandler(LoadBalanceMembershipHandler lbMembershipHandler) { this.lbMembershipHandler = lbMembershipHandler; } public void send(MessageContext synCtx) { EndpointReference to = synCtx.getTo(); DynamicLoadbalanceFaultHandler faultHandler = new DynamicLoadbalanceFaultHandler(to); if (isFailover()) { synCtx.pushFaultHandler(faultHandler); } ConfigurationContext configCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext(); if (lbMembershipHandler.getConfigurationContext() == null) { lbMembershipHandler.setConfigurationContext(configCtx); } // algorithmContext.setConfigurationContext(configCtx); sendToApplicationMember(synCtx, to, faultHandler); } public void setName(String name) { super.setName(name); // algorithmContext.setContextID(name); } private void sendToApplicationMember(MessageContext synCtx, EndpointReference to, DynamicLoadbalanceFaultHandler faultHandler) { org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); String transport = axis2MsgCtx.getTransportIn().getName(); Member currentMember = lbMembershipHandler.getNextApplicationMember(algorithmContext); faultHandler.setCurrentMember(currentMember); if (currentMember != null) { // URL rewrite if (transport.equals("http") || transport.equals("https")) { String address = to.getAddress(); if (address.indexOf(":") != -1) { try { address = new URL(address).getPath(); } catch (MalformedURLException e) { String msg = "URL " + address + " is malformed"; log.error(msg, e); throw new SynapseException(msg, e); } } EndpointReference epr = new EndpointReference(transport + "://" + currentMember.getHostName() + ":" + currentMember.getHttpPort() + address); synCtx.setTo(epr); if (isFailover()) { synCtx.getEnvelope().build(); } AddressEndpoint endpoint = new AddressEndpoint(); - endpoint.setName("DynamicLoadBalanceAddressEndpoint"); + endpoint.setName("DynamicLoadBalanceAddressEndpoint-" + Math.random()); EndpointDefinition definition = new EndpointDefinition(); + definition.setAddress(epr.getAddress()); endpoint.setDefinition(definition); endpoint.init((SynapseEnvironment) ((Axis2MessageContext) synCtx).getAxis2MessageContext(). getConfigurationContext().getAxisConfiguration(). getParameterValue(SynapseConstants.SYNAPSE_ENV)); endpoint.send(synCtx); } else { log.error("Cannot load balance for non-HTTP/S transport " + transport); } } else { synCtx.getFaultStack().pop(); // Remove the DynamicLoadbalanceFaultHandler String msg = "No application members available"; log.error(msg); throw new SynapseException(msg); } } /** * This FaultHandler will try to resend the message to another member if an error occurs * while sending to some member. This is a failover mechanism */ private class DynamicLoadbalanceFaultHandler extends FaultHandler { private EndpointReference to; private Member currentMember; public void setCurrentMember(Member currentMember) { this.currentMember = currentMember; } private DynamicLoadbalanceFaultHandler(EndpointReference to) { this.to = to; } public void onFault(MessageContext synCtx) { if (currentMember == null) { return; } synCtx.pushFaultHandler(this); sendToApplicationMember(synCtx, to, this); } } }
false
true
private void sendToApplicationMember(MessageContext synCtx, EndpointReference to, DynamicLoadbalanceFaultHandler faultHandler) { org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); String transport = axis2MsgCtx.getTransportIn().getName(); Member currentMember = lbMembershipHandler.getNextApplicationMember(algorithmContext); faultHandler.setCurrentMember(currentMember); if (currentMember != null) { // URL rewrite if (transport.equals("http") || transport.equals("https")) { String address = to.getAddress(); if (address.indexOf(":") != -1) { try { address = new URL(address).getPath(); } catch (MalformedURLException e) { String msg = "URL " + address + " is malformed"; log.error(msg, e); throw new SynapseException(msg, e); } } EndpointReference epr = new EndpointReference(transport + "://" + currentMember.getHostName() + ":" + currentMember.getHttpPort() + address); synCtx.setTo(epr); if (isFailover()) { synCtx.getEnvelope().build(); } AddressEndpoint endpoint = new AddressEndpoint(); endpoint.setName("DynamicLoadBalanceAddressEndpoint"); EndpointDefinition definition = new EndpointDefinition(); endpoint.setDefinition(definition); endpoint.init((SynapseEnvironment) ((Axis2MessageContext) synCtx).getAxis2MessageContext(). getConfigurationContext().getAxisConfiguration(). getParameterValue(SynapseConstants.SYNAPSE_ENV)); endpoint.send(synCtx); } else { log.error("Cannot load balance for non-HTTP/S transport " + transport); } } else { synCtx.getFaultStack().pop(); // Remove the DynamicLoadbalanceFaultHandler String msg = "No application members available"; log.error(msg); throw new SynapseException(msg); } }
private void sendToApplicationMember(MessageContext synCtx, EndpointReference to, DynamicLoadbalanceFaultHandler faultHandler) { org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); String transport = axis2MsgCtx.getTransportIn().getName(); Member currentMember = lbMembershipHandler.getNextApplicationMember(algorithmContext); faultHandler.setCurrentMember(currentMember); if (currentMember != null) { // URL rewrite if (transport.equals("http") || transport.equals("https")) { String address = to.getAddress(); if (address.indexOf(":") != -1) { try { address = new URL(address).getPath(); } catch (MalformedURLException e) { String msg = "URL " + address + " is malformed"; log.error(msg, e); throw new SynapseException(msg, e); } } EndpointReference epr = new EndpointReference(transport + "://" + currentMember.getHostName() + ":" + currentMember.getHttpPort() + address); synCtx.setTo(epr); if (isFailover()) { synCtx.getEnvelope().build(); } AddressEndpoint endpoint = new AddressEndpoint(); endpoint.setName("DynamicLoadBalanceAddressEndpoint-" + Math.random()); EndpointDefinition definition = new EndpointDefinition(); definition.setAddress(epr.getAddress()); endpoint.setDefinition(definition); endpoint.init((SynapseEnvironment) ((Axis2MessageContext) synCtx).getAxis2MessageContext(). getConfigurationContext().getAxisConfiguration(). getParameterValue(SynapseConstants.SYNAPSE_ENV)); endpoint.send(synCtx); } else { log.error("Cannot load balance for non-HTTP/S transport " + transport); } } else { synCtx.getFaultStack().pop(); // Remove the DynamicLoadbalanceFaultHandler String msg = "No application members available"; log.error(msg); throw new SynapseException(msg); } }
diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java index 29b93f85..b112cb1e 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java @@ -1,389 +1,389 @@ /******************************************************************************* * Copyright 2012 The MITRE Corporation * * 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.mitre.openid.connect.model; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import com.google.gson.JsonObject; @Entity @Table(name="user_info") @NamedQueries({ @NamedQuery(name="DefaultUserInfo.getAll", query = "select u from DefaultUserInfo u"), @NamedQuery(name="DefaultUserInfo.getByUsername", query = "select u from DefaultUserInfo u WHERE u.preferredUsername = :username") }) public class DefaultUserInfo implements UserInfo { private String userId; private String preferredUsername; private String name; private String givenName; private String familyName; private String middleName; private String nickname; private String profile; private String picture; private String website; private String email; private boolean emailVerified; private String gender; private String zoneinfo; private String locale; private String phoneNumber; private Address address; private String updatedTime; /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getUserId() */ @Override @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="user_id") public String getUserId() { return userId; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setUserId(java.lang.String) */ @Override public void setUserId(String userId) { this.userId = userId; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getPreferredUsername */ @Override @Basic @Column(name="preferred_username") public String getPreferredUsername() { return this.preferredUsername; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setPreferredUsername(java.lang.String) */ @Override public void setPreferredUsername(String preferredUsername) { this.preferredUsername = preferredUsername; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getName() */ @Override @Basic public String getName() { return name; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setName(java.lang.String) */ @Override public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getGivenName() */ @Override @Basic @Column(name="given_name") public String getGivenName() { return givenName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setGivenName(java.lang.String) */ @Override public void setGivenName(String givenName) { this.givenName = givenName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getFamilyName() */ @Override @Basic @Column(name="family_name") public String getFamilyName() { return familyName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setFamilyName(java.lang.String) */ @Override public void setFamilyName(String familyName) { this.familyName = familyName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getMiddleName() */ @Override @Basic @Column(name="middle_name") public String getMiddleName() { return middleName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setMiddleName(java.lang.String) */ @Override public void setMiddleName(String middleName) { this.middleName = middleName; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getNickname() */ @Override @Basic public String getNickname() { return nickname; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setNickname(java.lang.String) */ @Override public void setNickname(String nickname) { this.nickname = nickname; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getProfile() */ @Override @Basic public String getProfile() { return profile; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setProfile(java.lang.String) */ @Override public void setProfile(String profile) { this.profile = profile; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getPicture() */ @Override @Basic public String getPicture() { return picture; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setPicture(java.lang.String) */ @Override public void setPicture(String picture) { this.picture = picture; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getWebsite() */ @Override @Basic public String getWebsite() { return website; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setWebsite(java.lang.String) */ @Override public void setWebsite(String website) { this.website = website; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getEmail() */ @Override @Basic public String getEmail() { return email; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setEmail(java.lang.String) */ @Override public void setEmail(String email) { this.email = email; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getVerified() */ @Override @Basic @Column(name="email_verified") public boolean getEmailVerified() { return emailVerified; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setVerified(java.lang.boolean) */ @Override public void setEmailVerified(boolean emailVerified) { this.emailVerified = emailVerified; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getGender() */ @Override @Basic public String getGender() { return gender; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setGender(java.lang.String) */ @Override public void setGender(String gender) { this.gender = gender; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getZoneinfo() */ @Override @Basic @Column(name="zone_info") public String getZoneinfo() { return zoneinfo; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setZoneinfo(java.lang.String) */ @Override public void setZoneinfo(String zoneinfo) { this.zoneinfo = zoneinfo; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getLocale() */ @Override @Basic public String getLocale() { return locale; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setLocale(java.lang.String) */ @Override public void setLocale(String locale) { this.locale = locale; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getPhoneNumber() */ @Override @Basic @Column(name="phone_number") public String getPhoneNumber() { return phoneNumber; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setPhoneNumber(java.lang.String) */ @Override public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getAddress() */ @Override @OneToOne @JoinColumn(name="address_id") public Address getAddress() { return address; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setAddress(org.mitre.openid.connect.model.Address) */ @Override public void setAddress(Address address) { this.address = address; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#getUpdatedTime() */ @Override @Basic @Column(name="updated_time") public String getUpdatedTime() { return updatedTime; } /* (non-Javadoc) * @see org.mitre.openid.connect.model.UserInfo#setUpdatedTime(java.lang.String) */ @Override public void setUpdatedTime(String updatedTime) { this.updatedTime = updatedTime; } /** * Parse a JsonObject into a UserInfo. * @param o * @return */ public static UserInfo fromJson(JsonObject obj) { DefaultUserInfo ui = new DefaultUserInfo(); ui.setUserId(obj.has("user_id") ? obj.get("user_id").getAsString() : null); ui.setName(obj.has("name") ? obj.get("name").getAsString() : null); ui.setPreferredUsername(obj.has("preferred_username") ? obj.get("preferred_username").getAsString() : null); ui.setGivenName(obj.has("given_name") ? obj.get("given_name").getAsString() : null); ui.setFamilyName(obj.has("family_name") ? obj.get("family_name").getAsString() : null); ui.setMiddleName(obj.has("middle_name") ? obj.get("middle_name").getAsString() : null); ui.setNickname(obj.has("nickname") ? obj.get("nickname").getAsString() : null); ui.setProfile(obj.has("profile") ? obj.get("profile").getAsString() : null); ui.setPicture(obj.has("picture") ? obj.get("picture").getAsString() : null); ui.setWebsite(obj.has("website") ? obj.get("website").getAsString() : null); ui.setGender(obj.has("gender") ? obj.get("gender").getAsString() : null); ui.setZoneinfo(obj.has("zone_info") ? obj.get("zone_info").getAsString() : null); ui.setLocale(obj.has("locale") ? obj.get("locale").getAsString() : null); ui.setUpdatedTime(obj.has("updated_time") ? obj.get("updated_time").getAsString() : null); ui.setEmail(obj.has("email") ? obj.get("email").getAsString() : null); - ui.setEmailVerified(obj.has("email") ? obj.get("email_verified").getAsBoolean() : null); + ui.setEmailVerified(obj.has("email_verified") ? obj.get("email_verified").getAsBoolean() : null); ui.setPhoneNumber(obj.has("phone_number") ? obj.get("phone_number").getAsString() : null); if (obj.has("address") && obj.get("address").isJsonObject()) { JsonObject addr = obj.get("address").getAsJsonObject(); ui.setAddress(new Address()); ui.getAddress().setFormatted(addr.has("formatted") ? addr.get("formatted").getAsString() : null); ui.getAddress().setStreetAddress(addr.has("street_address") ? addr.get("street_address").getAsString() : null); ui.getAddress().setLocality(addr.has("locality") ? addr.get("locality").getAsString() : null); ui.getAddress().setRegion(addr.has("region") ? addr.get("region").getAsString() : null); ui.getAddress().setPostalCode(addr.has("postal_code") ? addr.get("postal_code").getAsString() : null); ui.getAddress().setCountry(addr.has("country") ? addr.get("country").getAsString() : null); } return ui; } }
true
true
public static UserInfo fromJson(JsonObject obj) { DefaultUserInfo ui = new DefaultUserInfo(); ui.setUserId(obj.has("user_id") ? obj.get("user_id").getAsString() : null); ui.setName(obj.has("name") ? obj.get("name").getAsString() : null); ui.setPreferredUsername(obj.has("preferred_username") ? obj.get("preferred_username").getAsString() : null); ui.setGivenName(obj.has("given_name") ? obj.get("given_name").getAsString() : null); ui.setFamilyName(obj.has("family_name") ? obj.get("family_name").getAsString() : null); ui.setMiddleName(obj.has("middle_name") ? obj.get("middle_name").getAsString() : null); ui.setNickname(obj.has("nickname") ? obj.get("nickname").getAsString() : null); ui.setProfile(obj.has("profile") ? obj.get("profile").getAsString() : null); ui.setPicture(obj.has("picture") ? obj.get("picture").getAsString() : null); ui.setWebsite(obj.has("website") ? obj.get("website").getAsString() : null); ui.setGender(obj.has("gender") ? obj.get("gender").getAsString() : null); ui.setZoneinfo(obj.has("zone_info") ? obj.get("zone_info").getAsString() : null); ui.setLocale(obj.has("locale") ? obj.get("locale").getAsString() : null); ui.setUpdatedTime(obj.has("updated_time") ? obj.get("updated_time").getAsString() : null); ui.setEmail(obj.has("email") ? obj.get("email").getAsString() : null); ui.setEmailVerified(obj.has("email") ? obj.get("email_verified").getAsBoolean() : null); ui.setPhoneNumber(obj.has("phone_number") ? obj.get("phone_number").getAsString() : null); if (obj.has("address") && obj.get("address").isJsonObject()) { JsonObject addr = obj.get("address").getAsJsonObject(); ui.setAddress(new Address()); ui.getAddress().setFormatted(addr.has("formatted") ? addr.get("formatted").getAsString() : null); ui.getAddress().setStreetAddress(addr.has("street_address") ? addr.get("street_address").getAsString() : null); ui.getAddress().setLocality(addr.has("locality") ? addr.get("locality").getAsString() : null); ui.getAddress().setRegion(addr.has("region") ? addr.get("region").getAsString() : null); ui.getAddress().setPostalCode(addr.has("postal_code") ? addr.get("postal_code").getAsString() : null); ui.getAddress().setCountry(addr.has("country") ? addr.get("country").getAsString() : null); } return ui; }
public static UserInfo fromJson(JsonObject obj) { DefaultUserInfo ui = new DefaultUserInfo(); ui.setUserId(obj.has("user_id") ? obj.get("user_id").getAsString() : null); ui.setName(obj.has("name") ? obj.get("name").getAsString() : null); ui.setPreferredUsername(obj.has("preferred_username") ? obj.get("preferred_username").getAsString() : null); ui.setGivenName(obj.has("given_name") ? obj.get("given_name").getAsString() : null); ui.setFamilyName(obj.has("family_name") ? obj.get("family_name").getAsString() : null); ui.setMiddleName(obj.has("middle_name") ? obj.get("middle_name").getAsString() : null); ui.setNickname(obj.has("nickname") ? obj.get("nickname").getAsString() : null); ui.setProfile(obj.has("profile") ? obj.get("profile").getAsString() : null); ui.setPicture(obj.has("picture") ? obj.get("picture").getAsString() : null); ui.setWebsite(obj.has("website") ? obj.get("website").getAsString() : null); ui.setGender(obj.has("gender") ? obj.get("gender").getAsString() : null); ui.setZoneinfo(obj.has("zone_info") ? obj.get("zone_info").getAsString() : null); ui.setLocale(obj.has("locale") ? obj.get("locale").getAsString() : null); ui.setUpdatedTime(obj.has("updated_time") ? obj.get("updated_time").getAsString() : null); ui.setEmail(obj.has("email") ? obj.get("email").getAsString() : null); ui.setEmailVerified(obj.has("email_verified") ? obj.get("email_verified").getAsBoolean() : null); ui.setPhoneNumber(obj.has("phone_number") ? obj.get("phone_number").getAsString() : null); if (obj.has("address") && obj.get("address").isJsonObject()) { JsonObject addr = obj.get("address").getAsJsonObject(); ui.setAddress(new Address()); ui.getAddress().setFormatted(addr.has("formatted") ? addr.get("formatted").getAsString() : null); ui.getAddress().setStreetAddress(addr.has("street_address") ? addr.get("street_address").getAsString() : null); ui.getAddress().setLocality(addr.has("locality") ? addr.get("locality").getAsString() : null); ui.getAddress().setRegion(addr.has("region") ? addr.get("region").getAsString() : null); ui.getAddress().setPostalCode(addr.has("postal_code") ? addr.get("postal_code").getAsString() : null); ui.getAddress().setCountry(addr.has("country") ? addr.get("country").getAsString() : null); } return ui; }
diff --git a/src/me/reddy360/theholyflint/command/CommandSetTP.java b/src/me/reddy360/theholyflint/command/CommandSetTP.java index fdfb8db..5889f6c 100644 --- a/src/me/reddy360/theholyflint/command/CommandSetTP.java +++ b/src/me/reddy360/theholyflint/command/CommandSetTP.java @@ -1,38 +1,38 @@ package me.reddy360.theholyflint.command; import me.reddy360.theholyflint.PluginMain; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CommandSetTP implements CommandExecutor { PluginMain pluginMain; public CommandSetTP(PluginMain pluginMain) { this.pluginMain = pluginMain; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.settp"))){ sender.sendMessage(ChatColor.DARK_RED + "THERE ALL DEAD!"); return true; }else if(!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_RED + "No player, no coords, no service."); return true; }else if(args.length == 1){ Player player = (Player) sender; - pluginMain.getConfig().set("coords." + args[0], player.getLocation().getWorld() + ":" + player.getLocation().getBlockX() + pluginMain.getConfig().set("coords." + args[0], player.getLocation().getWorld().getName() + ":" + player.getLocation().getBlockX() + ":" + player.getLocation().getBlockY() + ":" + player.getLocation().getBlockZ()); pluginMain.saveConfig(); player.sendMessage(ChatColor.GREEN + "TP Sign Coord set at" + pluginMain.getConfig().getString("coords." + args[0])); return true; } sender.sendMessage(ChatColor.DARK_RED + "Invalid Syntax. /settp [name]"); return true; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.settp"))){ sender.sendMessage(ChatColor.DARK_RED + "THERE ALL DEAD!"); return true; }else if(!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_RED + "No player, no coords, no service."); return true; }else if(args.length == 1){ Player player = (Player) sender; pluginMain.getConfig().set("coords." + args[0], player.getLocation().getWorld() + ":" + player.getLocation().getBlockX() + ":" + player.getLocation().getBlockY() + ":" + player.getLocation().getBlockZ()); pluginMain.saveConfig(); player.sendMessage(ChatColor.GREEN + "TP Sign Coord set at" + pluginMain.getConfig().getString("coords." + args[0])); return true; } sender.sendMessage(ChatColor.DARK_RED + "Invalid Syntax. /settp [name]"); return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.settp"))){ sender.sendMessage(ChatColor.DARK_RED + "THERE ALL DEAD!"); return true; }else if(!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_RED + "No player, no coords, no service."); return true; }else if(args.length == 1){ Player player = (Player) sender; pluginMain.getConfig().set("coords." + args[0], player.getLocation().getWorld().getName() + ":" + player.getLocation().getBlockX() + ":" + player.getLocation().getBlockY() + ":" + player.getLocation().getBlockZ()); pluginMain.saveConfig(); player.sendMessage(ChatColor.GREEN + "TP Sign Coord set at" + pluginMain.getConfig().getString("coords." + args[0])); return true; } sender.sendMessage(ChatColor.DARK_RED + "Invalid Syntax. /settp [name]"); return true; }
diff --git a/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java b/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java index f0dbe2de..f2a84f04 100644 --- a/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java +++ b/stripes/src/net/sourceforge/stripes/tag/MessagesTag.java @@ -1,156 +1,156 @@ /* Copyright (C) 2005 Tim Fennell * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the license with this software. If not, * it can be found online at http://www.fsf.org/licensing/licenses/lgpl.html */ package net.sourceforge.stripes.tag; import net.sourceforge.stripes.action.Message; import net.sourceforge.stripes.controller.StripesConstants; import net.sourceforge.stripes.controller.StripesFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import java.io.IOException; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * <p>Displays a list of non-error messages to the user. The list of messages can come from * either the request (preferred) or the session (checked 2nd). Lists of messages can be stored * under any arbitrary key in request or session and the key can be specified to the messages * tag. If no key is specified then the default key (and therefore default set of messages) is * used. Note that by default the ActionBeanContext stores messages in a * {@link net.sourceforge.stripes.controller.FlashScope} which causes them to be exposed as * request attributes in both the current and subsequent request (assuming a redirect is used).</p> * * <p>While similar in concept to the ErrorsTag, the MessagesTag is significantly simpler. It deals * with a List of Message objects, and does not understand any association between messages and * form fields, or even between messages and forms. It is designed to be used to show arbitrary * messages to the user, the prime example being a confirmation message displayed on the subsequent * page following an action.</p> * * <p>The messages tag outputs a header before the messages, the messages themselves, and a footer * after the messages. Default values are set for each of these four items. Different values * can be specified in the error messages resource bundle (StripesResources.properties unless you * have configured another). The default configuration would look like this: * * <ul> * <li>stripes.messages.header={@literal <ul class="messages">}</li> * <li>stripes.messages.footer={@literal </ul>}</li> * <li>stripes.messages.beforeMessage={@literal <li>}</li> * <li>stripes.messages.afterMessage={@literal </li>}</li> * </ul> * * <p>It should also be noted that while the errors tag supports custom headers and footers * through the use of nested tags, the messages tag does not support this. In fact the * messages tag does not support body content at all - it will simply be ignored.</p> * * @author Tim Fennell * @since Stripes 1.1.2 */ public class MessagesTag extends HtmlTagSupport { /** The header that will be emitted if no header is defined in the resource bundle. */ public static final String DEFAULT_HEADER = "<ul class=\"messages\">"; /** The footer that will be emitted if no footer is defined in the resource bundle. */ public static final String DEFAULT_FOOTER = "</ul>"; /** The key that will be used to perform a scope search for messages. */ private String key = StripesConstants.REQ_ATTR_MESSAGES; /** * Does nothing, all processing is performed in doEndTag(). * @return SKIP_BODY in all cases. */ public int doStartTag() throws JspException { return SKIP_BODY; } /** * Outputs the set of messages approprate for this tag. * @return EVAL_PAGE always */ public int doEndTag() throws JspException { try { List<Message> messages = getMessages(); if (messages != null && messages.size() > 0) { JspWriter writer = getPageContext().getOut(); // Output all errors in a standard format Locale locale = getPageContext().getRequest().getLocale(); ResourceBundle bundle = StripesFilter.getConfiguration() .getLocalizationBundleFactory().getErrorMessageBundle(locale); // Fetch the header and footer String header, footer, beforeMessage, afterMessage; try { header = bundle.getString("stripes.messages.header"); } catch (MissingResourceException mre) { header = DEFAULT_HEADER; } try { footer = bundle.getString("stripes.messages.footer"); } catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; } try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); } catch (MissingResourceException mre) { beforeMessage = "<li>"; } - try { afterMessage = bundle.getString("stripes.errors.afterMessage"); } + try { afterMessage = bundle.getString("stripes.messages.afterMessage"); } catch (MissingResourceException mre) { afterMessage = "</li>"; } // Write out the error messages writer.write(header); for (Message message : messages) { writer.write(beforeMessage); writer.write(message.getMessage(locale)); writer.write(afterMessage); } writer.write(footer); } return EVAL_PAGE; } catch (IOException e) { throw new JspException("IOException encountered while writing messages " + "tag to the JspWriter.", e); } } /** Gets the key that will be used to scope search for messages to display. */ public String getKey() { return key; } /** Sets the key that will be used to scope search for messages to display. */ public void setKey(String key) { this.key = key; } /** * Gets the list of messages that will be displayed by the tag. Looks first in the request * under the specified key, and if none are found, then looks in session under the same key. * * @return List<Message> a possibly null list of messages to display */ protected List<Message> getMessages() { HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest(); List<Message> messages = (List<Message>) request.getAttribute( getKey() ); if (messages == null) { messages = (List<Message>) request.getSession().getAttribute( getKey() ); request.getSession().removeAttribute( getKey() ); } return messages; } }
true
true
public int doEndTag() throws JspException { try { List<Message> messages = getMessages(); if (messages != null && messages.size() > 0) { JspWriter writer = getPageContext().getOut(); // Output all errors in a standard format Locale locale = getPageContext().getRequest().getLocale(); ResourceBundle bundle = StripesFilter.getConfiguration() .getLocalizationBundleFactory().getErrorMessageBundle(locale); // Fetch the header and footer String header, footer, beforeMessage, afterMessage; try { header = bundle.getString("stripes.messages.header"); } catch (MissingResourceException mre) { header = DEFAULT_HEADER; } try { footer = bundle.getString("stripes.messages.footer"); } catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; } try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); } catch (MissingResourceException mre) { beforeMessage = "<li>"; } try { afterMessage = bundle.getString("stripes.errors.afterMessage"); } catch (MissingResourceException mre) { afterMessage = "</li>"; } // Write out the error messages writer.write(header); for (Message message : messages) { writer.write(beforeMessage); writer.write(message.getMessage(locale)); writer.write(afterMessage); } writer.write(footer); } return EVAL_PAGE; } catch (IOException e) { throw new JspException("IOException encountered while writing messages " + "tag to the JspWriter.", e); } }
public int doEndTag() throws JspException { try { List<Message> messages = getMessages(); if (messages != null && messages.size() > 0) { JspWriter writer = getPageContext().getOut(); // Output all errors in a standard format Locale locale = getPageContext().getRequest().getLocale(); ResourceBundle bundle = StripesFilter.getConfiguration() .getLocalizationBundleFactory().getErrorMessageBundle(locale); // Fetch the header and footer String header, footer, beforeMessage, afterMessage; try { header = bundle.getString("stripes.messages.header"); } catch (MissingResourceException mre) { header = DEFAULT_HEADER; } try { footer = bundle.getString("stripes.messages.footer"); } catch (MissingResourceException mre) { footer = DEFAULT_FOOTER; } try { beforeMessage = bundle.getString("stripes.messages.beforeMessage"); } catch (MissingResourceException mre) { beforeMessage = "<li>"; } try { afterMessage = bundle.getString("stripes.messages.afterMessage"); } catch (MissingResourceException mre) { afterMessage = "</li>"; } // Write out the error messages writer.write(header); for (Message message : messages) { writer.write(beforeMessage); writer.write(message.getMessage(locale)); writer.write(afterMessage); } writer.write(footer); } return EVAL_PAGE; } catch (IOException e) { throw new JspException("IOException encountered while writing messages " + "tag to the JspWriter.", e); } }
diff --git a/org.eclipselabs.collage/src/org/eclipselabs/collage/CollageActivator.java b/org.eclipselabs.collage/src/org/eclipselabs/collage/CollageActivator.java index a5751e9..a73aadd 100644 --- a/org.eclipselabs.collage/src/org/eclipselabs/collage/CollageActivator.java +++ b/org.eclipselabs.collage/src/org/eclipselabs/collage/CollageActivator.java @@ -1,319 +1,321 @@ /******************************************************************************* * Copyright (c) 2011, 2012 Alex Bradley. * 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: * Alex Bradley - initial implementation *******************************************************************************/ package org.eclipselabs.collage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchListener; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.eclipselabs.collage.actions.FilesystemSchedulingRule; import org.eclipselabs.collage.model.CollageRoot; import org.eclipselabs.collage.util.CollageFontRegistry; import org.eclipselabs.collage.util.CollageUtilities; import org.osgi.framework.BundleContext; /** * Singleton activator for Collage plugin. Provides SWT image, colour and font registries * that are used throughout the Collage plugin and are also available for use in extensions. * Handles deserialization and serialization of Collage data on plugin load and unload. * @author Alex Bradley */ public final class CollageActivator extends AbstractUIPlugin implements IWorkbenchListener { private enum CollageStorageState { UNAVAILABLE, BLANK, HAS_DATA }; // The plug-in ID public static final String PLUGIN_ID = "org.eclipselabs.collage"; //$NON-NLS-1$ public static final String PLUGIN_NAME = "Collage"; // Persistent storage file public static final String COLLAGE_STORAGE_FILE = "collage-storage.xml.gz"; // Save error messages private static final String SAVE_FAILURE_STOP_SHUTDOWN_QUESTION = "Saving Collage data to %s was unsuccessful because %s. Would you like to stop the Eclipse shutdown and try to fix the problem?"; private static final String SAVE_FAILURE_FORCED_SHUTDOWN_ERROR = "Saving Collage data to %s was unsuccessful because %s. As this is a forced shutdown, Collage data may be lost."; // Icons public static final String UNKNOWN_SHAPE_ICON = "icons/unknown_shape.gif"; public static final String IBEAM_ICON = "icons/ibeam.png"; public static final String IMPORT_ICON = "icons/import.gif"; public static final String EXPORT_ICON = "icons/export.gif"; public static final String LAYERS_VIEW_ICON = "icons/layersview.png"; public static final String LAYER_VISIBLE_ICON = "icons/layer-visible.png"; public static final String LAYER_NEW_ICON = "icons/new_layer.gif"; // The shared instance private static CollageActivator plugin; private CollageRoot defaultCollageRoot = new CollageRoot(); private ColorRegistry colorRegistry; private CollageFontRegistry fontRegistry; @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; PlatformUI.getWorkbench().addWorkbenchListener(this); colorRegistry = new ColorRegistry(); fontRegistry = new CollageFontRegistry(); loadDefaultCollageRoot(); } @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared plugin instance * @return the shared instance */ public static CollageActivator getDefault() { return plugin; } /** * Get the Collage root model element (which is loaded from storage when the plugin starts and * saved when the plugin stops.) * @return Collage model root */ public CollageRoot getDefaultCollageRoot() { return defaultCollageRoot; } /** * Get font registry. * @return Common font registry for this plugin. */ public CollageFontRegistry getFontRegistry () { return fontRegistry; } /** * Get colour registry. * @return Common colour registry for this plugin. */ public ColorRegistry getColorRegistry () { return colorRegistry; } /** * Returns an image descriptor for the image file at the given * plug-in relative path * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } /** * Return an {@link Image} for the image file at the given path in this plugin. * @param path image path * @return {@link Image} at the given path. */ public static Image getImage (String path) { return getImage(PLUGIN_ID, path); } /** * Return an {@link Image} for the image file at the given path in the given plugin. * @param plugin a plugin ID * @param path image path * @return {@link Image} at the given path in the given plugin */ public static Image getImage (String plugin, String path) { ImageRegistry imageReg = getDefault().getImageRegistry(); String key = plugin + ":" + path; Image image = imageReg.get(key); if (image == null) { imageReg.put(key, imageDescriptorFromPlugin(plugin, path)); image = imageReg.get(key); } return image; } /** * Return an {@link Image} for the given {@link ImageDescriptor}. * @param descriptor an image descriptor * @return image for the given descriptor */ public static Image getImage (ImageDescriptor descriptor) { ImageRegistry imageReg = getDefault().getImageRegistry(); String key = "DESC:" + descriptor.hashCode(); Image image = imageReg.get(key); if (image == null) { imageReg.put(key, descriptor); image = imageReg.get(key); } return image; } @Override public boolean preShutdown(IWorkbench workbench, boolean forced) { final File saveFile = getStateLocation().append(COLLAGE_STORAGE_FILE).toFile(); String path = saveFile.getAbsolutePath(); if (collageStorageAvailable() == CollageStorageState.UNAVAILABLE) { return shouldShutdownProceed(path, "the file was not accessible", forced); } else { try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { IJobManager manager = Job.getJobManager(); ISchedulingRule rule = new FilesystemSchedulingRule(saveFile); try { manager.beginRule(rule, monitor); GZIPOutputStream gzOutputStream = new GZIPOutputStream(new FileOutputStream(saveFile)); try { defaultCollageRoot.saveTo(gzOutputStream); } finally { gzOutputStream.close(); } } catch (Exception e) { throw new InvocationTargetException(e); } finally { manager.endRule(rule); } } }); } catch (InvocationTargetException e) { e.printStackTrace(); return shouldShutdownProceed(path, "XML serialization failed", forced); } catch (InterruptedException e) { return shouldShutdownProceed(path, "the save operation was interrupted", forced); } } return true; } @Override public void postShutdown(IWorkbench workbench) { } private void loadDefaultCollageRoot() { switch (collageStorageAvailable()) { case UNAVAILABLE: showStorageUnavailableError(); break; - // if BLANK, no action needed + case BLANK: + // No action needed + break; case HAS_DATA: File loadFile = getStateLocation().append(COLLAGE_STORAGE_FILE).toFile(); try { IJobManager manager = Job.getJobManager(); ISchedulingRule rule = new FilesystemSchedulingRule(loadFile); try { manager.beginRule(rule, new NullProgressMonitor()); GZIPInputStream inputStream = new GZIPInputStream(new FileInputStream(loadFile)); try { defaultCollageRoot = CollageRoot.loadFrom(inputStream); } finally { inputStream.close(); } } finally { manager.endRule(rule); } List<String> warnings = defaultCollageRoot.getDependencyWarnings(); if (!warnings.isEmpty()) { CollageUtilities.showWarning(PLUGIN_NAME, String.format("Collage stored data loaded with the following warning%s:%n%s", (warnings.size() == 1) ? "" : "s", CollageUtilities.join(warnings, "\n"))); } } catch (Exception e) { File backupTarget = getStateLocation().append(getBackupFileName()).toFile(); try { CollageUtilities.fileCopy(loadFile, backupTarget); CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nCollage storage has been backed up to \"%s\".", e.getMessage(), backupTarget.getAbsolutePath())); } catch (Exception e1) { CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nWARNING: An attempt to back up Collage storage to \"%s\" failed!%nIf you want to recover your data, copy it from \"%s\" before closing Eclipse.", e.getMessage(), backupTarget.getAbsolutePath(), loadFile.getAbsolutePath())); } } break; } } /** * In the event of an error during save, ask the user if shutdown should be stopped. * @param path Path to Collage data location where save failed. * @param failureCause Cause of failure. * @param forced Is this a forced shutdown? * @return True if shutdown should proceed, false otherwise. */ private static boolean shouldShutdownProceed (String path, String failureCause, boolean forced) { if (forced) { MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), PLUGIN_NAME, String.format(SAVE_FAILURE_FORCED_SHUTDOWN_ERROR, path, failureCause)); return true; } else { return !MessageDialog.openQuestion(PlatformUI.getWorkbench().getDisplay().getActiveShell(), PLUGIN_NAME, String.format(SAVE_FAILURE_STOP_SHUTDOWN_QUESTION, path, failureCause)); } } private CollageStorageState collageStorageAvailable () { try { File collageFile = getStateLocation().append(COLLAGE_STORAGE_FILE).toFile(); CollageStorageState existsValue = CollageStorageState.HAS_DATA; if (!collageFile.exists()) { collageFile.createNewFile(); existsValue = CollageStorageState.BLANK; } if (collageFile.canRead() && collageFile.canWrite()) { return existsValue; } } catch (IOException e) { // fall through and return unavailable } return CollageStorageState.UNAVAILABLE; } private static void showStorageUnavailableError () { CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to access Collage storage in workspace path %s. Collage data will not be stored.", COLLAGE_STORAGE_FILE)); } private static String getBackupFileName () { return "collage-backup-" + System.currentTimeMillis() + ".xml.gz"; } }
true
true
private void loadDefaultCollageRoot() { switch (collageStorageAvailable()) { case UNAVAILABLE: showStorageUnavailableError(); break; // if BLANK, no action needed case HAS_DATA: File loadFile = getStateLocation().append(COLLAGE_STORAGE_FILE).toFile(); try { IJobManager manager = Job.getJobManager(); ISchedulingRule rule = new FilesystemSchedulingRule(loadFile); try { manager.beginRule(rule, new NullProgressMonitor()); GZIPInputStream inputStream = new GZIPInputStream(new FileInputStream(loadFile)); try { defaultCollageRoot = CollageRoot.loadFrom(inputStream); } finally { inputStream.close(); } } finally { manager.endRule(rule); } List<String> warnings = defaultCollageRoot.getDependencyWarnings(); if (!warnings.isEmpty()) { CollageUtilities.showWarning(PLUGIN_NAME, String.format("Collage stored data loaded with the following warning%s:%n%s", (warnings.size() == 1) ? "" : "s", CollageUtilities.join(warnings, "\n"))); } } catch (Exception e) { File backupTarget = getStateLocation().append(getBackupFileName()).toFile(); try { CollageUtilities.fileCopy(loadFile, backupTarget); CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nCollage storage has been backed up to \"%s\".", e.getMessage(), backupTarget.getAbsolutePath())); } catch (Exception e1) { CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nWARNING: An attempt to back up Collage storage to \"%s\" failed!%nIf you want to recover your data, copy it from \"%s\" before closing Eclipse.", e.getMessage(), backupTarget.getAbsolutePath(), loadFile.getAbsolutePath())); } } break; } }
private void loadDefaultCollageRoot() { switch (collageStorageAvailable()) { case UNAVAILABLE: showStorageUnavailableError(); break; case BLANK: // No action needed break; case HAS_DATA: File loadFile = getStateLocation().append(COLLAGE_STORAGE_FILE).toFile(); try { IJobManager manager = Job.getJobManager(); ISchedulingRule rule = new FilesystemSchedulingRule(loadFile); try { manager.beginRule(rule, new NullProgressMonitor()); GZIPInputStream inputStream = new GZIPInputStream(new FileInputStream(loadFile)); try { defaultCollageRoot = CollageRoot.loadFrom(inputStream); } finally { inputStream.close(); } } finally { manager.endRule(rule); } List<String> warnings = defaultCollageRoot.getDependencyWarnings(); if (!warnings.isEmpty()) { CollageUtilities.showWarning(PLUGIN_NAME, String.format("Collage stored data loaded with the following warning%s:%n%s", (warnings.size() == 1) ? "" : "s", CollageUtilities.join(warnings, "\n"))); } } catch (Exception e) { File backupTarget = getStateLocation().append(getBackupFileName()).toFile(); try { CollageUtilities.fileCopy(loadFile, backupTarget); CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nCollage storage has been backed up to \"%s\".", e.getMessage(), backupTarget.getAbsolutePath())); } catch (Exception e1) { CollageUtilities.showError(PLUGIN_NAME, String.format("Unable to load Collage stored data:%n%s%nWARNING: An attempt to back up Collage storage to \"%s\" failed!%nIf you want to recover your data, copy it from \"%s\" before closing Eclipse.", e.getMessage(), backupTarget.getAbsolutePath(), loadFile.getAbsolutePath())); } } break; } }
diff --git a/MonTransit/src/org/montrealtransit/android/activity/BusLineInfo.java b/MonTransit/src/org/montrealtransit/android/activity/BusLineInfo.java index f3093589..b1416df1 100644 --- a/MonTransit/src/org/montrealtransit/android/activity/BusLineInfo.java +++ b/MonTransit/src/org/montrealtransit/android/activity/BusLineInfo.java @@ -1,263 +1,265 @@ package org.montrealtransit.android.activity; import java.util.List; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.Utils; import org.montrealtransit.android.dialog.BusLineSelectDirection; import org.montrealtransit.android.dialog.BusLineSelectDirectionDialogListener; import org.montrealtransit.android.provider.StmManager; import org.montrealtransit.android.provider.StmStore; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.FilterQueryProvider; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.SimpleCursorAdapter.ViewBinder; /** * This activity display information about a bus line. * @author Mathieu M�a */ public class BusLineInfo extends Activity implements ViewBinder, BusLineSelectDirectionDialogListener, OnItemClickListener, FilterQueryProvider { /** * The current bus line. */ private StmStore.BusLine busLine; /** * The bus line direction. */ private StmStore.BusLineDirection busLineDirection; /** * The cursor used to display the bus line stops. */ private Cursor cursor; /** * The log tag. */ private static final String TAG = BusLineInfo.class.getSimpleName(); /** * The extra ID for the bus line number. */ public static final String EXTRA_LINE_NUMBER = "extra_line_number"; /** * The extra ID for the bus line direction ID. */ public static final String EXTRA_LINE_DIRECTION_ID = "extra_line_direction_id"; /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { MyLog.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); // set the UI setContentView(R.layout.bus_line_info); ((ListView) findViewById(R.id.list)).setEmptyView(findViewById(R.id.list_empty)); ((ListView) findViewById(R.id.list)).setOnItemClickListener(this); // get the bus line ID and bus line direction ID from the intent. String lineNumber = Utils.getSavedStringValue(this.getIntent(), savedInstanceState, BusLineInfo.EXTRA_LINE_NUMBER); String lineDirectionId = Utils.getSavedStringValue(this.getIntent(), savedInstanceState, BusLineInfo.EXTRA_LINE_DIRECTION_ID); showNewLine(lineNumber, lineDirectionId); } /** * {@inheritDoc} */ @Override public void showNewLine(String newLineNumber, String newDirectionId) { MyLog.v(TAG, "showNewLine(" + newLineNumber + ", " + newDirectionId + ")"); if ((this.busLine == null || this.busLineDirection == null) || (!this.busLine.getNumber().equals(newLineNumber) || !this.busLineDirection.getId().equals(newDirectionId))) { MyLog.v(TAG, "show new bus line."); this.busLine = StmManager.findBusLine(this.getContentResolver(), newLineNumber); this.busLineDirection = StmManager.findBusLineDirection(this.getContentResolver(), newDirectionId); refreshAll(); } } /** * Refresh ALL the UI. */ private void refreshAll() { refreshBusLineInfo(); refreshBusStopList(); } /** * Refresh the bus line info UI. */ private void refreshBusLineInfo() { // bus line number ((TextView) findViewById(R.id.line_number)).setText(this.busLine.getNumber()); // bus line name ((TextView) findViewById(R.id.line_name)).setText(this.busLine.getName()); // bus line type ((ImageView) findViewById(R.id.bus_type)).setImageResource(Utils.getBusLineTypeImgFromType(this.busLine.getType())); // bus line direction BusLineSelectDirection selectBusLineDirection = new BusLineSelectDirection(this, this.busLine.getNumber(), this); ((TextView) findViewById(R.id.direction_string)).setOnClickListener(selectBusLineDirection); List<Integer> busLineDirection = Utils.getBusLineDirectionStringIdFromId(this.busLineDirection.getId()); ((TextView) findViewById(R.id.direction_main)).setText(getResources().getString(busLineDirection.get(0))); ((TextView) findViewById(R.id.direction_main)).setOnClickListener(selectBusLineDirection); // bus line direction details if (busLineDirection.size() >= 2) { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.direction_detail)).setText(getResources().getString(busLineDirection.get(1))); ((TextView) findViewById(R.id.direction_detail)).setOnClickListener(selectBusLineDirection); + } else { + ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.INVISIBLE); } } /** * Refresh the bus stops list UI. */ private void refreshBusStopList() { ((ListView) findViewById(R.id.list)).setAdapter(getAdapter()); } /** * Return the bus stops list for this bus line number and direction. * @return the bus stops list adapter. */ private SimpleCursorAdapter getAdapter() { this.cursor = StmManager.findBusLineStops(this.getContentResolver(), this.busLine.getNumber(), this.busLineDirection.getId()); String[] from = new String[] { StmStore.BusStop.STOP_CODE, StmStore.BusStop.STOP_PLACE, StmStore.BusStop.STATION_NAME, StmStore.BusStop.STOP_SUBWAY_STATION_ID }; int[] to = new int[] { R.id.stop_code, R.id.place, R.id.station_name, R.id.subway_img }; SimpleCursorAdapter busStops = new SimpleCursorAdapter(this, R.layout.bus_line_info_stops_list_item, this.cursor, from, to); busStops.setViewBinder(this); busStops.setFilterQueryProvider(this); return busStops; } /** * {@inheritDoc} */ @Override public Cursor runQuery(CharSequence constraint) { return StmManager.searchBusLineStops(this.getContentResolver(), this.busLine.getNumber(), this.busLineDirection .getId(), constraint.toString()); } /** * {@inheritDoc} */ @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (view.getId() == R.id.subway_img) { if (cursor.getInt(cursor.getColumnIndex(StmStore.BusStop.STOP_SUBWAY_STATION_ID)) != 0) { ((ImageView) view).setVisibility(View.VISIBLE); } else { ((ImageView) view).setVisibility(View.GONE); } return true; } else if (view.getId() == R.id.place) { ((TextView) view).setText(Utils.cleanBusStopPlace(cursor.getString(cursor.getColumnIndex(StmStore.BusStop.STOP_PLACE)))); return true; } else { return false; } } /** * {@inheritDoc} */ @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { MyLog.v(TAG, "onItemClick(" + v.getId() + "," + v.getId() + "," + position + "," + id + ")"); if (id > 0) { Intent intent = new Intent(this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, String.valueOf(id)); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, this.busLine.getNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_DIRECTION, this.busLineDirection.getId()); startActivity(intent); } } /** * The menu item to show the map */ private static final int MENU_SEE_MAP = Menu.FIRST; /** * The menu item to select the bus line direction. */ private static final int MENU_CHANGE_DIRECTION = Menu.FIRST + 1; /** * The menu used to show the user preferences. */ private static final int MENU_PREFERENCES = Menu.FIRST + 2; /** * The menu used to show the about screen. */ private static final int MENU_ABOUT = Menu.FIRST + 3; /** * {@inheritDoc} */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem menuMap = menu.add(0, MENU_SEE_MAP, 0, R.string.see_bus_line_plan); menuMap.setIcon(R.drawable.ic_menu_bus_line_plan); MenuItem menuDirection = menu.add(0, MENU_CHANGE_DIRECTION, 0, R.string.change_direction); menuDirection.setIcon(android.R.drawable.ic_menu_compass); MenuItem menuPref = menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences); menuPref.setIcon(android.R.drawable.ic_menu_preferences); MenuItem menuAbout = menu.add(0, MENU_ABOUT, Menu.NONE, R.string.menu_about); menuAbout.setIcon(android.R.drawable.ic_menu_info_details); return true; } /** * {@inheritDoc} */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SEE_MAP: String url = "http://www.stm.info/bus/images/PLAN/lign-" + this.busLine.getNumber() + ".gif"; startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); break; case MENU_CHANGE_DIRECTION: BusLineSelectDirection select = new BusLineSelectDirection(this, this.busLine.getNumber(), this); select.showDialog(); break; case MENU_PREFERENCES: startActivity(new Intent(this, UserPreferences.class)); break; case MENU_ABOUT: Utils.showAboutDialog(this); break; } return false; } /** * {@inheritDoc} */ @Override protected void onDestroy() { MyLog.v(TAG, "onDestroy()"); if (this.cursor!=null) {this.cursor.close(); } super.onDestroy(); } }
true
true
private void refreshBusLineInfo() { // bus line number ((TextView) findViewById(R.id.line_number)).setText(this.busLine.getNumber()); // bus line name ((TextView) findViewById(R.id.line_name)).setText(this.busLine.getName()); // bus line type ((ImageView) findViewById(R.id.bus_type)).setImageResource(Utils.getBusLineTypeImgFromType(this.busLine.getType())); // bus line direction BusLineSelectDirection selectBusLineDirection = new BusLineSelectDirection(this, this.busLine.getNumber(), this); ((TextView) findViewById(R.id.direction_string)).setOnClickListener(selectBusLineDirection); List<Integer> busLineDirection = Utils.getBusLineDirectionStringIdFromId(this.busLineDirection.getId()); ((TextView) findViewById(R.id.direction_main)).setText(getResources().getString(busLineDirection.get(0))); ((TextView) findViewById(R.id.direction_main)).setOnClickListener(selectBusLineDirection); // bus line direction details if (busLineDirection.size() >= 2) { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.direction_detail)).setText(getResources().getString(busLineDirection.get(1))); ((TextView) findViewById(R.id.direction_detail)).setOnClickListener(selectBusLineDirection); } }
private void refreshBusLineInfo() { // bus line number ((TextView) findViewById(R.id.line_number)).setText(this.busLine.getNumber()); // bus line name ((TextView) findViewById(R.id.line_name)).setText(this.busLine.getName()); // bus line type ((ImageView) findViewById(R.id.bus_type)).setImageResource(Utils.getBusLineTypeImgFromType(this.busLine.getType())); // bus line direction BusLineSelectDirection selectBusLineDirection = new BusLineSelectDirection(this, this.busLine.getNumber(), this); ((TextView) findViewById(R.id.direction_string)).setOnClickListener(selectBusLineDirection); List<Integer> busLineDirection = Utils.getBusLineDirectionStringIdFromId(this.busLineDirection.getId()); ((TextView) findViewById(R.id.direction_main)).setText(getResources().getString(busLineDirection.get(0))); ((TextView) findViewById(R.id.direction_main)).setOnClickListener(selectBusLineDirection); // bus line direction details if (busLineDirection.size() >= 2) { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.direction_detail)).setText(getResources().getString(busLineDirection.get(1))); ((TextView) findViewById(R.id.direction_detail)).setOnClickListener(selectBusLineDirection); } else { ((TextView) findViewById(R.id.direction_detail)).setVisibility(View.INVISIBLE); } }
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java b/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java index ca57dd4f..a99955b9 100644 --- a/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java +++ b/araqne-logdb/src/main/java/org/araqne/logdb/query/parser/ExpressionParser.java @@ -1,400 +1,402 @@ /* * Copyright 2013 Future Systems * * 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.logdb.query.parser; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.araqne.logdb.LogQueryParseException; import org.araqne.logdb.query.expr.Expression; public class ExpressionParser { public static Expression parse(String s, OpEmitterFactory of, FuncEmitterFactory ff, TermEmitterFactory tf) { if (s == null) throw new IllegalArgumentException("expression string should not be null"); s = s.replaceAll("\t", " "); List<Term> terms = tokenize(s); List<Term> output = convertToPostfix(terms); Stack<Expression> exprStack = new Stack<Expression>(); for (Term term : output) { if (term instanceof OpTerm) { OpTerm op = (OpTerm) term; of.emit(exprStack, op); } else if (term instanceof TokenTerm) { // parse token expression (variable or numeric constant) TokenTerm t = (TokenTerm) term; tf.emit(exprStack, t); } else { // parse function expression FuncTerm f = (FuncTerm) term; ff.emit(exprStack, f); } } return exprStack.pop(); } private static OpEmitterFactory evalOEF = new EvalOpEmitterFactory(); private static FuncEmitterFactory evalFEF = new EvalFuncEmitterFactory(); private static TermEmitterFactory evalTEF = new EvalTermEmitterFactory(); public static Expression parse(String s) { return parse(s, evalOEF, evalFEF, evalTEF); } private static List<Term> convertToPostfix(List<Term> tokens) { Stack<Term> opStack = new Stack<Term>(); List<Term> output = new ArrayList<Term>(); int i = 0; int len = tokens.size(); while (i < len) { Term token = tokens.get(i); if (isDelimiter(token)) { // need to pop operator and write to output? while (needPop(token, opStack, output)) { Term last = opStack.pop(); output.add(last); } if (token instanceof OpTerm || token instanceof FuncTerm) { opStack.add(token); } else if (((TokenTerm) token).getText().equals("(")) { opStack.add(token); } else if (((TokenTerm) token).getText().equals(")")) { boolean foundMatchParens = false; while (!opStack.isEmpty()) { Term last = opStack.pop(); if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) { foundMatchParens = true; break; } else { output.add(last); } } if (!foundMatchParens) throw new LogQueryParseException("parens-mismatch", -1); - Term last = opStack.pop(); - if (last instanceof FuncTerm) { - output.add(last); - } else { - opStack.push(last); + if (!opStack.empty()) { + Term last = opStack.pop(); + if (last instanceof FuncTerm) { + output.add(last); + } else { + opStack.push(last); + } } } } else { output.add(token); } i++; } // last operator flush while (!opStack.isEmpty()) { Term op = opStack.pop(); output.add(op); } return output; } private static boolean needPop(Term token, Stack<Term> opStack, List<Term> output) { if (!(token instanceof OpTerm)) return false; OpTerm currentOp = (OpTerm) token; int precedence = currentOp.precedence; boolean leftAssoc = currentOp.leftAssoc; OpTerm lastOp = null; if (!opStack.isEmpty()) { Term t = opStack.peek(); if (!(t instanceof OpTerm)) { return false; } lastOp = (OpTerm) t; } else { return false; } if (leftAssoc && precedence <= lastOp.precedence) return true; if (precedence < lastOp.precedence) return true; return false; } private static boolean isOperator(String token) { if (token == null) return false; return isDelimiter(token); } public static List<Term> tokenize(String s) { return tokenize(s, 0, s.length() - 1); } private static List<Term> tokenize(String s, int begin, int end) { List<Term> tokens = new ArrayList<Term>(); String lastToken = null; int next = begin; while (true) { ParseResult r = nextToken(s, next, end); if (r == null) break; String token = (String) r.value; if (token.isEmpty()) continue; // read function call (including nested one) if (token.equals("(") && lastToken != null && !isOperator(lastToken)) { // remove last term and add function term instead tokens.remove(tokens.size() - 1); List<String> functionTokens = new ArrayList<String>(); functionTokens.add(lastToken); tokens.add(new FuncTerm(functionTokens)); } OpTerm op = OpTerm.parse(token); // check if unary operator if (op != null && op.symbol.equals("-")) { Term lastTerm = null; if (!tokens.isEmpty()) { lastTerm = tokens.get(tokens.size() - 1); } if (lastToken == null || lastToken.equals("(") || lastTerm instanceof OpTerm) { op = OpTerm.Neg; } } if (op != null) tokens.add(op); else tokens.add(new TokenTerm(token)); next = r.next; lastToken = token; } return tokens; } private static ParseResult nextToken(String s, int begin, int end) { if (begin > end) return null; // use r.next as a position here (need +1 for actual next) ParseResult r = findNextDelimiter(s, begin, end); if (r.next < begin) { // no symbol operator and white space, return whole string String token = s.substring(begin, end + 1).trim(); return new ParseResult(token, end + 1); } if (isAllWhitespaces(s, begin, r.next - 1)) { // check if next token is quoted string if (r.value.equals("\"")) { int p = s.indexOf('"', r.next + 1); if (p < 0) { String quoted = s.substring(r.next); return new ParseResult(quoted, s.length()); } else { String quoted = s.substring(r.next, p + 1); return new ParseResult(quoted, p + 1); } } // check whitespace String token = (String) r.value; if (token.trim().isEmpty()) return nextToken(s, skipSpaces(s, begin), end); // return operator int len = token.length(); return new ParseResult(token, r.next + len); } else { // return term String token = s.substring(begin, r.next).trim(); return new ParseResult(token, r.next); } } private static boolean isAllWhitespaces(String s, int begin, int end) { if (end < begin) return true; for (int i = begin; i <= end; i++) if (s.charAt(i) != ' ' && s.charAt(i) != '\t') return false; return true; } private static ParseResult findNextDelimiter(String s, int begin, int end) { // check parens, comma and operators ParseResult r = new ParseResult(null, -1); min(r, "\"", s.indexOf('"', begin), end); min(r, "(", s.indexOf('(', begin), end); min(r, ")", s.indexOf(')', begin), end); min(r, ",", s.indexOf(',', begin), end); for (OpTerm op : OpTerm.values()) { // check alphabet keywords if (op.isAlpha) continue; min(r, op.symbol, s.indexOf(op.symbol, begin), end); } // check white spaces // tabs are removed by ExpressionParser.parse, so it processes space only. min(r, " ", s.indexOf(' ', begin), end); return r; } private static boolean isDelimiter(String s) { String d = s.trim(); if (d.equals("(") || d.equals(")") || d.equals(",")) return true; for (OpTerm op : OpTerm.values()) if (op.symbol.equals(s)) return true; return false; } private static void min(ParseResult r, String symbol, int p, int end) { if (p < 0) return; boolean change = p >= 0 && p <= end && (r.next == -1 || p < r.next); if (change) { r.value = symbol; r.next = p; } } private static boolean isDelimiter(Term t) { if (t instanceof OpTerm || t instanceof FuncTerm) return true; if (t instanceof TokenTerm) { String text = ((TokenTerm) t).getText(); return text.equals("(") || text.equals(")"); } return false; } private static interface Term { } public static class TokenTerm implements Term { private String text; public TokenTerm(String text) { this.text = text; } @Override public String toString() { return getText(); } public String getText() { return text; } } public static enum OpTerm implements Term { Add("+", 500), Sub("-", 500), Mul("*", 510), Div("/", 510), Neg("-", 520, false, true, false), Gte(">=", 410), Lte("<=", 410), Gt(">", 410), Lt("<", 410), Eq("==", 400), Neq("!=", 400), And("and", 310, true, false, true), Or("or", 300, true, false, true), Not("not", 320, false, true, true), Comma(",", 200), From("from", 100, true, false, true), union("union", 110, false, true, true), ; OpTerm(String symbol, int precedence) { this(symbol, precedence, true, false, false); } OpTerm(String symbol, int precedence, boolean leftAssoc, boolean unary, boolean isAlpha) { this.symbol = symbol; this.precedence = precedence; this.leftAssoc = leftAssoc; this.unary = unary; this.isAlpha = isAlpha; } public String symbol; public int precedence; public boolean leftAssoc; public boolean unary; public boolean isAlpha; public static OpTerm parse(String token) { for (OpTerm t : values()) if (t.symbol.equals(token)) return t; return null; } @Override public String toString() { return symbol; } } public static class FuncTerm implements Term { private List<String> tokens; public FuncTerm(List<String> tokens) { this.tokens = tokens; } @Override public String toString() { return "func term(" + tokens + ")"; } public List<String> getTokens() { return tokens; } } public static int skipSpaces(String text, int position) { int i = position; while (i < text.length() && text.charAt(i) == ' ') i++; return i; } }
true
true
private static List<Term> convertToPostfix(List<Term> tokens) { Stack<Term> opStack = new Stack<Term>(); List<Term> output = new ArrayList<Term>(); int i = 0; int len = tokens.size(); while (i < len) { Term token = tokens.get(i); if (isDelimiter(token)) { // need to pop operator and write to output? while (needPop(token, opStack, output)) { Term last = opStack.pop(); output.add(last); } if (token instanceof OpTerm || token instanceof FuncTerm) { opStack.add(token); } else if (((TokenTerm) token).getText().equals("(")) { opStack.add(token); } else if (((TokenTerm) token).getText().equals(")")) { boolean foundMatchParens = false; while (!opStack.isEmpty()) { Term last = opStack.pop(); if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) { foundMatchParens = true; break; } else { output.add(last); } } if (!foundMatchParens) throw new LogQueryParseException("parens-mismatch", -1); Term last = opStack.pop(); if (last instanceof FuncTerm) { output.add(last); } else { opStack.push(last); } } } else { output.add(token); } i++; } // last operator flush while (!opStack.isEmpty()) { Term op = opStack.pop(); output.add(op); } return output; }
private static List<Term> convertToPostfix(List<Term> tokens) { Stack<Term> opStack = new Stack<Term>(); List<Term> output = new ArrayList<Term>(); int i = 0; int len = tokens.size(); while (i < len) { Term token = tokens.get(i); if (isDelimiter(token)) { // need to pop operator and write to output? while (needPop(token, opStack, output)) { Term last = opStack.pop(); output.add(last); } if (token instanceof OpTerm || token instanceof FuncTerm) { opStack.add(token); } else if (((TokenTerm) token).getText().equals("(")) { opStack.add(token); } else if (((TokenTerm) token).getText().equals(")")) { boolean foundMatchParens = false; while (!opStack.isEmpty()) { Term last = opStack.pop(); if (last instanceof TokenTerm && ((TokenTerm) last).getText().equals("(")) { foundMatchParens = true; break; } else { output.add(last); } } if (!foundMatchParens) throw new LogQueryParseException("parens-mismatch", -1); if (!opStack.empty()) { Term last = opStack.pop(); if (last instanceof FuncTerm) { output.add(last); } else { opStack.push(last); } } } } else { output.add(token); } i++; } // last operator flush while (!opStack.isEmpty()) { Term op = opStack.pop(); output.add(op); } return output; }
diff --git a/src/test/java/org/mailoverlord/server/config/DbcpDataSourceConfig.java b/src/test/java/org/mailoverlord/server/config/DbcpDataSourceConfig.java index 4ddb635..7b23cc8 100644 --- a/src/test/java/org/mailoverlord/server/config/DbcpDataSourceConfig.java +++ b/src/test/java/org/mailoverlord/server/config/DbcpDataSourceConfig.java @@ -1,51 +1,52 @@ package org.mailoverlord.server.config; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import javax.sql.DataSource; import java.sql.Connection; /** * DBCP DataSource configured by properties file. Used by continuous integration. */ @Configuration @PropertySource("file:src/test/config/ci/${DB:h2}.properties") public class DbcpDataSourceConfig { private static final Logger logger = LoggerFactory.getLogger(DbcpDataSourceConfig.class); @Autowired private Environment environment; @Bean(destroyMethod = "close") public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(environment.getProperty("db.class")); dataSource.setUrl(environment.getProperty("db.url")); dataSource.setUsername(environment.getProperty("db.user")); dataSource.setPassword(environment.getProperty("db.password")); dataSource.setValidationQuery(environment.getProperty("db.validation.query")); dataSource.setTestOnBorrow(environment.getProperty("db.test.on.borrow", Boolean.class)); + dataSource.setDefaultAutoCommit(false); logger.info("DataSource: " + dataSource); Connection con = null; try { con = dataSource.getConnection(); logger.info("Connection is closed: {}", con.isClosed()); } catch(Exception e) { logger.error("Error while getting connection", e); } finally { if(con != null) try { con.close(); } catch(Exception ignore) {} } return dataSource; } }
true
true
public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(environment.getProperty("db.class")); dataSource.setUrl(environment.getProperty("db.url")); dataSource.setUsername(environment.getProperty("db.user")); dataSource.setPassword(environment.getProperty("db.password")); dataSource.setValidationQuery(environment.getProperty("db.validation.query")); dataSource.setTestOnBorrow(environment.getProperty("db.test.on.borrow", Boolean.class)); logger.info("DataSource: " + dataSource); Connection con = null; try { con = dataSource.getConnection(); logger.info("Connection is closed: {}", con.isClosed()); } catch(Exception e) { logger.error("Error while getting connection", e); } finally { if(con != null) try { con.close(); } catch(Exception ignore) {} } return dataSource; }
public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(environment.getProperty("db.class")); dataSource.setUrl(environment.getProperty("db.url")); dataSource.setUsername(environment.getProperty("db.user")); dataSource.setPassword(environment.getProperty("db.password")); dataSource.setValidationQuery(environment.getProperty("db.validation.query")); dataSource.setTestOnBorrow(environment.getProperty("db.test.on.borrow", Boolean.class)); dataSource.setDefaultAutoCommit(false); logger.info("DataSource: " + dataSource); Connection con = null; try { con = dataSource.getConnection(); logger.info("Connection is closed: {}", con.isClosed()); } catch(Exception e) { logger.error("Error while getting connection", e); } finally { if(con != null) try { con.close(); } catch(Exception ignore) {} } return dataSource; }
diff --git a/src/helperclasses/AnnotationWriter.java b/src/helperclasses/AnnotationWriter.java index 1715ff7..4658725 100644 --- a/src/helperclasses/AnnotationWriter.java +++ b/src/helperclasses/AnnotationWriter.java @@ -1,189 +1,198 @@ package helperclasses; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import annotationclasses.DocInfoAnnotation; import annotationclasses.EventAnnotation; import annotationclasses.LinkInfoAnnotation; import dataclasses.DocInfo; import dataclasses.EventInfo; import dataclasses.LinkInfo; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.time.TimeAnnotations.TimexAnnotation; import edu.stanford.nlp.time.Timex; import edu.stanford.nlp.time.XMLUtils; import edu.stanford.nlp.util.CoreMap; import org.w3c.dom.Element; import org.w3c.dom.Node; public class AnnotationWriter { public static final String HEADER = "<?xml version=\"1.0\" ?>\n" + "<TimeML xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:noNamespaceSchemaLocation=\"http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd\">\n\n"; public static final String FOOTER = "</TimeML>\n\n"; /* * Taken from http://www.java2s.com/Code/Java/Data-Type/Returnstrueifspecifiedcharacterisapunctuationcharacter.htm */ private static boolean isPunctuation(char c) { return c == ',' || c == '.' || c == '!' || c == '?' || c == ':' || c == ';' || c == '"' || c == '\'' || c == '`'; } private static void writeText(Annotation annotation, BufferedWriter out, ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException { Element textElem = createTextElement(annotation, events, links); String s = XMLUtils.nodeToString(textElem, false); out.write(s + "\n"); } private static Element createTextElement(Annotation annotation, ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException { // Link ID assignment happens here int nextLinkID = 0; // Keep track of whether we're inside a tag String curType = ""; Timex curTimex = null; Element element = XMLUtils.createElement("TEXT"); + int lastCharOffset = 0; + String docText = annotation.get(CoreAnnotations.TextAnnotation.class); List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); int tid = 1; for(CoreMap sentence: sentences) { List<CoreLabel> tokens = sentence.get(TokensAnnotation.class); for (CoreLabel token: tokens) { // Get information from token Timex timex = token.get(TimexAnnotation.class); EventInfo event = token.get(EventAnnotation.class); LinkInfo link = token.get(LinkInfoAnnotation.class); - String text = token.get(CoreAnnotations.OriginalTextAnnotation.class); + String tokenText = token.get(CoreAnnotations.OriginalTextAnnotation.class); - //TODO fix this, and in general have better whitespace recovery - String space = (isPunctuation(text.charAt(0)) ? "" : " "); Node tokenNode = null; + int annotatedBeginCharOffset = -1; + int annotatedEndCharOffset = -1; // Handle if this is a timex if (timex != null) { if (!timex.equals(curTimex)) { // TODO: use timex tid as is once fixed in SUTime Element timexElem = timex.toXmlElement(); timexElem.setAttribute("tid", "t" + tid); tid++; tokenNode = timexElem; curType = timex.timexType(); curTimex = timex; + annotatedBeginCharOffset = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class); + annotatedEndCharOffset = annotatedBeginCharOffset + timex.text().length(); } // Handle if this is an event } else if (event != null /*&& !curType.equals(event.currEventType)*/) { // TODO: Handle events with multiple tokens? Element eventElem = XMLUtils.createElement("EVENT"); eventElem.setAttribute("eid", event.currEventId); eventElem.setAttribute("class", event.currEventType); - eventElem.setTextContent(text); + eventElem.setTextContent(tokenText); tokenNode = eventElem; curType = event.currEventType; curTimex = null; events.add(event); + annotatedBeginCharOffset = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class); + annotatedEndCharOffset = token.get(CoreAnnotations.CharacterOffsetEndAnnotation.class); // Handle normal tokens } else { - tokenNode = XMLUtils.createTextNode(space + text); curType = ""; curTimex = null; } if (tokenNode != null) { - if (!curType.isEmpty()) { - element.appendChild(XMLUtils.createTextNode(" ")); - } + String spanText = docText.substring(lastCharOffset,annotatedBeginCharOffset); + element.appendChild(XMLUtils.createTextNode(spanText)); element.appendChild(tokenNode); + lastCharOffset = annotatedEndCharOffset; } // Handle links if (link != null) { link.id = "l" + (nextLinkID++); links.add(link); } } } + if (lastCharOffset < docText.length()) { + String spanText = docText.substring(lastCharOffset); + element.appendChild(XMLUtils.createTextNode(spanText)); + } return element; } private static void writeEventInstances(ArrayList<EventInfo> events, BufferedWriter out) throws IOException { for (EventInfo event: events) { out.write("<MAKEINSTANCE eventID=\"" + event.currEventId + "\" eiid=\"" + event.currEiid + "\" tense=\"" + event.tense + "\" aspect=\"" + event.aspect + "\" polarity=\"" + event.polarity + "\" pos=\"" + event.pos + "\"/>\n"); } } private static void writeTimexEventLinks(ArrayList<LinkInfo> links, BufferedWriter out) throws IOException { for (LinkInfo link: links) { String instanceString = ""; if (link.time != null) instanceString = "timeID=\"" + link.time.currTimeId + "\""; else instanceString = "eventInstanceID=\"" + link.eventInstance.currEiid + "\""; out.write("<TLINK lid=\"" + link.id + "\" relType=\"" + link.type + "\" " + instanceString + " relatedToEventInstance=\"" + link.relatedTo.currEiid + "\" origin=\"USER\"/>\n"); //TODO fix origin } } public static Element createElement(String tag, String text) { Element elem = XMLUtils.createElement(tag); elem.setTextContent(text); return elem; } public static void writeElement(BufferedWriter out, String tag, String text) throws IOException { Element elem = createElement(tag, text); String s = XMLUtils.nodeToString(elem, false); out.write(s + "\n"); } public static void writeAnnotation(Annotation annotation, BufferedWriter out) throws IOException { ArrayList<EventInfo> events = new ArrayList<EventInfo>(); ArrayList<LinkInfo> links = new ArrayList<LinkInfo>(); // Get the auxiliary information associated with this document DocInfo info = annotation.get(DocInfoAnnotation.class); out.write(HEADER); out.write("<DOCID>" + info.id + "</DOCID>\n\n"); out.write("<DCT>" + info.dct + "</DCT>\n\n"); writeElement(out, "TITLE", info.title); writeElement(out, "EXTRAINFO", info.extra); writeText(annotation, out, events, links); writeEventInstances(events, out); writeTimexEventLinks(links, out); out.write(FOOTER); } }
false
true
private static Element createTextElement(Annotation annotation, ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException { // Link ID assignment happens here int nextLinkID = 0; // Keep track of whether we're inside a tag String curType = ""; Timex curTimex = null; Element element = XMLUtils.createElement("TEXT"); List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); int tid = 1; for(CoreMap sentence: sentences) { List<CoreLabel> tokens = sentence.get(TokensAnnotation.class); for (CoreLabel token: tokens) { // Get information from token Timex timex = token.get(TimexAnnotation.class); EventInfo event = token.get(EventAnnotation.class); LinkInfo link = token.get(LinkInfoAnnotation.class); String text = token.get(CoreAnnotations.OriginalTextAnnotation.class); //TODO fix this, and in general have better whitespace recovery String space = (isPunctuation(text.charAt(0)) ? "" : " "); Node tokenNode = null; // Handle if this is a timex if (timex != null) { if (!timex.equals(curTimex)) { // TODO: use timex tid as is once fixed in SUTime Element timexElem = timex.toXmlElement(); timexElem.setAttribute("tid", "t" + tid); tid++; tokenNode = timexElem; curType = timex.timexType(); curTimex = timex; } // Handle if this is an event } else if (event != null /*&& !curType.equals(event.currEventType)*/) { // TODO: Handle events with multiple tokens? Element eventElem = XMLUtils.createElement("EVENT"); eventElem.setAttribute("eid", event.currEventId); eventElem.setAttribute("class", event.currEventType); eventElem.setTextContent(text); tokenNode = eventElem; curType = event.currEventType; curTimex = null; events.add(event); // Handle normal tokens } else { tokenNode = XMLUtils.createTextNode(space + text); curType = ""; curTimex = null; } if (tokenNode != null) { if (!curType.isEmpty()) { element.appendChild(XMLUtils.createTextNode(" ")); } element.appendChild(tokenNode); } // Handle links if (link != null) { link.id = "l" + (nextLinkID++); links.add(link); } } } return element; }
private static Element createTextElement(Annotation annotation, ArrayList<EventInfo> events, ArrayList<LinkInfo> links) throws IOException { // Link ID assignment happens here int nextLinkID = 0; // Keep track of whether we're inside a tag String curType = ""; Timex curTimex = null; Element element = XMLUtils.createElement("TEXT"); int lastCharOffset = 0; String docText = annotation.get(CoreAnnotations.TextAnnotation.class); List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); int tid = 1; for(CoreMap sentence: sentences) { List<CoreLabel> tokens = sentence.get(TokensAnnotation.class); for (CoreLabel token: tokens) { // Get information from token Timex timex = token.get(TimexAnnotation.class); EventInfo event = token.get(EventAnnotation.class); LinkInfo link = token.get(LinkInfoAnnotation.class); String tokenText = token.get(CoreAnnotations.OriginalTextAnnotation.class); Node tokenNode = null; int annotatedBeginCharOffset = -1; int annotatedEndCharOffset = -1; // Handle if this is a timex if (timex != null) { if (!timex.equals(curTimex)) { // TODO: use timex tid as is once fixed in SUTime Element timexElem = timex.toXmlElement(); timexElem.setAttribute("tid", "t" + tid); tid++; tokenNode = timexElem; curType = timex.timexType(); curTimex = timex; annotatedBeginCharOffset = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class); annotatedEndCharOffset = annotatedBeginCharOffset + timex.text().length(); } // Handle if this is an event } else if (event != null /*&& !curType.equals(event.currEventType)*/) { // TODO: Handle events with multiple tokens? Element eventElem = XMLUtils.createElement("EVENT"); eventElem.setAttribute("eid", event.currEventId); eventElem.setAttribute("class", event.currEventType); eventElem.setTextContent(tokenText); tokenNode = eventElem; curType = event.currEventType; curTimex = null; events.add(event); annotatedBeginCharOffset = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class); annotatedEndCharOffset = token.get(CoreAnnotations.CharacterOffsetEndAnnotation.class); // Handle normal tokens } else { curType = ""; curTimex = null; } if (tokenNode != null) { String spanText = docText.substring(lastCharOffset,annotatedBeginCharOffset); element.appendChild(XMLUtils.createTextNode(spanText)); element.appendChild(tokenNode); lastCharOffset = annotatedEndCharOffset; } // Handle links if (link != null) { link.id = "l" + (nextLinkID++); links.add(link); } } } if (lastCharOffset < docText.length()) { String spanText = docText.substring(lastCharOffset); element.appendChild(XMLUtils.createTextNode(spanText)); } return element; }
diff --git a/src/java_jjclient/jjUpdate.java b/src/java_jjclient/jjUpdate.java index f5714e91..4aea1ece 100644 --- a/src/java_jjclient/jjUpdate.java +++ b/src/java_jjclient/jjUpdate.java @@ -1,152 +1,152 @@ /* * jjUpdate.java * * Created on October 17, 2005, 9:33 AM */ package java_jjclient; import javax.net.ssl.HttpsURLConnection; import java.net.URL; import java.util.Date; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URLEncoder; /** * * @author caryn */ public class jjUpdate { // account information private String username; private String password; /** * Constructor * @param jjUsername * @param jjPassword */ public jjUpdate(String jjUsername, String jjPassword) { username = jjUsername; password = jjPassword; } /** * Updates journal * @param subject * @param body * @param mood * @param location * @param security * @param music * @param format * @param email * @param allowComment * @return true if update succeeded. */ public boolean update (String subject, String body, String mood, String location, String security, String music, boolean format, boolean email, boolean allowComment) { Date today = new Date(); String strDate = today.toString(); // location, mood, security are all int values // aformat, subject, body, allow_comments, email_comments (checked, unchecked) are strings // translate location to integer value int locationInteger = 0; if (location.equals("Home")) locationInteger = 1; else if (location.equals("Work")) locationInteger = 2; else if (location.equals("School")) locationInteger = 3; else if (location.equals("Other")) locationInteger = 5; // translate security to integer value // default value is public int securityInteger = 2; if (security.equals("Private")) securityInteger = 0; else if (security.equals("Friends Only")) securityInteger = 1; // translate format, email and allow comments to string // boolean to string for auto format String strFormat = "checked"; if (!format) strFormat = "unchecked"; // boolean to string for email comments String strEmail = "unchecked"; if (email) strEmail = "checked"; String strAllow = "checked"; if (!allowComment) strAllow = "unchecked"; try { // construct the POST request data String type = "application/x-www-form-urlencoded"; String data = ""; data += "user=" + username; data += "&pass=" + password; data += "&security=" + securityInteger; data += "&location=" + locationInteger; data += "&mood=12"; // Not Specified value data += "&music=" + music; data += "&aformat" + strFormat; data += "&allow_comment=" + strAllow; data += "&email_comment" + strEmail; data += "&date=" + strDate; data += "&subject=" + subject; data += "&body=" + body; String encodedData = java.net.URLEncoder.encode(data,"UTF-8"); // open connection - URL jj = new URL ("https://www.justjournal/updateJournal"); + URL jj = new URL ("https://www.justjournal.com/updateJournal"); HttpsURLConnection conn = (HttpsURLConnection) jj.openConnection(); // set requesting agent, and POST conn.setRequestMethod ("POST"); conn.setRequestProperty ("User-Agent", "JustJournal"); conn.setRequestProperty( "Content-Type", type ); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(encodedData); writer.flush(); writer.close(); // getting the response BufferedReader input = new BufferedReader (new InputStreamReader (conn.getInputStream())); int response = input.read(); char [] returnCode = new char [50]; int i = 0; // for debugging while (response != -1) { returnCode [i] = (char) response; i++; response = input.read(); } input.close(); String code = new String (returnCode); System.out.println(code); } catch (Exception e) { System.err.println(e.getMessage()); } // if we get this far, we failed // display error msg return false; } }
true
true
public boolean update (String subject, String body, String mood, String location, String security, String music, boolean format, boolean email, boolean allowComment) { Date today = new Date(); String strDate = today.toString(); // location, mood, security are all int values // aformat, subject, body, allow_comments, email_comments (checked, unchecked) are strings // translate location to integer value int locationInteger = 0; if (location.equals("Home")) locationInteger = 1; else if (location.equals("Work")) locationInteger = 2; else if (location.equals("School")) locationInteger = 3; else if (location.equals("Other")) locationInteger = 5; // translate security to integer value // default value is public int securityInteger = 2; if (security.equals("Private")) securityInteger = 0; else if (security.equals("Friends Only")) securityInteger = 1; // translate format, email and allow comments to string // boolean to string for auto format String strFormat = "checked"; if (!format) strFormat = "unchecked"; // boolean to string for email comments String strEmail = "unchecked"; if (email) strEmail = "checked"; String strAllow = "checked"; if (!allowComment) strAllow = "unchecked"; try { // construct the POST request data String type = "application/x-www-form-urlencoded"; String data = ""; data += "user=" + username; data += "&pass=" + password; data += "&security=" + securityInteger; data += "&location=" + locationInteger; data += "&mood=12"; // Not Specified value data += "&music=" + music; data += "&aformat" + strFormat; data += "&allow_comment=" + strAllow; data += "&email_comment" + strEmail; data += "&date=" + strDate; data += "&subject=" + subject; data += "&body=" + body; String encodedData = java.net.URLEncoder.encode(data,"UTF-8"); // open connection URL jj = new URL ("https://www.justjournal/updateJournal"); HttpsURLConnection conn = (HttpsURLConnection) jj.openConnection(); // set requesting agent, and POST conn.setRequestMethod ("POST"); conn.setRequestProperty ("User-Agent", "JustJournal"); conn.setRequestProperty( "Content-Type", type ); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(encodedData); writer.flush(); writer.close(); // getting the response BufferedReader input = new BufferedReader (new InputStreamReader (conn.getInputStream())); int response = input.read(); char [] returnCode = new char [50]; int i = 0; // for debugging while (response != -1) { returnCode [i] = (char) response; i++; response = input.read(); } input.close(); String code = new String (returnCode); System.out.println(code); } catch (Exception e) { System.err.println(e.getMessage()); } // if we get this far, we failed // display error msg return false; }
public boolean update (String subject, String body, String mood, String location, String security, String music, boolean format, boolean email, boolean allowComment) { Date today = new Date(); String strDate = today.toString(); // location, mood, security are all int values // aformat, subject, body, allow_comments, email_comments (checked, unchecked) are strings // translate location to integer value int locationInteger = 0; if (location.equals("Home")) locationInteger = 1; else if (location.equals("Work")) locationInteger = 2; else if (location.equals("School")) locationInteger = 3; else if (location.equals("Other")) locationInteger = 5; // translate security to integer value // default value is public int securityInteger = 2; if (security.equals("Private")) securityInteger = 0; else if (security.equals("Friends Only")) securityInteger = 1; // translate format, email and allow comments to string // boolean to string for auto format String strFormat = "checked"; if (!format) strFormat = "unchecked"; // boolean to string for email comments String strEmail = "unchecked"; if (email) strEmail = "checked"; String strAllow = "checked"; if (!allowComment) strAllow = "unchecked"; try { // construct the POST request data String type = "application/x-www-form-urlencoded"; String data = ""; data += "user=" + username; data += "&pass=" + password; data += "&security=" + securityInteger; data += "&location=" + locationInteger; data += "&mood=12"; // Not Specified value data += "&music=" + music; data += "&aformat" + strFormat; data += "&allow_comment=" + strAllow; data += "&email_comment" + strEmail; data += "&date=" + strDate; data += "&subject=" + subject; data += "&body=" + body; String encodedData = java.net.URLEncoder.encode(data,"UTF-8"); // open connection URL jj = new URL ("https://www.justjournal.com/updateJournal"); HttpsURLConnection conn = (HttpsURLConnection) jj.openConnection(); // set requesting agent, and POST conn.setRequestMethod ("POST"); conn.setRequestProperty ("User-Agent", "JustJournal"); conn.setRequestProperty( "Content-Type", type ); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(encodedData); writer.flush(); writer.close(); // getting the response BufferedReader input = new BufferedReader (new InputStreamReader (conn.getInputStream())); int response = input.read(); char [] returnCode = new char [50]; int i = 0; // for debugging while (response != -1) { returnCode [i] = (char) response; i++; response = input.read(); } input.close(); String code = new String (returnCode); System.out.println(code); } catch (Exception e) { System.err.println(e.getMessage()); } // if we get this far, we failed // display error msg return false; }
diff --git a/components/bio-formats/src/loci/formats/in/CellSensReader.java b/components/bio-formats/src/loci/formats/in/CellSensReader.java index 85249404a..e86e4c1bf 100644 --- a/components/bio-formats/src/loci/formats/in/CellSensReader.java +++ b/components/bio-formats/src/loci/formats/in/CellSensReader.java @@ -1,599 +1,599 @@ // // CellSensReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, 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 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 loci.formats.in; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import loci.common.ByteArrayHandle; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.MetadataTools; import loci.formats.codec.Codec; import loci.formats.codec.CodecOptions; import loci.formats.codec.JPEGCodec; import loci.formats.codec.JPEG2000Codec; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffParser; /** * CellSensReader is the file format reader for cellSens .vsi files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/CellSensReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/CellSensReader.java;hb=HEAD">Gitweb</a></dd></dl> */ public class CellSensReader extends FormatReader { // -- Constants -- // Compression types private static final int RAW = 0; private static final int JPEG = 2; private static final int JPEG_2000 = 3; private static final int PNG = 8; private static final int BMP = 9; // Pixel types private static final int CHAR = 1; private static final int UCHAR = 2; private static final int SHORT = 3; private static final int USHORT = 4; private static final int INT = 5; private static final int UINT = 6; private static final int LONG = 7; private static final int ULONG = 8; private static final int FLOAT = 9; private static final int DOUBLE = 10; // -- Fields -- private String[] usedFiles; private TiffParser parser; private IFDList ifds; private Long[][] tileOffsets; private boolean jpeg = false; private int[] rows, cols; private int[] compressionType; private int[] tileX, tileY; private HashMap<TileCoordinate, Integer>[] tileMap; private int[] nDimensions; // -- Constructor -- /** Constructs a new cellSens reader. */ public CellSensReader() { super("CellSens VSI", "vsi"); domains = new String[] {FormatTools.HISTOLOGY_DOMAIN}; suffixSufficient = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); return usedFiles; } /* @see loci.formats.IFormatHandler#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); int currentSeries = getSeries(); if (currentSeries >= usedFiles.length - 1) { return super.openThumbBytes(no); } setSeries(usedFiles.length); byte[] thumb = FormatTools.openThumbBytes(this, 0); setSeries(currentSeries); return thumb; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (getSeries() < getSeriesCount() - ifds.size()) { int tileRows = rows[getSeries()]; int tileCols = cols[getSeries()]; Region image = new Region(x, y, w, h); int outputRow = 0, outputCol = 0; Region intersection = null; byte[] tileBuf = null; int pixel = getRGBChannelCount() * FormatTools.getBytesPerPixel(getPixelType()); int outputRowLen = w * pixel; for (int row=0; row<tileRows; row++) { for (int col=0; col<tileCols; col++) { int width = tileX[getSeries()]; int height = tileY[getSeries()]; Region tile = new Region(col * width, row * height, width, height); if (!tile.intersects(image)) { continue; } intersection = tile.intersection(image); tileBuf = decodeTile(no, row, col); int rowLen = pixel * (int) Math.min(intersection.width, width); int outputOffset = outputRow * outputRowLen + outputCol; for (int trow=0; trow<intersection.height; trow++) { int realRow = trow + intersection.y - tile.y; System.arraycopy(tileBuf, realRow * width * pixel, buf, outputOffset, rowLen); outputOffset += outputRowLen; } outputCol += rowLen; } if (intersection != null) { outputRow += intersection.height; outputCol = 0; } } return buf; } else { int ifdIndex = getSeries() - (usedFiles.length - 1); return parser.getSamples(ifds.get(ifdIndex), buf, x, y, w, h); } } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { parser = null; ifds = null; usedFiles = null; tileOffsets = null; jpeg = false; rows = null; cols = null; compressionType = null; tileX = null; tileY = null; tileMap = null; nDimensions = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser = new TiffParser(id); ifds = parser.getIFDs(); RandomAccessInputStream vsi = new RandomAccessInputStream(id); vsi.order(parser.getStream().isLittleEndian()); vsi.seek(parser.getStream().getFilePointer()); vsi.skipBytes(273); ArrayList<String> files = new ArrayList<String>(); Location file = new Location(id).getAbsoluteFile(); Location dir = file.getParentFile(); String name = file.getName(); name = name.substring(0, name.lastIndexOf(".")); Location pixelsDir = new Location(dir, "_" + name + "_"); String[] stackDirs = pixelsDir.list(true); for (String f : stackDirs) { Location stackDir = new Location(pixelsDir, f); String[] pixelsFiles = stackDir.list(true); if (pixelsFiles != null) { for (String pixelsFile : pixelsFiles) { if (checkSuffix(pixelsFile, "ets")) { files.add(new Location(stackDir, pixelsFile).getAbsolutePath()); } } } } files.add(file.getAbsolutePath()); usedFiles = files.toArray(new String[files.size()]); core = new CoreMetadata[files.size() - 1 + ifds.size()]; tileOffsets = new Long[files.size() - 1][]; rows = new int[files.size() - 1]; cols = new int[files.size() - 1]; nDimensions = new int[core.length]; IFDList exifs = parser.getExifIFDs(); compressionType = new int[core.length]; tileX = new int[core.length]; tileY = new int[core.length]; tileMap = new HashMap[core.length]; for (int s=0; s<core.length; s++) { core[s] = new CoreMetadata(); tileMap[s] = new HashMap<TileCoordinate, Integer>(); if (s < files.size() - 1) { setSeries(s); parseETSFile(files.get(s), s); core[s].littleEndian = false; core[s].interleaved = core[s].rgb; setSeries(0); } else { IFD ifd = ifds.get(s - files.size() + 1); PhotoInterp p = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[s].rgb = samples > 1 || p == PhotoInterp.RGB; core[s].sizeX = (int) ifd.getImageWidth(); core[s].sizeY = (int) ifd.getImageLength(); core[s].sizeZ = 1; core[s].sizeT = 1; core[s].sizeC = core[s].rgb ? samples : 1; core[s].littleEndian = ifd.isLittleEndian(); core[s].indexed = p == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null); core[s].imageCount = 1; core[s].pixelType = ifd.getPixelType(); core[s].interleaved = false; core[s].falseColor = false; core[s].thumbnail = s != 0; } core[s].dimensionOrder = "XYCZT"; core[s].metadataComplete = true; } vsi.close(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); } // -- Helper methods -- private int getTileSize() { int channels = getRGBChannelCount(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); return bpp * channels * tileX[getSeries()] * tileY[getSeries()]; } private byte[] decodeTile(int no, int row, int col) throws FormatException, IOException { if (tileMap[getSeries()] == null) { return new byte[getTileSize()]; } int[] zct = getZCTCoords(no); TileCoordinate t = new TileCoordinate(nDimensions[getSeries()]); t.coordinate[0] = col; t.coordinate[1] = row; if (t.coordinate.length > 3) { t.coordinate[2] = zct[0]; if (t.coordinate.length > 4) { t.coordinate[3] = zct[1]; } } Integer index = (Integer) tileMap[getSeries()].get(t); if (index == null) { return new byte[getTileSize()]; } Long offset = tileOffsets[getSeries()][index]; RandomAccessInputStream ets = new RandomAccessInputStream(usedFiles[getSeries()]); ets.seek(offset); CodecOptions options = new CodecOptions(); options.interleaved = isInterleaved(); options.littleEndian = isLittleEndian(); int tileSize = getTileSize(); if (tileSize == 0) { tileSize = tileX[getSeries()] * tileY[getSeries()] * 10; } options.maxBytes = (int) (offset + tileSize); byte[] buf = null; long end = index < tileOffsets[getSeries()].length - 1 ? tileOffsets[getSeries()][index + 1] : ets.length(); IFormatReader reader = null; String file = null; switch (compressionType[getSeries()]) { case RAW: buf = new byte[tileSize]; ets.read(buf); break; case JPEG: Codec codec = new JPEGCodec(); buf = codec.decompress(ets, options); break; case JPEG_2000: codec = new JPEG2000Codec(); buf = codec.decompress(ets, options); break; case PNG: file = "tile.png"; reader = new APNGReader(); case BMP: if (reader == null) { file = "tile.bmp"; reader = new BMPReader(); } byte[] b = new byte[(int) (end - offset)]; ets.read(b); Location.mapFile(file, new ByteArrayHandle(b)); reader.setId(file); buf = reader.openBytes(0); Location.mapFile(file, null); break; } if (reader != null) { reader.close(); } ets.close(); return buf; } private void parseETSFile(String file, int s) throws FormatException, IOException { RandomAccessInputStream etsFile = new RandomAccessInputStream(file); etsFile.order(true); // read the volume header String magic = etsFile.readString(4).trim(); if (!magic.equals("SIS")) { throw new FormatException("Unknown magic bytes: " + magic); } int headerSize = etsFile.readInt(); int version = etsFile.readInt(); nDimensions[s] = etsFile.readInt(); long additionalHeaderOffset = etsFile.readLong(); int additionalHeaderSize = etsFile.readInt(); etsFile.skipBytes(4); // reserved long usedChunkOffset = etsFile.readLong(); int nUsedChunks = etsFile.readInt(); etsFile.skipBytes(4); // reserved // read the additional header etsFile.seek(additionalHeaderOffset); String moreMagic = etsFile.readString(4).trim(); if (!moreMagic.equals("ETS")) { throw new FormatException("Unknown magic bytes: " + moreMagic); } etsFile.skipBytes(4); // extra version number int pixelType = etsFile.readInt(); core[s].sizeC = etsFile.readInt(); int colorspace = etsFile.readInt(); compressionType[s] = etsFile.readInt(); int compressionQuality = etsFile.readInt(); tileX[s] = etsFile.readInt(); tileY[s] = etsFile.readInt(); int tileZ = etsFile.readInt(); core[s].rgb = core[s].sizeC > 1; // read the used chunks etsFile.seek(usedChunkOffset); tileOffsets[s] = new Long[nUsedChunks]; ArrayList<TileCoordinate> tmpTiles = new ArrayList<TileCoordinate>(); for (int chunk=0; chunk<nUsedChunks; chunk++) { etsFile.skipBytes(4); TileCoordinate t = new TileCoordinate(nDimensions[s]); for (int i=0; i<nDimensions[s]; i++) { t.coordinate[i] = etsFile.readInt(); } tileOffsets[s][chunk] = etsFile.readLong(); int nBytes = etsFile.readInt(); etsFile.skipBytes(4); tmpTiles.add(t); } ArrayList<Integer> uniqueX = new ArrayList<Integer>(); ArrayList<Integer> uniqueY = new ArrayList<Integer>(); ArrayList<Integer> uniqueZ = new ArrayList<Integer>(); ArrayList<Integer> uniqueC = new ArrayList<Integer>(); for (TileCoordinate t : tmpTiles) { if (!uniqueX.contains(t.coordinate[0])) { uniqueX.add(t.coordinate[0]); } if (!uniqueY.contains(t.coordinate[1])) { uniqueY.add(t.coordinate[1]); } if (t.coordinate.length > 3) { if (!uniqueZ.contains(t.coordinate[2])) { uniqueZ.add(t.coordinate[2]); } if (t.coordinate.length > 4) { if (!uniqueC.contains(t.coordinate[3])) { uniqueC.add(t.coordinate[3]); } } } } core[s].sizeX = tileX[s] * uniqueX.size(); core[s].sizeY = tileY[s] * uniqueY.size(); core[s].sizeZ = uniqueZ.size(); if (uniqueC.size() > 1) { core[s].sizeC *= uniqueC.size(); } core[s].sizeT = 1; if (core[s].sizeZ == 0) { core[s].sizeZ = 1; } core[s].imageCount = core[s].sizeZ * core[s].sizeT; if (uniqueC.size() > 1) { core[s].imageCount *= uniqueC.size(); } - rows[s] = uniqueX.size(); - cols[s] = uniqueY.size(); + rows[s] = uniqueY.size(); + cols[s] = uniqueX.size(); for (int i=0; i<tmpTiles.size(); i++) { tileMap[s].put(tmpTiles.get(i), i); } core[s].pixelType = convertPixelType(pixelType); etsFile.close(); } private int convertPixelType(int pixelType) throws FormatException { switch (pixelType) { case CHAR: return FormatTools.INT8; case UCHAR: return FormatTools.UINT8; case SHORT: return FormatTools.INT16; case USHORT: return FormatTools.UINT16; case INT: return FormatTools.INT32; case UINT: return FormatTools.UINT32; case LONG: throw new FormatException("Unsupported pixel type: long"); case ULONG: throw new FormatException("Unsupported pixel type: unsigned long"); case FLOAT: return FormatTools.FLOAT; case DOUBLE: return FormatTools.DOUBLE; default: throw new FormatException("Unsupported pixel type: " + pixelType); } } // -- Helper class -- class TileCoordinate { public int[] coordinate; public TileCoordinate(int nDimensions) { coordinate = new int[nDimensions]; } public boolean equals(Object o) { if (!(o instanceof TileCoordinate)) { return false; } TileCoordinate t = (TileCoordinate) o; if (coordinate.length != t.coordinate.length) { return false; } for (int i=0; i<coordinate.length; i++) { if (coordinate[i] != t.coordinate[i]) { return false; } } return true; } public int hashCode() { int[] lengths = new int[coordinate.length]; lengths[0] = rows[getSeries()]; lengths[1] = cols[getSeries()]; if (coordinate.length > 3) { lengths[2] = getSizeZ(); if (coordinate.length > 4) { lengths[3] = getEffectiveSizeC(); } } for (int i=0; i<lengths.length; i++) { if (lengths[i] == 0) { lengths[i] = 1; } } return FormatTools.positionToRaster(lengths, coordinate); } public String toString() { StringBuffer b = new StringBuffer("{"); for (int p : coordinate) { b.append(p); b.append(", "); } b.append("}"); return b.toString(); } } }
true
true
private void parseETSFile(String file, int s) throws FormatException, IOException { RandomAccessInputStream etsFile = new RandomAccessInputStream(file); etsFile.order(true); // read the volume header String magic = etsFile.readString(4).trim(); if (!magic.equals("SIS")) { throw new FormatException("Unknown magic bytes: " + magic); } int headerSize = etsFile.readInt(); int version = etsFile.readInt(); nDimensions[s] = etsFile.readInt(); long additionalHeaderOffset = etsFile.readLong(); int additionalHeaderSize = etsFile.readInt(); etsFile.skipBytes(4); // reserved long usedChunkOffset = etsFile.readLong(); int nUsedChunks = etsFile.readInt(); etsFile.skipBytes(4); // reserved // read the additional header etsFile.seek(additionalHeaderOffset); String moreMagic = etsFile.readString(4).trim(); if (!moreMagic.equals("ETS")) { throw new FormatException("Unknown magic bytes: " + moreMagic); } etsFile.skipBytes(4); // extra version number int pixelType = etsFile.readInt(); core[s].sizeC = etsFile.readInt(); int colorspace = etsFile.readInt(); compressionType[s] = etsFile.readInt(); int compressionQuality = etsFile.readInt(); tileX[s] = etsFile.readInt(); tileY[s] = etsFile.readInt(); int tileZ = etsFile.readInt(); core[s].rgb = core[s].sizeC > 1; // read the used chunks etsFile.seek(usedChunkOffset); tileOffsets[s] = new Long[nUsedChunks]; ArrayList<TileCoordinate> tmpTiles = new ArrayList<TileCoordinate>(); for (int chunk=0; chunk<nUsedChunks; chunk++) { etsFile.skipBytes(4); TileCoordinate t = new TileCoordinate(nDimensions[s]); for (int i=0; i<nDimensions[s]; i++) { t.coordinate[i] = etsFile.readInt(); } tileOffsets[s][chunk] = etsFile.readLong(); int nBytes = etsFile.readInt(); etsFile.skipBytes(4); tmpTiles.add(t); } ArrayList<Integer> uniqueX = new ArrayList<Integer>(); ArrayList<Integer> uniqueY = new ArrayList<Integer>(); ArrayList<Integer> uniqueZ = new ArrayList<Integer>(); ArrayList<Integer> uniqueC = new ArrayList<Integer>(); for (TileCoordinate t : tmpTiles) { if (!uniqueX.contains(t.coordinate[0])) { uniqueX.add(t.coordinate[0]); } if (!uniqueY.contains(t.coordinate[1])) { uniqueY.add(t.coordinate[1]); } if (t.coordinate.length > 3) { if (!uniqueZ.contains(t.coordinate[2])) { uniqueZ.add(t.coordinate[2]); } if (t.coordinate.length > 4) { if (!uniqueC.contains(t.coordinate[3])) { uniqueC.add(t.coordinate[3]); } } } } core[s].sizeX = tileX[s] * uniqueX.size(); core[s].sizeY = tileY[s] * uniqueY.size(); core[s].sizeZ = uniqueZ.size(); if (uniqueC.size() > 1) { core[s].sizeC *= uniqueC.size(); } core[s].sizeT = 1; if (core[s].sizeZ == 0) { core[s].sizeZ = 1; } core[s].imageCount = core[s].sizeZ * core[s].sizeT; if (uniqueC.size() > 1) { core[s].imageCount *= uniqueC.size(); } rows[s] = uniqueX.size(); cols[s] = uniqueY.size(); for (int i=0; i<tmpTiles.size(); i++) { tileMap[s].put(tmpTiles.get(i), i); } core[s].pixelType = convertPixelType(pixelType); etsFile.close(); }
private void parseETSFile(String file, int s) throws FormatException, IOException { RandomAccessInputStream etsFile = new RandomAccessInputStream(file); etsFile.order(true); // read the volume header String magic = etsFile.readString(4).trim(); if (!magic.equals("SIS")) { throw new FormatException("Unknown magic bytes: " + magic); } int headerSize = etsFile.readInt(); int version = etsFile.readInt(); nDimensions[s] = etsFile.readInt(); long additionalHeaderOffset = etsFile.readLong(); int additionalHeaderSize = etsFile.readInt(); etsFile.skipBytes(4); // reserved long usedChunkOffset = etsFile.readLong(); int nUsedChunks = etsFile.readInt(); etsFile.skipBytes(4); // reserved // read the additional header etsFile.seek(additionalHeaderOffset); String moreMagic = etsFile.readString(4).trim(); if (!moreMagic.equals("ETS")) { throw new FormatException("Unknown magic bytes: " + moreMagic); } etsFile.skipBytes(4); // extra version number int pixelType = etsFile.readInt(); core[s].sizeC = etsFile.readInt(); int colorspace = etsFile.readInt(); compressionType[s] = etsFile.readInt(); int compressionQuality = etsFile.readInt(); tileX[s] = etsFile.readInt(); tileY[s] = etsFile.readInt(); int tileZ = etsFile.readInt(); core[s].rgb = core[s].sizeC > 1; // read the used chunks etsFile.seek(usedChunkOffset); tileOffsets[s] = new Long[nUsedChunks]; ArrayList<TileCoordinate> tmpTiles = new ArrayList<TileCoordinate>(); for (int chunk=0; chunk<nUsedChunks; chunk++) { etsFile.skipBytes(4); TileCoordinate t = new TileCoordinate(nDimensions[s]); for (int i=0; i<nDimensions[s]; i++) { t.coordinate[i] = etsFile.readInt(); } tileOffsets[s][chunk] = etsFile.readLong(); int nBytes = etsFile.readInt(); etsFile.skipBytes(4); tmpTiles.add(t); } ArrayList<Integer> uniqueX = new ArrayList<Integer>(); ArrayList<Integer> uniqueY = new ArrayList<Integer>(); ArrayList<Integer> uniqueZ = new ArrayList<Integer>(); ArrayList<Integer> uniqueC = new ArrayList<Integer>(); for (TileCoordinate t : tmpTiles) { if (!uniqueX.contains(t.coordinate[0])) { uniqueX.add(t.coordinate[0]); } if (!uniqueY.contains(t.coordinate[1])) { uniqueY.add(t.coordinate[1]); } if (t.coordinate.length > 3) { if (!uniqueZ.contains(t.coordinate[2])) { uniqueZ.add(t.coordinate[2]); } if (t.coordinate.length > 4) { if (!uniqueC.contains(t.coordinate[3])) { uniqueC.add(t.coordinate[3]); } } } } core[s].sizeX = tileX[s] * uniqueX.size(); core[s].sizeY = tileY[s] * uniqueY.size(); core[s].sizeZ = uniqueZ.size(); if (uniqueC.size() > 1) { core[s].sizeC *= uniqueC.size(); } core[s].sizeT = 1; if (core[s].sizeZ == 0) { core[s].sizeZ = 1; } core[s].imageCount = core[s].sizeZ * core[s].sizeT; if (uniqueC.size() > 1) { core[s].imageCount *= uniqueC.size(); } rows[s] = uniqueY.size(); cols[s] = uniqueX.size(); for (int i=0; i<tmpTiles.size(); i++) { tileMap[s].put(tmpTiles.get(i), i); } core[s].pixelType = convertPixelType(pixelType); etsFile.close(); }
diff --git a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/external/proxy/event/ProxyDebugEvent.java b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/external/proxy/event/ProxyDebugEvent.java index 037dfdc3d..817cd8963 100644 --- a/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/external/proxy/event/ProxyDebugEvent.java +++ b/debug/org.eclipse.ptp.debug.sdm.core/src/org/eclipse/ptp/debug/external/proxy/event/ProxyDebugEvent.java @@ -1,196 +1,196 @@ /******************************************************************************* * Copyright (c) 2005 The Regents of the University of California. * This material was produced under U.S. Government contract W-7405-ENG-36 * for Los Alamos National Laboratory, which is operated by the University * of California for the U.S. Department of Energy. The U.S. Government has * rights to use, reproduce, and distribute this software. NEITHER THE * GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, 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 * * LA-CC 04-115 *******************************************************************************/ package org.eclipse.ptp.debug.external.proxy.event; import java.math.BigInteger; import org.eclipse.cdt.debug.core.cdi.ICDICondition; import org.eclipse.cdt.debug.core.cdi.ICDILineLocation; import org.eclipse.cdt.debug.core.cdi.ICDILocator; import org.eclipse.cdt.debug.core.cdi.model.ICDIBreakpoint; import org.eclipse.ptp.core.proxy.event.IProxyEvent; import org.eclipse.ptp.core.proxy.event.ProxyEvent; import org.eclipse.ptp.core.util.BitList; import org.eclipse.ptp.debug.external.ExtFormat; import org.eclipse.ptp.debug.external.aif.AIF; import org.eclipse.ptp.debug.external.aif.IAIF; import org.eclipse.ptp.debug.external.cdi.Condition; import org.eclipse.ptp.debug.external.cdi.Locator; import org.eclipse.ptp.debug.external.cdi.breakpoints.LineBreakpoint; import org.eclipse.ptp.debug.external.cdi.model.LineLocation; import org.eclipse.ptp.debug.external.proxy.ProxyDebugStackframe; public class ProxyDebugEvent extends ProxyEvent { public static IProxyEvent toEvent(String str) { IProxyDebugEvent evt = null; String[] args = str.split(" "); int type = Integer.parseInt(args[0]); BitList set = ProxyEvent.decodeBitSet(args[1]); switch (type) { case IProxyDebugEvent.EVENT_DBG_OK: evt = new ProxyDebugOKEvent(set); break; case IProxyDebugEvent.EVENT_DBG_ERROR: int errCode = Integer.parseInt(args[2]); evt = new ProxyDebugErrorEvent(set, errCode, decodeString(args[3])); break; case IProxyDebugEvent.EVENT_DBG_BPHIT: int hitId = Integer.parseInt(args[2]); evt = new ProxyDebugBreakpointHitEvent(set, hitId); break; case IProxyDebugEvent.EVENT_DBG_BPSET: int setId = Integer.parseInt(args[2]); ICDILineLocation loc = toLineLocation(args[8], args[11]); ICDIBreakpoint bpt = toBreakpoint(args[4], args[5], args[6], args[7], loc); evt = new ProxyDebugBreakpointSetEvent(set, setId, bpt); break; case IProxyDebugEvent.EVENT_DBG_SIGNAL: int sigTid = Integer.parseInt(args[4]); ICDILocator sigLoc = null; if (!(args[5].compareTo("*") == 0)) { sigLoc = toLocator(args[6], args[7], args[8], args[9]); } evt = new ProxyDebugSignalEvent(set, decodeString(args[2]), decodeString(args[3]), sigTid, sigLoc); break; case IProxyDebugEvent.EVENT_DBG_EXIT: int status = Integer.parseInt(args[2]); evt = new ProxyDebugExitEvent(set, status); break; case IProxyDebugEvent.EVENT_DBG_STEP: ProxyDebugStackframe frame = toFrame(args[2], args[3], args[4], args[6], args[5]); evt = new ProxyDebugStepEvent(set, frame); break; case IProxyDebugEvent.EVENT_DBG_FRAMES: int numFrames = Integer.parseInt(args[2]); ProxyDebugStackframe[] frames = new ProxyDebugStackframe[numFrames]; for (int i = 0; i < numFrames; i++) { int frameLevel = Integer.parseInt(args[5*i+3]); int line = Integer.parseInt(args[5*i+7]); frames[i] = new ProxyDebugStackframe(frameLevel, decodeString(args[5*i+4]), decodeString(args[5*i+5]), line, decodeString(args[5*i+6])); } evt = new ProxyDebugStackframeEvent(set, frames); break; case IProxyDebugEvent.EVENT_DBG_DATA: IAIF data = AIF.toAIF(args[2], args[3]); evt = new ProxyDebugDataEvent(set, data); break; case IProxyDebugEvent.EVENT_DBG_TYPE: - evt = new ProxyDebugTypeEvent(set, args[2]); + evt = new ProxyDebugTypeEvent(set, decodeString(args[2])); break; case IProxyDebugEvent.EVENT_DBG_VARS: int numVars = Integer.parseInt(args[2]); String[] vars = new String[numVars]; for (int i = 0; i < numVars; i++) { vars[i] = decodeString(args[i+3]); } evt = new ProxyDebugVarsEvent(set, vars); break; case IProxyDebugEvent.EVENT_DBG_ARGS: int numArgs = Integer.parseInt(args[2]); String[] arg_strs = new String[numArgs]; for (int i = 0; i < numArgs; i++) { arg_strs[i] = decodeString(args[i+3]); } evt = new ProxyDebugArgsEvent(set, arg_strs); break; case IProxyDebugEvent.EVENT_DBG_INIT: int num_servers = Integer.parseInt(args[2]); evt = new ProxyDebugInitEvent(set, num_servers); break; } return evt; } public static BigInteger decodeAddr(String str) { String[] parts = str.split(":"); int len = Integer.parseInt(parts[0], 16) - 1; // Skip trailing NULL byte[] strBytes = new byte[len]; for (int i = 0, p = 0; i < len; i++, p += 2) { byte c = (byte) ((Character.digit(parts[1].charAt(p), 16) & 0xf) << 4); c |= (byte) ((Character.digit(parts[1].charAt(p+1), 16) & 0xf)); strBytes[i] = c; } BigInteger a = new BigInteger(strBytes); return a; } public static ICDIBreakpoint toBreakpoint(String ignoreStr, String spec, String del, String typeStr, ICDILineLocation loc) { ICDIBreakpoint bpt = null; int typeVal; int ignore = Integer.parseInt(ignoreStr); ICDICondition cond = new Condition(ignore, null, null); String type = decodeString(typeStr); if (type.compareTo("breakpoint") == 0) typeVal = ICDIBreakpoint.REGULAR; else if (type.compareTo("hw") == 0) typeVal = ICDIBreakpoint.HARDWARE; else typeVal = ICDIBreakpoint.TEMPORARY; bpt = new LineBreakpoint(typeVal, loc, cond); return bpt; } public static ICDILineLocation toLineLocation(String fileStr, String lineStr) { String file = decodeString(fileStr); int line = Integer.parseInt(lineStr); return new LineLocation(file, line); } public static ICDILocator toLocator(String fileStr, String funcStr, String addrStr, String lineStr) { String file = decodeString(fileStr); String func = decodeString(funcStr); int line = Integer.parseInt(lineStr); String addr = decodeString(addrStr); return new Locator(file, func, line, ExtFormat.getBigInteger(addr)); } public static ProxyDebugStackframe toFrame(String level, String file, String func, String line, String addr) { int stepLevel = Integer.parseInt(level); int stepLine = Integer.parseInt(line); return new ProxyDebugStackframe(stepLevel, decodeString(file), decodeString(func), stepLine, decodeString(addr)); } }
true
true
public static IProxyEvent toEvent(String str) { IProxyDebugEvent evt = null; String[] args = str.split(" "); int type = Integer.parseInt(args[0]); BitList set = ProxyEvent.decodeBitSet(args[1]); switch (type) { case IProxyDebugEvent.EVENT_DBG_OK: evt = new ProxyDebugOKEvent(set); break; case IProxyDebugEvent.EVENT_DBG_ERROR: int errCode = Integer.parseInt(args[2]); evt = new ProxyDebugErrorEvent(set, errCode, decodeString(args[3])); break; case IProxyDebugEvent.EVENT_DBG_BPHIT: int hitId = Integer.parseInt(args[2]); evt = new ProxyDebugBreakpointHitEvent(set, hitId); break; case IProxyDebugEvent.EVENT_DBG_BPSET: int setId = Integer.parseInt(args[2]); ICDILineLocation loc = toLineLocation(args[8], args[11]); ICDIBreakpoint bpt = toBreakpoint(args[4], args[5], args[6], args[7], loc); evt = new ProxyDebugBreakpointSetEvent(set, setId, bpt); break; case IProxyDebugEvent.EVENT_DBG_SIGNAL: int sigTid = Integer.parseInt(args[4]); ICDILocator sigLoc = null; if (!(args[5].compareTo("*") == 0)) { sigLoc = toLocator(args[6], args[7], args[8], args[9]); } evt = new ProxyDebugSignalEvent(set, decodeString(args[2]), decodeString(args[3]), sigTid, sigLoc); break; case IProxyDebugEvent.EVENT_DBG_EXIT: int status = Integer.parseInt(args[2]); evt = new ProxyDebugExitEvent(set, status); break; case IProxyDebugEvent.EVENT_DBG_STEP: ProxyDebugStackframe frame = toFrame(args[2], args[3], args[4], args[6], args[5]); evt = new ProxyDebugStepEvent(set, frame); break; case IProxyDebugEvent.EVENT_DBG_FRAMES: int numFrames = Integer.parseInt(args[2]); ProxyDebugStackframe[] frames = new ProxyDebugStackframe[numFrames]; for (int i = 0; i < numFrames; i++) { int frameLevel = Integer.parseInt(args[5*i+3]); int line = Integer.parseInt(args[5*i+7]); frames[i] = new ProxyDebugStackframe(frameLevel, decodeString(args[5*i+4]), decodeString(args[5*i+5]), line, decodeString(args[5*i+6])); } evt = new ProxyDebugStackframeEvent(set, frames); break; case IProxyDebugEvent.EVENT_DBG_DATA: IAIF data = AIF.toAIF(args[2], args[3]); evt = new ProxyDebugDataEvent(set, data); break; case IProxyDebugEvent.EVENT_DBG_TYPE: evt = new ProxyDebugTypeEvent(set, args[2]); break; case IProxyDebugEvent.EVENT_DBG_VARS: int numVars = Integer.parseInt(args[2]); String[] vars = new String[numVars]; for (int i = 0; i < numVars; i++) { vars[i] = decodeString(args[i+3]); } evt = new ProxyDebugVarsEvent(set, vars); break; case IProxyDebugEvent.EVENT_DBG_ARGS: int numArgs = Integer.parseInt(args[2]); String[] arg_strs = new String[numArgs]; for (int i = 0; i < numArgs; i++) { arg_strs[i] = decodeString(args[i+3]); } evt = new ProxyDebugArgsEvent(set, arg_strs); break; case IProxyDebugEvent.EVENT_DBG_INIT: int num_servers = Integer.parseInt(args[2]); evt = new ProxyDebugInitEvent(set, num_servers); break; } return evt; }
public static IProxyEvent toEvent(String str) { IProxyDebugEvent evt = null; String[] args = str.split(" "); int type = Integer.parseInt(args[0]); BitList set = ProxyEvent.decodeBitSet(args[1]); switch (type) { case IProxyDebugEvent.EVENT_DBG_OK: evt = new ProxyDebugOKEvent(set); break; case IProxyDebugEvent.EVENT_DBG_ERROR: int errCode = Integer.parseInt(args[2]); evt = new ProxyDebugErrorEvent(set, errCode, decodeString(args[3])); break; case IProxyDebugEvent.EVENT_DBG_BPHIT: int hitId = Integer.parseInt(args[2]); evt = new ProxyDebugBreakpointHitEvent(set, hitId); break; case IProxyDebugEvent.EVENT_DBG_BPSET: int setId = Integer.parseInt(args[2]); ICDILineLocation loc = toLineLocation(args[8], args[11]); ICDIBreakpoint bpt = toBreakpoint(args[4], args[5], args[6], args[7], loc); evt = new ProxyDebugBreakpointSetEvent(set, setId, bpt); break; case IProxyDebugEvent.EVENT_DBG_SIGNAL: int sigTid = Integer.parseInt(args[4]); ICDILocator sigLoc = null; if (!(args[5].compareTo("*") == 0)) { sigLoc = toLocator(args[6], args[7], args[8], args[9]); } evt = new ProxyDebugSignalEvent(set, decodeString(args[2]), decodeString(args[3]), sigTid, sigLoc); break; case IProxyDebugEvent.EVENT_DBG_EXIT: int status = Integer.parseInt(args[2]); evt = new ProxyDebugExitEvent(set, status); break; case IProxyDebugEvent.EVENT_DBG_STEP: ProxyDebugStackframe frame = toFrame(args[2], args[3], args[4], args[6], args[5]); evt = new ProxyDebugStepEvent(set, frame); break; case IProxyDebugEvent.EVENT_DBG_FRAMES: int numFrames = Integer.parseInt(args[2]); ProxyDebugStackframe[] frames = new ProxyDebugStackframe[numFrames]; for (int i = 0; i < numFrames; i++) { int frameLevel = Integer.parseInt(args[5*i+3]); int line = Integer.parseInt(args[5*i+7]); frames[i] = new ProxyDebugStackframe(frameLevel, decodeString(args[5*i+4]), decodeString(args[5*i+5]), line, decodeString(args[5*i+6])); } evt = new ProxyDebugStackframeEvent(set, frames); break; case IProxyDebugEvent.EVENT_DBG_DATA: IAIF data = AIF.toAIF(args[2], args[3]); evt = new ProxyDebugDataEvent(set, data); break; case IProxyDebugEvent.EVENT_DBG_TYPE: evt = new ProxyDebugTypeEvent(set, decodeString(args[2])); break; case IProxyDebugEvent.EVENT_DBG_VARS: int numVars = Integer.parseInt(args[2]); String[] vars = new String[numVars]; for (int i = 0; i < numVars; i++) { vars[i] = decodeString(args[i+3]); } evt = new ProxyDebugVarsEvent(set, vars); break; case IProxyDebugEvent.EVENT_DBG_ARGS: int numArgs = Integer.parseInt(args[2]); String[] arg_strs = new String[numArgs]; for (int i = 0; i < numArgs; i++) { arg_strs[i] = decodeString(args[i+3]); } evt = new ProxyDebugArgsEvent(set, arg_strs); break; case IProxyDebugEvent.EVENT_DBG_INIT: int num_servers = Integer.parseInt(args[2]); evt = new ProxyDebugInitEvent(set, num_servers); break; } return evt; }
diff --git a/dev/core/src/com/google/gwt/dev/shell/jetty/JettyLauncher.java b/dev/core/src/com/google/gwt/dev/shell/jetty/JettyLauncher.java index 9a6b12b3e..c86aa77c6 100644 --- a/dev/core/src/com/google/gwt/dev/shell/jetty/JettyLauncher.java +++ b/dev/core/src/com/google/gwt/dev/shell/jetty/JettyLauncher.java @@ -1,256 +1,256 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.dev.shell.jetty; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.TreeLogger.Type; import com.google.gwt.dev.shell.ServletContainer; import com.google.gwt.dev.shell.ServletContainerLauncher; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.log.Log; import org.mortbay.log.Logger; import java.io.File; import javax.servlet.Filter; /** * A launcher for an embedded Jetty server. */ public class JettyLauncher implements ServletContainerLauncher { /** * An adapter for the Jetty logging system to GWT's TreeLogger. This * implementation class is only public to allow {@link Log} to instantiate it. * * The weird static data / default construction setup is a game we play with * {@link Log}'s static initializer to prevent the initial log message from * going to stderr. */ public static final class JettyTreeLogger implements Logger { private static Type nextBranchLevel; private static TreeLogger nextLogger; /** * Returns true if the default constructor can be called. */ public static boolean isDefaultConstructionReady() { return nextLogger != null; } /** * Call to set initial state for default construction; must be called again * each time before a default instantiation occurs. */ public static void setDefaultConstruction(TreeLogger logger, Type branchLevel) { if (logger == null || branchLevel == null) { throw new NullPointerException(); } nextLogger = logger; nextBranchLevel = branchLevel; } private final Type branchLevel; private final TreeLogger logger; public JettyTreeLogger() { this(nextLogger, nextBranchLevel); nextLogger = null; nextBranchLevel = null; } public JettyTreeLogger(TreeLogger logger, Type branchLevel) { if (logger == null || branchLevel == null) { throw new NullPointerException(); } this.branchLevel = branchLevel; this.logger = logger; } public void debug(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.DEBUG, format(msg, arg0, arg1)); } public void debug(String msg, Throwable th) { logger.log(TreeLogger.DEBUG, msg, th); } public Logger getLogger(String name) { return new JettyTreeLogger(logger.branch(branchLevel, name), branchLevel); } public void info(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.INFO, format(msg, arg0, arg1)); } public boolean isDebugEnabled() { return logger.isLoggable(TreeLogger.DEBUG); } public void setDebugEnabled(boolean enabled) { // ignored } public void warn(String msg, Object arg0, Object arg1) { logger.log(TreeLogger.WARN, format(msg, arg0, arg1)); } public void warn(String msg, Throwable th) { logger.log(TreeLogger.WARN, msg, th); } /** * Copied from org.mortbay.log.StdErrLog. */ private String format(String msg, Object arg0, Object arg1) { int i0 = msg.indexOf("{}"); int i1 = i0 < 0 ? -1 : msg.indexOf("{}", i0 + 2); if (arg1 != null && i1 >= 0) { msg = msg.substring(0, i1) + arg1 + msg.substring(i1 + 2); } if (arg0 != null && i0 >= 0) { msg = msg.substring(0, i0) + arg0 + msg.substring(i0 + 2); } return msg; } } private static class JettyServletContainer implements ServletContainer { private final int actualPort; private final File appRootDir; private final TreeLogger logger; private final WebAppContext wac; public JettyServletContainer(TreeLogger logger, WebAppContext wac, int actualPort, File appRootDir) { this.logger = logger; this.wac = wac; this.actualPort = actualPort; this.appRootDir = appRootDir; } public int getPort() { return actualPort; } public void refresh() throws UnableToCompleteException { String msg = "Reloading web app to reflect changes in " + appRootDir.getAbsolutePath(); TreeLogger branch = logger.branch(TreeLogger.INFO, msg); try { wac.stop(); } catch (Exception e) { branch.log(TreeLogger.ERROR, "Unable to stop embedded Jetty server", e); throw new UnableToCompleteException(); } try { wac.start(); } catch (Exception e) { branch.log(TreeLogger.ERROR, "Unable to stop embedded Jetty server", e); throw new UnableToCompleteException(); } branch.log(TreeLogger.INFO, "Reload completed successfully"); } public void stop() throws UnableToCompleteException { TreeLogger branch = logger.branch(TreeLogger.INFO, "Stopping Jetty server"); try { wac.stop(); } catch (Exception e) { branch.log(TreeLogger.ERROR, "Unable to stop embedded Jetty server", e); throw new UnableToCompleteException(); } branch.log(TreeLogger.INFO, "Stopped successfully"); } } @SuppressWarnings("unchecked") public ServletContainer start(TreeLogger logger, int port, File appRootDir, Filter shellServletFilter) throws UnableToCompleteException { checkStartParams(logger, port, appRootDir); // The dance we do with Jetty's logging system. System.setProperty("VERBOSE", "true"); JettyTreeLogger.setDefaultConstruction(logger, TreeLogger.INFO); System.setProperty("org.mortbay.log.class", JettyTreeLogger.class.getName()); // Force initialization. Log.isDebugEnabled(); if (JettyTreeLogger.isDefaultConstructionReady()) { // The log system was already initialized and did not use our // newly-constructed logger, set it explicitly now. Log.setLog(new JettyTreeLogger()); } Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); // Create a new web app in the war directory. WebAppContext wac = new WebAppContext(appRootDir.getAbsolutePath(), "/"); // Prevent file locking on windows; pick up file changes. wac.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); // Setup the shell servlet filter to generate nocache.js files (and run // the hosted mode linker stack. FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(shellServletFilter); wac.addFilter(filterHolder, "/*", Handler.ALL); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); - int actualPort = connector.getPort(); + int actualPort = connector.getLocalPort(); return new JettyServletContainer(logger, wac, actualPort, appRootDir); } catch (Exception e) { logger.log(TreeLogger.ERROR, "Unable to start embedded Jetty server", e); throw new UnableToCompleteException(); } } private void checkStartParams(TreeLogger logger, int port, File appRootDir) { if (logger == null) { throw new NullPointerException("logger cannot be null"); } if (port < 0 || port > 65535) { throw new IllegalArgumentException( "port must be either 0 (for auto) or less than 65536"); } if (appRootDir == null) { throw new NullPointerException("app root direcotry cannot be null"); } } }
true
true
public ServletContainer start(TreeLogger logger, int port, File appRootDir, Filter shellServletFilter) throws UnableToCompleteException { checkStartParams(logger, port, appRootDir); // The dance we do with Jetty's logging system. System.setProperty("VERBOSE", "true"); JettyTreeLogger.setDefaultConstruction(logger, TreeLogger.INFO); System.setProperty("org.mortbay.log.class", JettyTreeLogger.class.getName()); // Force initialization. Log.isDebugEnabled(); if (JettyTreeLogger.isDefaultConstructionReady()) { // The log system was already initialized and did not use our // newly-constructed logger, set it explicitly now. Log.setLog(new JettyTreeLogger()); } Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); // Create a new web app in the war directory. WebAppContext wac = new WebAppContext(appRootDir.getAbsolutePath(), "/"); // Prevent file locking on windows; pick up file changes. wac.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); // Setup the shell servlet filter to generate nocache.js files (and run // the hosted mode linker stack. FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(shellServletFilter); wac.addFilter(filterHolder, "/*", Handler.ALL); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); int actualPort = connector.getPort(); return new JettyServletContainer(logger, wac, actualPort, appRootDir); } catch (Exception e) { logger.log(TreeLogger.ERROR, "Unable to start embedded Jetty server", e); throw new UnableToCompleteException(); } }
public ServletContainer start(TreeLogger logger, int port, File appRootDir, Filter shellServletFilter) throws UnableToCompleteException { checkStartParams(logger, port, appRootDir); // The dance we do with Jetty's logging system. System.setProperty("VERBOSE", "true"); JettyTreeLogger.setDefaultConstruction(logger, TreeLogger.INFO); System.setProperty("org.mortbay.log.class", JettyTreeLogger.class.getName()); // Force initialization. Log.isDebugEnabled(); if (JettyTreeLogger.isDefaultConstructionReady()) { // The log system was already initialized and did not use our // newly-constructed logger, set it explicitly now. Log.setLog(new JettyTreeLogger()); } Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); // Create a new web app in the war directory. WebAppContext wac = new WebAppContext(appRootDir.getAbsolutePath(), "/"); // Prevent file locking on windows; pick up file changes. wac.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); // Setup the shell servlet filter to generate nocache.js files (and run // the hosted mode linker stack. FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(shellServletFilter); wac.addFilter(filterHolder, "/*", Handler.ALL); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); int actualPort = connector.getLocalPort(); return new JettyServletContainer(logger, wac, actualPort, appRootDir); } catch (Exception e) { logger.log(TreeLogger.ERROR, "Unable to start embedded Jetty server", e); throw new UnableToCompleteException(); } }
diff --git a/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/ShapeView.java b/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/ShapeView.java index d290b9485..a840d4c28 100644 --- a/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/ShapeView.java +++ b/flexodesktop/GUI/flexographicalengine/src/main/java/org/openflexo/fge/view/ShapeView.java @@ -1,586 +1,588 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.fge.view; import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.JLayeredPane; import javax.swing.SwingUtilities; import org.openflexo.fge.ConnectorGraphicalRepresentation; import org.openflexo.fge.DrawingGraphicalRepresentation; import org.openflexo.fge.FGEConstants; import org.openflexo.fge.GeometricGraphicalRepresentation; import org.openflexo.fge.GraphicalRepresentation; import org.openflexo.fge.ShapeGraphicalRepresentation; import org.openflexo.fge.controller.DrawingController; import org.openflexo.fge.controller.DrawingPalette; import org.openflexo.fge.notifications.FGENotification; import org.openflexo.fge.notifications.GraphicalRepresentationAdded; import org.openflexo.fge.notifications.GraphicalRepresentationDeleted; import org.openflexo.fge.notifications.GraphicalRepresentationRemoved; import org.openflexo.fge.notifications.ObjectHasMoved; import org.openflexo.fge.notifications.ObjectHasResized; import org.openflexo.fge.notifications.ObjectMove; import org.openflexo.fge.notifications.ObjectResized; import org.openflexo.fge.notifications.ObjectWillMove; import org.openflexo.fge.notifications.ObjectWillResize; import org.openflexo.fge.notifications.ShapeNeedsToBeRedrawn; import org.openflexo.fge.view.listener.ShapeViewMouseListener; public class ShapeView<O> extends FGELayeredView<O> { private static final Logger logger = Logger.getLogger(ShapeView.class.getPackage().getName()); private ShapeGraphicalRepresentation<O> graphicalRepresentation; private ShapeViewMouseListener mouseListener; private DrawingController _controller; private LabelView<O> _labelView; public ShapeView(ShapeGraphicalRepresentation<O> aGraphicalRepresentation, DrawingController<?> controller) { super(); logger.fine("Create ShapeView " + Integer.toHexString(hashCode()) + " for " + aGraphicalRepresentation); _controller = controller; graphicalRepresentation = aGraphicalRepresentation; graphicalRepresentation.finalizeConstraints(); updateLabelView(); relocateAndResizeView(); mouseListener = makeShapeViewMouseListener(); addMouseListener(mouseListener); addMouseMotionListener(mouseListener); getGraphicalRepresentation().addObserver(this); setOpaque(false); updateVisibility(); setFocusable(true); if (controller.getPalettes() != null) { for (DrawingPalette p : controller.getPalettes()) { registerPalette(p); } } // logger.info("make ShapeView with "+aGraphicalRepresentation+" bounds="+getBounds()); // setToolTipText(getClass().getSimpleName()+hashCode()); // System.out.println("isDoubleBuffered()="+isDoubleBuffered()); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent event) { if (event.getKeyCode() == KeyEvent.VK_UP) { getController().upKeyPressed(); event.consume(); return; } else if (event.getKeyCode() == KeyEvent.VK_DOWN) { getController().downKeyPressed(); event.consume(); return; } else if (event.getKeyCode() == KeyEvent.VK_RIGHT) { getController().rightKeyPressed(); event.consume(); return; } else if (event.getKeyCode() == KeyEvent.VK_LEFT) { getController().leftKeyPressed(); event.consume(); return; } } }); } public void disableFGEViewMouseListener() { System.out.println("Disable FGEViewMouseListener "); removeMouseListener(mouseListener); removeMouseMotionListener(mouseListener); } public void enableFGEViewMouseListener() { addMouseListener(mouseListener); addMouseMotionListener(mouseListener); } private boolean isDeleted = false; @Override public boolean isDeleted() { return isDeleted; } @Override public synchronized void delete() { logger.fine("Delete ShapeView " + Integer.toHexString(hashCode()) + " for " + getGraphicalRepresentation()); if (getParentView() != null) { FGELayeredView parentView = getParentView(); // logger.warning("Unexpected not null parent, proceeding anyway"); parentView.remove(this); parentView.revalidate(); if (getPaintManager() != null) { getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(parentView); } } if (getGraphicalRepresentation() != null) { getGraphicalRepresentation().deleteObserver(this); } setDropTarget(null); removeMouseListener(mouseListener); removeMouseMotionListener(mouseListener); if (_labelView != null) { _labelView.delete(); } _labelView = null; _controller = null; mouseListener = null; graphicalRepresentation = null; isDeleted = true; } @Override public O getModel() { return getDrawable(); } public O getDrawable() { return getGraphicalRepresentation().getDrawable(); } @Override public DrawingView<?> getDrawingView() { if (getController() != null) { return getController().getDrawingView(); } return null; } @Override public FGELayeredView getParent() { return (FGELayeredView) super.getParent(); } public FGELayeredView getParentView() { return getParent(); } @Override public ShapeGraphicalRepresentation<O> getGraphicalRepresentation() { return graphicalRepresentation; } public DrawingGraphicalRepresentation<?> getDrawingGraphicalRepresentation() { return graphicalRepresentation.getDrawingGraphicalRepresentation(); } @Override public double getScale() { return getController().getScale(); } @Override public void rescale() { relocateAndResizeView(); } private void relocateAndResizeView() { relocateView(); resizeView(); // System.out.println("relocateAndResizeView() for "+drawable+" bounds="+getBounds()); } private void relocateView() { if (getX() != getGraphicalRepresentation().getViewX(getScale()) || getY() != getGraphicalRepresentation().getViewY(getScale())) { if (_labelView != null) { _labelView.updateBounds(); } setLocation(getGraphicalRepresentation().getViewX(getScale()), getGraphicalRepresentation().getViewY(getScale())); } else { // logger.info("Ignore relocateView() because unchanged"); } } private void resizeView() { if (getWidth() != getGraphicalRepresentation().getViewWidth(getScale()) || getHeight() != getGraphicalRepresentation().getViewHeight(getScale())) { if (_labelView != null) { _labelView.updateBounds(); } setSize(getGraphicalRepresentation().getViewWidth(getScale()), getGraphicalRepresentation().getViewHeight(getScale())); } else { // logger.info("Ignore resizeView() because unchanged"); } } private void updateLayer() { if (getParent() instanceof JLayeredPane) { if (_labelView != null) { getParent().setLayer((Component) _labelView, getLayer()); getParent().setPosition(_labelView, getGraphicalRepresentation().getLayerOrder() * 2); } getParent().setLayer((Component) this, getLayer()); getParent().setPosition(this, getGraphicalRepresentation().getLayerOrder() * 2 + 1); } } private void updateVisibility() { if (_labelView != null) { _labelView.setVisible(getGraphicalRepresentation().shouldBeDisplayed()); } setVisible(getGraphicalRepresentation().shouldBeDisplayed()); } private void updateLabelView() { if (!getGraphicalRepresentation().getHasText() && _labelView != null) { _labelView.delete(); _labelView = null; } else if (getGraphicalRepresentation().getHasText() && _labelView == null) { _labelView = new LabelView<O>(getGraphicalRepresentation(), getController(), this); if (getParentView() != null) { getParentView().add(getLabelView(), getLayer(), -1); } } } public Integer getLayer() { return FGEConstants.INITIAL_LAYER + getGraphicalRepresentation().getLayer(); } @Override public void paint(Graphics g) { if (isDeleted()) { return; } if (getPaintManager().isPaintingCacheEnabled()) { if (getDrawingView().isBuffering()) { // Buffering painting if (getPaintManager().isTemporaryObject(getGraphicalRepresentation())) { // This object is declared to be a temporary object, to be redrawn // continuously, so we need to ignore it: do nothing if (FGEPaintManager.paintPrimitiveLogger.isLoggable(Level.FINE)) { FGEPaintManager.paintPrimitiveLogger.fine("ShapeView: buffering paint, ignore: " + getGraphicalRepresentation()); } } else { if (FGEPaintManager.paintPrimitiveLogger.isLoggable(Level.FINE)) { FGEPaintManager.paintPrimitiveLogger.fine("ShapeView: buffering paint, draw: " + getGraphicalRepresentation() + " clip=" + g.getClip()); } doPaint(g); } } else { if (!getPaintManager().renderUsingBuffer((Graphics2D) g, g.getClipBounds(), getGraphicalRepresentation(), getScale())) { doPaint(g); } /* // Use buffer Image buffer = getPaintManager().getPaintBuffer(); Rectangle localViewBounds = g.getClipBounds(); Rectangle viewBoundsInDrawingView = GraphicalRepresentation.convertRectangle(getGraphicalRepresentation(), localViewBounds, getDrawingGraphicalRepresentation(), getScale()); //System.out.println("SHAPEVIEW Paint buffer "+g.getClipBounds()); Point dp1 = localViewBounds.getLocation(); Point dp2 = new Point(localViewBounds.x+localViewBounds.width,localViewBounds.y+localViewBounds.height); Point sp1 = viewBoundsInDrawingView.getLocation(); Point sp2 = new Point(viewBoundsInDrawingView.x+viewBoundsInDrawingView.width,viewBoundsInDrawingView.y+viewBoundsInDrawingView.height); if (FGEPaintManager.paintPrimitiveLogger.isLoggable(Level.FINE)) FGEPaintManager.paintPrimitiveLogger.fine("ShapeView: use image buffer, copy area from "+sp1+"x"+sp2+" to "+dp1+"x"+dp2); g.drawImage(buffer, dp1.x,dp1.y,dp2.x,dp2.y, sp1.x,sp1.y,sp2.x,sp2.y, null); */ } } else { // Normal painting doPaint(g); } // getGraphicalRepresentation().paint(g,getController()); // super.paint(g); } private void doPaint(Graphics g) { getGraphicalRepresentation().paint(g, getController()); super.paint(g); } protected ShapeViewMouseListener makeShapeViewMouseListener() { return new ShapeViewMouseListener(graphicalRepresentation, this); } @Override public DrawingController<?> getController() { return _controller; } @Override public void update(final Observable o, final Object aNotification) { if (isDeleted) { logger.warning("Received notifications for deleted view: observable=" + o); return; } if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { update(o, aNotification); } }); } else { // logger.info("For "+getGraphicalRepresentation().getClass().getSimpleName()+" received: "+aNotification); if (aNotification instanceof FGENotification) { FGENotification notification = (FGENotification) aNotification; if (notification instanceof GraphicalRepresentationAdded) { GraphicalRepresentation<?> newGR = ((GraphicalRepresentationAdded) notification).getAddedGraphicalRepresentation(); logger.fine("ShapeView: Received ObjectAdded notification, creating view for " + newGR); if (newGR instanceof ShapeGraphicalRepresentation) { ShapeGraphicalRepresentation<?> shapeGR = (ShapeGraphicalRepresentation<?>) newGR; add(shapeGR.makeShapeView(getController())); revalidate(); getPaintManager().repaint(this); shapeGR.notifyShapeNeedsToBeRedrawn(); } else if (newGR instanceof ConnectorGraphicalRepresentation) { ConnectorGraphicalRepresentation<?> connectorGR = (ConnectorGraphicalRepresentation<?>) newGR; add(connectorGR.makeConnectorView(getController())); revalidate(); getPaintManager().repaint(this); } else if (newGR instanceof GeometricGraphicalRepresentation) { newGR.addObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationRemoved) { GraphicalRepresentation<?> removedGR = ((GraphicalRepresentationRemoved) notification) .getRemovedGraphicalRepresentation(); if (removedGR instanceof ShapeGraphicalRepresentation) { ShapeView<?> view = getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof ConnectorGraphicalRepresentation) { ConnectorView<?> view = getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof GeometricGraphicalRepresentation) { removedGR.deleteObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationDeleted) { GraphicalRepresentation<?> deletedGR = ((GraphicalRepresentationDeleted) notification) .getDeletedGraphicalRepresentation(); // If was not removed, try to do it now if (getGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation().contains(getGraphicalRepresentation())) { getGraphicalRepresentation().getContainerGraphicalRepresentation().notifyDrawableRemoved(deletedGR); } if (getGraphicalRepresentation() != null && getController().getFocusedObjects().contains(getGraphicalRepresentation())) { getController().removeFromFocusedObjects(getGraphicalRepresentation()); } if (getGraphicalRepresentation() != null && getController().getSelectedObjects().contains(getGraphicalRepresentation())) { getController().removeFromSelectedObjects(getGraphicalRepresentation()); } delete(); } else if (notification instanceof ObjectWillMove) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectMove) { relocateView(); if (getParentView() != null) { getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasMoved) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ObjectWillResize) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectResized) { resizeView(); if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasResized) { resizeView(); if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ShapeNeedsToBeRedrawn) { if (getPaintManager().isPaintingCacheEnabled()) { /*getPaintManager().resetTemporaryObjects(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView());*/ getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().repaint(this); } } else if (notification.getParameter() == GraphicalRepresentation.Parameters.layer) { updateLayer(); if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } getPaintManager().repaint(this); /*if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); }*/ } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isFocused) { // TODO: ugly hack, please fix this, implement a ForceRepaint in FGEPaintManager - getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); + if (getGraphicalRepresentation().getHasFocusedBackground() || getGraphicalRepresentation().getHasFocusedForeground()) { + getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); + } getPaintManager().repaint(this); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.hasText) { updateLabelView(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isSelected) { if (getParent() != null) { getParent().moveToFront(this); } if (getParent() != null && getLabelView() != null) { getParent().moveToFront(getLabelView()); } getPaintManager().repaint(this); requestFocusInWindow(); // requestFocus(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isVisible) { updateVisibility(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); } else { // revalidate(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); // revalidate(); // getPaintManager().repaint(this); } } else { revalidate(); getPaintManager().repaint(this); } } } @Override public LabelView<O> getLabelView() { return _labelView; } @Override public void registerPalette(DrawingPalette aPalette) { // A palette is registered, listen to drag'n'drop events setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY, aPalette.buildPaletteDropListener(this, _controller), true)); } @Override public FGEPaintManager getPaintManager() { return getDrawingView().getPaintManager(); } @Override public String getToolTipText(MouseEvent event) { return getController().getToolTipText(); } private BufferedImage screenshot; public BufferedImage getScreenshot() { if (screenshot == null) { captureScreenshot(); } return screenshot; } private void captureScreenshot() { JComponent lbl = this; getController().disablePaintingCache(); try { Rectangle bounds = new Rectangle(getBounds()); if (getLabelView() != null) { bounds = bounds.union(getLabelView().getBounds()); } screenshot = new BufferedImage(bounds.width, bounds.height, java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);// buffered image // reference passing // the label's ht // and width Graphics2D graphics = screenshot.createGraphics();// creating the graphics for buffered image graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); // Sets the Composite for the Graphics2D // context lbl.print(graphics); // painting the graphics to label /*if (this.getGraphicalRepresentation().getBackground() instanceof BackgroundImage) { graphics.drawImage(((BackgroundImage)this.getGraphicalRepresentation().getBackground()).getImage(),0,0,null); }*/ if (getLabelView() != null) { Rectangle r = getLabelView().getBounds(); getLabelView().print(graphics.create(r.x - bounds.x, r.y - bounds.y, r.width, r.height)); } graphics.dispose(); if (logger.isLoggable(Level.INFO)) { logger.info("Captured image on " + this); } } finally { getController().enablePaintingCache(); } } }
true
true
public void update(final Observable o, final Object aNotification) { if (isDeleted) { logger.warning("Received notifications for deleted view: observable=" + o); return; } if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { update(o, aNotification); } }); } else { // logger.info("For "+getGraphicalRepresentation().getClass().getSimpleName()+" received: "+aNotification); if (aNotification instanceof FGENotification) { FGENotification notification = (FGENotification) aNotification; if (notification instanceof GraphicalRepresentationAdded) { GraphicalRepresentation<?> newGR = ((GraphicalRepresentationAdded) notification).getAddedGraphicalRepresentation(); logger.fine("ShapeView: Received ObjectAdded notification, creating view for " + newGR); if (newGR instanceof ShapeGraphicalRepresentation) { ShapeGraphicalRepresentation<?> shapeGR = (ShapeGraphicalRepresentation<?>) newGR; add(shapeGR.makeShapeView(getController())); revalidate(); getPaintManager().repaint(this); shapeGR.notifyShapeNeedsToBeRedrawn(); } else if (newGR instanceof ConnectorGraphicalRepresentation) { ConnectorGraphicalRepresentation<?> connectorGR = (ConnectorGraphicalRepresentation<?>) newGR; add(connectorGR.makeConnectorView(getController())); revalidate(); getPaintManager().repaint(this); } else if (newGR instanceof GeometricGraphicalRepresentation) { newGR.addObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationRemoved) { GraphicalRepresentation<?> removedGR = ((GraphicalRepresentationRemoved) notification) .getRemovedGraphicalRepresentation(); if (removedGR instanceof ShapeGraphicalRepresentation) { ShapeView<?> view = getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof ConnectorGraphicalRepresentation) { ConnectorView<?> view = getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof GeometricGraphicalRepresentation) { removedGR.deleteObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationDeleted) { GraphicalRepresentation<?> deletedGR = ((GraphicalRepresentationDeleted) notification) .getDeletedGraphicalRepresentation(); // If was not removed, try to do it now if (getGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation().contains(getGraphicalRepresentation())) { getGraphicalRepresentation().getContainerGraphicalRepresentation().notifyDrawableRemoved(deletedGR); } if (getGraphicalRepresentation() != null && getController().getFocusedObjects().contains(getGraphicalRepresentation())) { getController().removeFromFocusedObjects(getGraphicalRepresentation()); } if (getGraphicalRepresentation() != null && getController().getSelectedObjects().contains(getGraphicalRepresentation())) { getController().removeFromSelectedObjects(getGraphicalRepresentation()); } delete(); } else if (notification instanceof ObjectWillMove) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectMove) { relocateView(); if (getParentView() != null) { getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasMoved) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ObjectWillResize) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectResized) { resizeView(); if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasResized) { resizeView(); if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ShapeNeedsToBeRedrawn) { if (getPaintManager().isPaintingCacheEnabled()) { /*getPaintManager().resetTemporaryObjects(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView());*/ getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().repaint(this); } } else if (notification.getParameter() == GraphicalRepresentation.Parameters.layer) { updateLayer(); if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } getPaintManager().repaint(this); /*if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); }*/ } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isFocused) { // TODO: ugly hack, please fix this, implement a ForceRepaint in FGEPaintManager getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().repaint(this); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.hasText) { updateLabelView(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isSelected) { if (getParent() != null) { getParent().moveToFront(this); } if (getParent() != null && getLabelView() != null) { getParent().moveToFront(getLabelView()); } getPaintManager().repaint(this); requestFocusInWindow(); // requestFocus(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isVisible) { updateVisibility(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); } else { // revalidate(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); // revalidate(); // getPaintManager().repaint(this); } } else { revalidate(); getPaintManager().repaint(this); } }
public void update(final Observable o, final Object aNotification) { if (isDeleted) { logger.warning("Received notifications for deleted view: observable=" + o); return; } if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { update(o, aNotification); } }); } else { // logger.info("For "+getGraphicalRepresentation().getClass().getSimpleName()+" received: "+aNotification); if (aNotification instanceof FGENotification) { FGENotification notification = (FGENotification) aNotification; if (notification instanceof GraphicalRepresentationAdded) { GraphicalRepresentation<?> newGR = ((GraphicalRepresentationAdded) notification).getAddedGraphicalRepresentation(); logger.fine("ShapeView: Received ObjectAdded notification, creating view for " + newGR); if (newGR instanceof ShapeGraphicalRepresentation) { ShapeGraphicalRepresentation<?> shapeGR = (ShapeGraphicalRepresentation<?>) newGR; add(shapeGR.makeShapeView(getController())); revalidate(); getPaintManager().repaint(this); shapeGR.notifyShapeNeedsToBeRedrawn(); } else if (newGR instanceof ConnectorGraphicalRepresentation) { ConnectorGraphicalRepresentation<?> connectorGR = (ConnectorGraphicalRepresentation<?>) newGR; add(connectorGR.makeConnectorView(getController())); revalidate(); getPaintManager().repaint(this); } else if (newGR instanceof GeometricGraphicalRepresentation) { newGR.addObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationRemoved) { GraphicalRepresentation<?> removedGR = ((GraphicalRepresentationRemoved) notification) .getRemovedGraphicalRepresentation(); if (removedGR instanceof ShapeGraphicalRepresentation) { ShapeView<?> view = getDrawingView().shapeViewForObject((ShapeGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof ConnectorGraphicalRepresentation) { ConnectorView<?> view = getDrawingView().connectorViewForObject((ConnectorGraphicalRepresentation<?>) removedGR); if (view != null) { remove(view); revalidate(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(this); } else { logger.warning("Cannot find view for " + removedGR); } } else if (removedGR instanceof GeometricGraphicalRepresentation) { removedGR.deleteObserver(this); revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof GraphicalRepresentationDeleted) { GraphicalRepresentation<?> deletedGR = ((GraphicalRepresentationDeleted) notification) .getDeletedGraphicalRepresentation(); // If was not removed, try to do it now if (getGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation() != null && getGraphicalRepresentation().getContainerGraphicalRepresentation().contains(getGraphicalRepresentation())) { getGraphicalRepresentation().getContainerGraphicalRepresentation().notifyDrawableRemoved(deletedGR); } if (getGraphicalRepresentation() != null && getController().getFocusedObjects().contains(getGraphicalRepresentation())) { getController().removeFromFocusedObjects(getGraphicalRepresentation()); } if (getGraphicalRepresentation() != null && getController().getSelectedObjects().contains(getGraphicalRepresentation())) { getController().removeFromSelectedObjects(getGraphicalRepresentation()); } delete(); } else if (notification instanceof ObjectWillMove) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectMove) { relocateView(); if (getParentView() != null) { getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasMoved) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ObjectWillResize) { if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); } } else if (notification instanceof ObjectResized) { resizeView(); if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); } } else if (notification instanceof ObjectHasResized) { resizeView(); if (getPaintManager().isPaintingCacheEnabled()) { getPaintManager().removeFromTemporaryObjects(getGraphicalRepresentation()); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView()); } } else if (notification instanceof ShapeNeedsToBeRedrawn) { if (getPaintManager().isPaintingCacheEnabled()) { /*getPaintManager().resetTemporaryObjects(); getPaintManager().invalidate(getGraphicalRepresentation()); getPaintManager().repaint(getParentView());*/ getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); getPaintManager().repaint(this); } } else if (notification.getParameter() == GraphicalRepresentation.Parameters.layer) { updateLayer(); if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } getPaintManager().repaint(this); /*if (getParentView() != null) { getParentView().revalidate(); getPaintManager().repaint(this); }*/ } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isFocused) { // TODO: ugly hack, please fix this, implement a ForceRepaint in FGEPaintManager if (getGraphicalRepresentation().getHasFocusedBackground() || getGraphicalRepresentation().getHasFocusedForeground()) { getPaintManager().addToTemporaryObjects(getGraphicalRepresentation()); } getPaintManager().repaint(this); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.hasText) { updateLabelView(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isSelected) { if (getParent() != null) { getParent().moveToFront(this); } if (getParent() != null && getLabelView() != null) { getParent().moveToFront(getLabelView()); } getPaintManager().repaint(this); requestFocusInWindow(); // requestFocus(); } else if (notification.getParameter() == GraphicalRepresentation.Parameters.isVisible) { updateVisibility(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); } else { // revalidate(); if (getPaintManager().isPaintingCacheEnabled()) { if (!getPaintManager().isTemporaryObjectOrParentIsTemporaryObject(getGraphicalRepresentation())) { getPaintManager().invalidate(getGraphicalRepresentation()); } } getPaintManager().repaint(this); // revalidate(); // getPaintManager().repaint(this); } } else { revalidate(); getPaintManager().repaint(this); } }
diff --git a/S2/TapeA_B.java b/S2/TapeA_B.java index 70b5aca..7ed8072 100644 --- a/S2/TapeA_B.java +++ b/S2/TapeA_B.java @@ -1,265 +1,264 @@ public class TapeA_B implements Tape { private Cell readhead; //private int repOkNb = -1; // not used private boolean nullNextEncountered; private boolean nullPreviousEncountered; private static final char B = ' '; // final variable for the Blank /** * @param : init : the string that represent the tape * @post : build a TapeA_B object, the readhead is the block * after the last char of init * raise an exception if init is null or contains char not allowed */ public TapeA_B(String init) throws Exception { // ensure something to transform in a tape if (init == null) throw new Exception(); // to ensure the position of the read head is after the last block of init String initB = init + " "; // initialisation readhead = null; Cell tempNew = null; int maxLength = initB.length (); int i = 0; char[] initChar = initB.toCharArray (); /** * building of the tape: * Inv: TODO * Var: TODO */ while(i < maxLength){ tempNew = new Cell(); testChar(initChar[i]); // throw exception if needed tempNew.content = initChar[i]; tempNew.previous = readhead; readhead = tempNew; if (readhead.previous != null) // first cell: previous doesn't exist readhead.previous.next = readhead; i++; } // finish the tape readhead.next = null; nullNextEncountered = true; nullPreviousEncountered = (readhead.previous == null); } /** * Test if the structure agreed the invariant of representation : * - characters are in the Gamma alphabet (from char n°32 to 126) * - no loop, linear course long the double linked list * - only one cell with a null previous and only one with a null next * - the readhead must be on the tape (not null) * - B zone (contains all the not blanc char) as little as possible * - B' (extended zone B with blanc at ends) zone as little as possible * @return : true, if the object agreed the invariant of representation * false, if not * TODO : invariant et variant de boucle */ public boolean repOk() { - // in case of already tested int test = 0; // ensure at least one block if (readhead == null) test++; // first search, to the left Cell tempNow = readhead.next; Cell tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e){ test++; } // ensure double linkage - if ((tempNow.previous != tempPast) || (tempNow != readhead)) + if ((tempNow.previous != tempPast) || (tempNow == readhead)) test++; tempPast = tempNow; tempNow = tempPast.next; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; // second search, to the right tempNow = readhead.previous; tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e) { test++; } // ensure double linkage - if ((tempNow.next != tempPast) || (tempNow != readhead)) + if ((tempNow.next != tempPast) || (tempNow == readhead)) test++; tempPast = tempNow; tempNow = tempPast.previous; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; return (test == 0); } /** * @pre: / * @post: true iff the symbol bellow the read head is 's'. * An exception is produced if 's' is not valid */ public boolean isSymbol(char s) throws Exception { testChar(s); return readhead.content == s; } /** * @pre: / * @post: replace the symbol bellow the read hind by 's'. * An exception is produced if 's' is not valid */ public void putSymbol(char s) throws Exception { testChar(s); readhead.content = s; } /** * @pre: TODO: nothing? * @post: move the read head to the cell on the left or do nothing if the * tape only contains a blank. * If the previous cell doesn't exist, create a new one with blank char. * If the read head is on the last cell which is blank (and is not * the only one), remove this cell. */ public void leftMove() { try { // case of basic tape with only one box with B inside if (nullNextEncountered && nullPreviousEncountered && isSymbol(B)) return; // case of we are leaving a end of the tape and it is B // so we have to delete the last box ton maintain the invariant if (nullNextEncountered && isSymbol(B)) readhead.previous.next = null; } catch (Exception e) { return; // problem with isSymbol: should not happen because the // symbol has been checked before (constructor or putSymbol) } // case of end of the tape and we have to go into the B territory if (nullPreviousEncountered){ readhead.previous = new Cell(); readhead.previous.next = readhead; } // normal case readhead = readhead.previous; nullPreviousEncountered = (readhead.previous == null); nullNextEncountered = false; } /** * @pre: TODO: nothing? * @post: move the read head to the cell on the right or do nothing if the * tape only contains a blank. * If the next cell doesn't exist, create a new one with blank char. * If the read head is on the first cell which is blank (and is not * the only one), remove this cell. */ public void rightMove() { try { // case of basic tape with only one box with B inside if (nullPreviousEncountered && nullNextEncountered && isSymbol(B)) return; // case of we are leaving a end of the tape and it is B // so we have to delete the last box ton maintain the invariant if (nullPreviousEncountered && isSymbol(B)) // readhead.previous == null readhead.next.previous = null; } catch (Exception e) { return; // problem with isSymbol: should not happen because the // symbol has been checked before (constructor or putSymbol) } // case of end of the tape and we have to go into the B territory if (nullNextEncountered){ readhead.next = new Cell(); readhead.next.previous = readhead; } // normal case readhead = readhead.next; nullNextEncountered = (readhead.next == null); nullPreviousEncountered = false; } /** * @pre: readhead valid and != null (always the case) * @post: return a String of the form alpha[s]beta with the content * of all char available on the tape. * The char bellow the read head is surrounded by brackets (s). * alpha is a suffixe of what is before the readhead * beta is a prefixe of what is after the readhead */ public String toString() { String answer = "[" + readhead.content + "]"; Cell temp; temp = readhead.next; /** * Inv: answer contains the string [s]beta' where beta' is the * string representation up to the previous cell of temp. * Var: at each steps, temp take the value of temp.next so temp * contains the first cell after readhead with the content * is not already in answer */ while (temp != null){ answer = answer + temp.content; temp = temp.next; } temp = readhead.previous; /** * Inv: answer contains the string alpha'[s]beta where alpha' is the * string representation up to the next cell of temp. * Var: at each steps, temp take the value of temp.previous so temp * contains the first cell before readhead with the content * is not already in answer */ while (temp != null){ answer = temp.content + answer; temp = temp.previous; } return answer; } /** * @pre: / * @post: a new Cell is created. The char is B (blank) by default */ private class Cell { char content = B; Cell next = null; Cell previous = null; // int checkedFor = -1; // not used public Cell() { } } /** * @pre: s is an ASCII char. * @post: throws an exception if the char is invalid (not between 32 and 126) */ private void testChar(char s) throws Exception { if ((int) s > 126 || (int) s < 32) { System.err.println ("Invalid char: '" + s + "'"); throw new Exception(); } } }
false
true
public boolean repOk() { // in case of already tested int test = 0; // ensure at least one block if (readhead == null) test++; // first search, to the left Cell tempNow = readhead.next; Cell tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e){ test++; } // ensure double linkage if ((tempNow.previous != tempPast) || (tempNow != readhead)) test++; tempPast = tempNow; tempNow = tempPast.next; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; // second search, to the right tempNow = readhead.previous; tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e) { test++; } // ensure double linkage if ((tempNow.next != tempPast) || (tempNow != readhead)) test++; tempPast = tempNow; tempNow = tempPast.previous; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; return (test == 0); }
public boolean repOk() { int test = 0; // ensure at least one block if (readhead == null) test++; // first search, to the left Cell tempNow = readhead.next; Cell tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e){ test++; } // ensure double linkage if ((tempNow.previous != tempPast) || (tempNow == readhead)) test++; tempPast = tempNow; tempNow = tempPast.next; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; // second search, to the right tempNow = readhead.previous; tempPast = readhead; while (tempNow != null && test == 0) { // ensure an available char try { testChar(tempNow.content); } catch (Exception e) { test++; } // ensure double linkage if ((tempNow.next != tempPast) || (tempNow == readhead)) test++; tempPast = tempNow; tempNow = tempPast.previous; } // test if there is not too much blanc at the end (B' as little as possible) if (test == 0 && tempPast != readhead && tempPast.content == B) test++; return (test == 0); }
diff --git a/src/main/java/me/desht/portablehole/PortableHolePlugin.java b/src/main/java/me/desht/portablehole/PortableHolePlugin.java index 80505a4..48c7a4d 100644 --- a/src/main/java/me/desht/portablehole/PortableHolePlugin.java +++ b/src/main/java/me/desht/portablehole/PortableHolePlugin.java @@ -1,198 +1,198 @@ package me.desht.portablehole; /* This file is part of PortableHole PortableHole 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. PortableHole 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 PortableHole. If not, see <http://www.gnu.org/licenses/>. */ import java.util.HashSet; import java.util.List; import java.util.Set; import me.desht.dhutils.Cost; import me.desht.dhutils.DHUtilsException; import me.desht.dhutils.LogUtils; import me.desht.dhutils.MiscUtil; import me.desht.dhutils.commands.CommandManager; import me.desht.portablehole.commands.GiveCommand; import me.desht.portablehole.commands.InfoCommand; import me.desht.portablehole.commands.ReloadCommand; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; public class PortableHolePlugin extends JavaPlugin { private HoleManager holeManager; private CreditManager creditManager; private final CommandManager cmds = new CommandManager(this); private Economy economy; private Permission permission; private final Set<String> validAuthors = new HashSet<String>(); private final Set<String> validGroups = new HashSet<String>(); private static PortableHolePlugin instance = null; public void onEnable() { LogUtils.init(this); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(new PortableholeEventListener(this), this); setupVault(pm); registerCommands(); this.getConfig().options().copyDefaults(true); - this.getConfig().options().header("See http://dev.bukkit.org/server-mods/portablehole/configuration"); + this.getConfig().options().header("See http://dev.bukkit.org/server-mods/portablehole/pages/configuration"); this.saveConfig(); holeManager = new HoleManager(); creditManager = new CreditManager(this); creditManager.loadCredits(); processConfig(); instance = this; } public void onDisable() { // shut down any open holes, restoring the original blocks for (Hole h : holeManager.getHoles()) { h.close(true); } creditManager.saveCredits(); instance = null; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { return cmds.dispatch(sender, command.getName(), args); } catch (DHUtilsException e) { MiscUtil.errorMessage(sender, e.getMessage()); return true; } } private void setupVault(PluginManager pm) { Plugin vault = pm.getPlugin("Vault"); if (vault != null && vault instanceof net.milkbowl.vault.Vault) { LogUtils.fine("Loaded Vault v" + vault.getDescription().getVersion()); if (!setupEconomy()) { LogUtils.warning("No economy plugin detected - economy cost type not available"); } else { Cost.setEconomy(economy); } if (!setupPermission()) { LogUtils.warning("No permission plugin detected - author group checking disabled"); } LogUtils.warning("Vault not loaded: no economy support"); } } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } private boolean setupPermission() { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } return (permission != null); } public static PortableHolePlugin getInstance() { return instance; } public HoleManager getHoleManager() { return holeManager; } public CreditManager getCreditManager() { return creditManager; } private void registerCommands() { cmds.registerCommand(new InfoCommand()); cmds.registerCommand(new ReloadCommand()); cmds.registerCommand(new GiveCommand()); } private void setValidAuthors(List<String> authors) { validAuthors.clear(); for (String a : authors) { validAuthors.add(a); } } private void setValidGroups(List<String> groups) { validGroups.clear(); for (String a : groups) { validGroups.add(a); } } public Set<String> getValidAuthors() { return validAuthors; } public Set<String> getValidGroups() { return validGroups; } public void processConfig() { Hole.initMaterials(this); setValidAuthors(getConfig().getStringList("author_validation.players")); setValidGroups(getConfig().getStringList("author_validation.groups")); String level = getConfig().getString("log_level"); try { LogUtils.setLogLevel(level); } catch (IllegalArgumentException e) { LogUtils.warning("invalid log level " + level + " - ignored"); } getCreditManager().loadCosts(); } public Permission getPermissionHandler() { return permission; } public String getMessage(String key) { return getConfig().getString("messages." + key); } }
true
true
public void onEnable() { LogUtils.init(this); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(new PortableholeEventListener(this), this); setupVault(pm); registerCommands(); this.getConfig().options().copyDefaults(true); this.getConfig().options().header("See http://dev.bukkit.org/server-mods/portablehole/configuration"); this.saveConfig(); holeManager = new HoleManager(); creditManager = new CreditManager(this); creditManager.loadCredits(); processConfig(); instance = this; }
public void onEnable() { LogUtils.init(this); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(new PortableholeEventListener(this), this); setupVault(pm); registerCommands(); this.getConfig().options().copyDefaults(true); this.getConfig().options().header("See http://dev.bukkit.org/server-mods/portablehole/pages/configuration"); this.saveConfig(); holeManager = new HoleManager(); creditManager = new CreditManager(this); creditManager.loadCredits(); processConfig(); instance = this; }
diff --git a/src/game/PublicGameInfo.java b/src/game/PublicGameInfo.java index d0ff724..a6fadda 100644 --- a/src/game/PublicGameInfo.java +++ b/src/game/PublicGameInfo.java @@ -1,959 +1,961 @@ /* Open Meerkat Testbed. An open source implementation of the Meerkat API for running poker games Copyright (C) 2010 Dan Schatzberg 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 game; import java.util.ArrayList; import java.util.List; import util.Utils; import com.biotools.meerkat.Action; import com.biotools.meerkat.GameInfo; import com.biotools.meerkat.GameObserver; import com.biotools.meerkat.Hand; import com.biotools.meerkat.HandEvaluator; import com.biotools.meerkat.Holdem; import common.handeval.klaatu.PartialStageFastEval; public class PublicGameInfo implements GameInfo { /** * this action-Type is used to inform observers about the return * of uncalled bets.<br> * We need this for the history-writer - if this information is missing * Holdem-Manager gets confused */ public static final int SPECIAL_ACTION_RETURNUNCALLEDBET = 100; //limit definitions public static final int FIXED_LIMIT = 0; public static final int POT_LIMIT = 1; public static final int NO_LIMIT = 2; private boolean reverseBlinds = false; private boolean simulation = false; private boolean zipMode = false; private int buttonSeat = -1; private int smallBlindSeat = -1; private int bigBlindSeat = -1; private int toAct = 0; //next player to act (-1 if no one to act) private int numRaises = 0; //number of raises THIS ROUND private int numWinners = 0; private int stage = 0; private int limit = 0; private double bet = 0.0D; private double ante = 0.0D; private double smallBlind = 0.0D; private double bigBlind = 0.0D; private double minRaise = 0.0D; private long gameID = 0L; private PotManager potManager; private String logDirectory = ""; private Hand boardCards = null; private PublicPlayerInfo[] players = new PublicPlayerInfo[0]; private List<GameObserver> gameObservers = new ArrayList<GameObserver>(); private int lastToAct = 0; private int lastAggressor = -1; public PublicGameInfo() { HandEvaluator.setHandEval(new HandEvalImpl()); } @Override public boolean canRaise(int seat) { return hasPlayerInSeat(seat) && getPlayer(seat).hasEnoughToRaise(); } @Override public double getAmountToCall(int seat) { double highestAmount = 0.0D; if (!isActive(seat)) { return 0; } for (int i = 0; i < this.players.length; i++) if (isCommitted(i)) highestAmount = Math.max(highestAmount, getPlayer(i).getAmountInPotThisRound()); double toCall = Utils.roundToCents(highestAmount - getPlayer(seat).getAmountInPotThisRound()); if (toCall > getPlayer(seat).getBankRoll()) { toCall = getPlayer(seat).getBankRoll(); } return toCall; } @Override public double getAnte() { return this.ante; } @Override public double getBankRoll(int seat) { return hasPlayerInSeat(seat) ? getPlayer(seat).getBankRoll() : 0.0D; } @Override public double getBankRollAtRisk(int seat) { double biggestBankroll = 0.0D; for (int i = 0; i < getNumSeats(); i++) biggestBankroll = Math.max(biggestBankroll, getBankRoll(i)); return Math.min(biggestBankroll, getBankRoll(seat)); } @Override public double getBetsToCall(int seat) { return isValidSeat(seat) ? getAmountToCall(seat) / getCurrentBetSize() : 0.0D; } @Override public int getBigBlindSeat() { return bigBlindSeat; } @Override public double getBigBlindSize() { return this.bigBlind; } @Override public Hand getBoard() { return this.boardCards; //I wonder if this is OK. Can't anyone modify the board through this method? } @Override public int getButtonSeat() { return this.buttonSeat; } @Override public double getCurrentBetSize() { return isFixedLimit() ? this.bet : 0.0D; } @Override public int getCurrentPlayerSeat() { return this.toAct; } @Override public double getEligiblePot(int seat) { if(!isActive(seat)) return 0.0D; double eligiblePot = 0.0D; for (int i = 0; i < getNumSeats(); i++) if(i != seat) eligiblePot += Math.min(getPlayer(i).getAmountInPot(),getPlayer(seat).getAmountInPot() + getBankRoll(seat)); eligiblePot += getPlayer(seat).getAmountInPot(); return eligiblePot; } @Override public long getGameID() { return this.gameID; } @Override public String getLogDirectory() { return this.logDirectory; } @Override public double getMainPotSize() { return potManager.getPot(0).getValue(); } @Override public double getMinRaise() { return this.minRaise; } @Override public int getNumActivePlayers() { int active = 0; for (int i = 0; i < getNumSeats(); i++) if (isActive(i)) active++; return active; } @Override public int getNumActivePlayersNotAllIn() { int active = 0; for (int i = 0; i < getNumSeats(); i++) if (isActive(i) && !getPlayer(i).isAllIn()) active++; return active; } @Override public int getNumPlayers() { int num = 0; for (int i = 0; i < getNumSeats(); i++) if (hasPlayerInSeat(i)) num++; return num; } @Override public int getNumRaises() { return this.numRaises; } @Override public int getNumSeats() { return this.players.length; } @Override public int getNumSidePots() { return this.potManager.getNumPots() - 1; } @Override public int getNumToAct() { if (this.toAct == -1) { return 0; } int currentToAct = this.toAct; int numToAct = 0; numToAct++; // currentPlayer always counts as 'toAct' if (isPreFlop()) { if (!getPlayer(getSmallBlindSeat()).hasActedThisRound()) { currentToAct++; numToAct++; } if (!getPlayer(getBigBlindSeat()).hasActedThisRound()) { currentToAct++; numToAct++; } } while (currentToAct != this.lastToAct && currentToAct != -1) { currentToAct = nextActivePlayer(currentToAct); if (!getPlayer(currentToAct).isAllIn()) { numToAct++; } } return numToAct; } @Override public int getNumWinners() { return this.numWinners; } @Override public int getNumberOfAllInPlayers() { int allin = 0; for (int i = 0; i < getNumSeats(); i++) if (isValidSeat(i) && getPlayer(i).isAllIn()) allin++; return allin; } @Override public PublicPlayerInfo getPlayer(int seat) { return isValidSeat(seat) ? this.players[seat] : null; } @Override public PublicPlayerInfo getPlayer(String name) { for (int i = 0; i < getNumSeats(); i++) if (hasPlayerInSeat(i) && players[i].getName() == name) return getPlayer(i); return null; } @Override public String getPlayerName(int seat) { if (hasPlayerInSeat(seat)) return getPlayer(seat).getName(); return null; } @Override public int getPlayerSeat(String name) { for (int i = 0; i < getNumSeats(); i++) if (name.equals(getPlayerName(i))) return i; return -1; } @Override public List<PublicPlayerInfo> getPlayersInPot(double potSize) { List<PublicPlayerInfo> list = new ArrayList<PublicPlayerInfo>(); for (int i = 0; i < getNumSeats(); i++) if (isActive(i) && getPlayer(i).getAmountInPot() >= potSize) list.add(getPlayer(i)); return list; } @Override //Rake on a per-hand basis is not implemented yet public double getRake() { return 0.0D; } @Override //index 0 is the first side pot public double getSidePotSize(int index) { if (index < 0 || index >= getNumSidePots()) return 0.0D; return this.potManager.getPot(index + 1).getValue(); } @Override public int getSmallBlindSeat() { return smallBlindSeat; } @Override public double getSmallBlindSize() { return this.smallBlind; } @Override public int getStage() { return this.stage; } @Override //Meerkat is also really ambiguous about this method. I took it to mean the maximum amount a player put in the pot prior to this round. //This would be equal to the amount a player had to put into the pot to be active and not all-in this round. public double getStakes() { double stakes = 0.0D; for (int i = 0; i < getNumSeats(); i++) stakes = Math.max(stakes, getPlayer(i).getAmountInPot() - getPlayer(i).getAmountInPotThisRound()); return stakes; } @Override public double getTotalPotSize() { return potManager.getTotalPotSize(); } @Override public int getUnacted() { int unacted = 0; for (int i = 0; i < getNumSeats(); i++) if (hasPlayerInSeat(i) && !getPlayer(i).hasActedThisRound()) unacted++; return unacted; } @Override public boolean inGame(int seat) { return hasPlayerInSeat(seat) && getPlayer(seat).inGame(); } @Override public boolean isActive(int seat) { return hasPlayerInSeat(seat) && getPlayer(seat).isActive(); } @Override public boolean isCommitted(int seat) { return hasPlayerInSeat(seat) && getPlayer(seat).isCommitted(); } @Override public boolean isFixedLimit() { return this.limit == PublicGameInfo.FIXED_LIMIT; } @Override public boolean isFlop() { return this.stage == Holdem.FLOP; } @Override public boolean isGameOver() { return getNumWinners() != 0; } @Override public boolean isNoLimit() { return this.limit == PublicGameInfo.NO_LIMIT; } @Override public boolean isPostFlop() { return this.stage == Holdem.FLOP || this.stage == Holdem.TURN || this.stage == Holdem.RIVER || this.stage == Holdem.SHOWDOWN; } @Override public boolean isPotLimit() { return this.limit == PublicGameInfo.POT_LIMIT; } @Override public boolean isPreFlop() { return this.stage == Holdem.PREFLOP; } @Override public boolean isReverseBlinds() { return this.reverseBlinds; } @Override public boolean isRiver() { return this.stage == Holdem.RIVER; } @Override public boolean isSimulation() { return this.simulation; } @Override public boolean isTurn() { return this.stage == Holdem.TURN; } @Override public boolean isZipMode() { return this.zipMode; } @Override public int nextActivePlayer(int seat) { if (!isValidSeat(seat) || getNumActivePlayers() <= 0) return -1; int i; for (i = nextPlayer(seat); i != seat && !isActive(i); i = nextPlayer(i)) ; return i != seat ? i : -1; } /** * return the next active player, or -1 of noone is active behind the current seat * @param seat * @return */ public int nextActivePlayerNotAllIn(int seat) { if (!isValidSeat(seat) || getNumActivePlayersNotAllIn() <= 0) return -1; int i; for (i = nextPlayer(seat); i != seat && (!isActive(i) || getPlayer(i).isAllIn()); i = nextPlayer(i)) ; return i != seat ? i : -1; } @Override public int nextPlayer(int seat) { if (!isValidSeat(seat) || getNumPlayers() <= 0) return -1; int i; for (i = nextSeat(seat); i != seat && !hasPlayerInSeat(i); i = nextSeat(i)) ; return i; } @Override public int nextSeat(int seat) { return !isValidSeat(seat) ? -1 : (seat + 1) % getNumSeats(); } public int previousSeat(int seat) { return !isValidSeat(seat) ? -1 : (seat + getNumSeats() - 1) % getNumSeats(); } @Override public int previousPlayer(int seat) { if (!isValidSeat(seat) || getNumPlayers() <= 0) return -1; int i; for (i = previousSeat(seat); i != seat && !hasPlayerInSeat(i); i = previousSeat(i)) ; return i; } public int previousActivePlayer(int seat) { if (!isValidSeat(seat) || getNumPlayers() <= 0) return -1; int i; for (i = previousSeat(seat); i != seat && !isActive(i); i = previousSeat(i)) ; return i; } public int previousActivePlayerNotAllIn(int seat) { if (!isValidSeat(seat) || getNumPlayers() <= 0) return -1; int i; for (i = previousSeat(seat); i != seat && (!isActive(i) || getPlayer(i).isAllIn()); i = previousSeat(i)) ; return i; } /** * Whether or not seat is a valid seat number. * @param seat * @return */ private boolean isValidSeat(int seat) { return (seat >= 0) && (seat < getNumSeats()); } private boolean hasPlayerInSeat(int seat) { return getPlayer(seat) != null; } public void setReverseBlinds(boolean rev) { this.reverseBlinds = rev; } public void setSimulation(boolean sim) { this.simulation = sim; } public void setZipMode(boolean zip) { this.zipMode = zip; } public void setNumSeats(int numSeats) { this.players = new PublicPlayerInfo[numSeats]; } public void setLimit(int lim) { this.limit = lim; } public void setAnte(double ant) { this.ante = ant; } public void setBlinds(double sb, double bb) { this.smallBlind = sb; this.bigBlind = bb; } public void setGameID(long gid) { this.gameID = gid; } public void setLogDirectory(String logDir) { this.logDirectory = logDir; } //I think here is the best place to advance the round, increase bet size if necessary, etc. public void nextStage(Hand cardsToAddToBoard) { if (getNumActivePlayersNotAllIn() <= 1) { removeUncalledBetFromPot(); Pot lastPot = potManager.getPot(potManager.getNumPots() - 1); List<Integer> playersContestingPot = getPlayersContestingPot(lastPot); for (Integer seat : playersContestingPot) { playerShowDown(seat); } this.toAct = -1; this.lastToAct = -1; } else { this.toAct = nextActivePlayerNotAllIn(getButtonSeat()); this.lastToAct = previousActivePlayerNotAllIn(this.toAct); // button could be at an inactive Player } this.lastAggressor = -1; getBoard().addHand(cardsToAddToBoard); this.stage = nextStage(getStage()); if (isTurn() && isFixedLimit()) this.bet = getBigBlindSize() * 2; for (int i = 0; i < getNumSeats(); i++) { if (hasPlayerInSeat(i)) getPlayer(i).newRound(); } observersFireStageEvent(); } public void newHand(int buttonSeat, int smallBlindSeat, int bigBlindSeat) { this.buttonSeat = buttonSeat; this.smallBlindSeat = smallBlindSeat; this.bigBlindSeat = bigBlindSeat; this.toAct = smallBlindSeat; this.lastToAct = smallBlindSeat; // as long as noone called, the SB is last to act this.lastAggressor = -1; this.numRaises = 0; this.numWinners = 0; this.stage = Holdem.PREFLOP; if (isFixedLimit()) this.bet = getBigBlindSize(); this.minRaise = getBigBlindSize(); this.potManager = new PotManager(this); for (int i = 0; i < getNumSeats(); i++) if (hasPlayerInSeat(i)) { getPlayer(i).newHand(); } this.boardCards = new Hand(); observersFireGameStartEvent(); observersFireStageEvent(); } /** * determines the winner and pays him the money. * if needed cards are put to showdown */ public void payout() { removeUncalledBetFromPot(); // for each pot (starting with the highest) we determine the winner for (int currentPotID = potManager.getNumPots() - 1; currentPotID >= 0; currentPotID--) { Pot currentPot = potManager.getPot(currentPotID); List<Integer> playersContestingPot = getPlayersContestingPot(currentPot); if (playersContestingPot.size() == 1) { getPlayer(playersContestingPot.get(0)).wonHand(currentPot.getValue()); observersFireWin(playersContestingPot.get(0), currentPot.getValue(), ""); } else { // in the order of contestants check the final handrank int bestHandRank = -1; List<Integer> winners = new ArrayList<Integer>(); for (Integer seat : playersContestingPot) { PublicPlayerInfo player = getPlayer(seat); Hand playerHand = player.getHand(); int rank = HandEvaluator.rankHand(playerHand.getFirstCard(), playerHand.getSecondCard(), boardCards); if (rank > bestHandRank) { // this player is better than the last - make him showdown his cards // and make him single winner winners.clear(); winners.add(seat); playerShowDown(seat); bestHandRank = rank; } else if (rank == bestHandRank) { // this player has the same handrank - make him showdown and add him // to the winners winners.add(seat); playerShowDown(seat); } else { // this player sucks and can't beat the players before him // he just mucks, if he didn't had to show his cards // earlier if (player.getRevealedHand() == null) { observersFireActionEvent(seat, Action.muckAction()); observersFireGameStateChangedEvent(); } } } distributeWinMoney(currentPot.getValue(), winners, PartialStageFastEval.handString(bestHandRank)); } } observersFireGameOverEvent(); } /** * the last raiser might have been uncalled (or called but the other player didn't have * enough money).<br> * His uncalled bet needs to be returned, before we look at winnings */ private void removeUncalledBetFromPot() { if (lastAggressor != -1) { double amountInPotLastAggressor = getPlayer(lastAggressor).getAmountInPotThisRound(); double highestOther = 0; for (int i = 0; i < getNumSeats(); i++) { if (i != lastAggressor && getPlayer(i) != null && getPlayer(i).getAmountInPotThisRound() > highestOther) { highestOther = getPlayer(i).getAmountInPotThisRound(); } } double returnedMoney = Utils.roundToCents(amountInPotLastAggressor - highestOther); if (returnedMoney > 0) { potManager.removeFromPot(lastAggressor, returnedMoney); getPlayer(lastAggressor).putMoney(-returnedMoney); observersFireActionEvent(lastAggressor, new Action(SPECIAL_ACTION_RETURNUNCALLEDBET, 0, returnedMoney)); } } } /** * makes the player at the corresponding seat show his cards.<br> * All observers are informed.<br> * It is save to call this method multiple times - if the player * already showed his cards this is not done twice * @param seat */ private void playerShowDown(Integer seat) { PublicPlayerInfo player = getPlayer(seat); if (player.getRevealedHand() == null) { Hand playerHand = player.getHand(); observersFireHandShown(seat, playerHand); player.showCards(true); } } /** * distributes the amount to the given List of winners, updates the PlayerInfos and * sends events to the observers.<br> * if the amount cannot be distributed equally (say 5 cent for 3 winners), the remaining * cents are distributed in order of the winners (2-2-1 for the example given above). * @param amount * @param winners * @param handString */ private void distributeWinMoney(double amount, List<Integer> winners, String handString) { double amountForEachWinner = amount / winners.size(); // round amount to proper cents amountForEachWinner = Math.floor(amountForEachWinner * 100) / 100D; int extraCents = (int) ((amount - amountForEachWinner * winners.size()) * 100); for (Integer winSeat : winners) { PublicPlayerInfo winPlayer = getPlayer(winSeat); double amountWon = amountForEachWinner; if (extraCents-- > 0) { amountWon += 0.01; } winPlayer.wonHand(amountWon); observersFireWin(winSeat, amountWon, handString); } } /** * gets a list of seat-IDs of all players still contesting the given pot * (i.e. all players eligible to the pot, that haven't folded yet).<br> * The seats are ordered clockwise with the last aggressor (raiser or bettor) first. * If in the current round there was no aggressor the first seat after the button is used. * This order is the typical showdown order * @param pot * @return */ private List<Integer> getPlayersContestingPot(Pot pot) { List<Integer> playersContestingPot = new ArrayList<Integer>(); // get the player to start the showdown with int startShowDownWith = this.lastAggressor; if (startShowDownWith == -1) { startShowDownWith = nextActivePlayer(buttonSeat); } if (pot.isEligible(startShowDownWith) && !getPlayer(startShowDownWith).isFolded()) { playersContestingPot.add(startShowDownWith); } // and then get all players clockwise for (int seat = nextActivePlayer(startShowDownWith); seat != startShowDownWith && seat != -1; seat = nextActivePlayer(seat)) { if (pot.isEligible(seat) && !getPlayer(seat).isFolded()) { playersContestingPot.add(seat); } } return playersContestingPot; } public void update(Action act, int s) { //UNFINISHED act = correctPlayerErrors(act, s); if (s != getCurrentPlayerSeat()) throw new IllegalArgumentException("Not players turn to act"); if (act.isAllInPass()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isAnte()) { potManager.addToPot(s, getAnte()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isBet()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isBigBlind()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); + this.lastAggressor = s; } else if (act.isCall()) { //TO DO: check if call amount < amount to call and split pots potManager.addToPot(s, act.getToCall()); getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); // if someone calls preflop, the bigblind gets a chance to act if (stage == Holdem.PREFLOP && lastToAct == smallBlindSeat && numRaises == 0) { lastToAct = bigBlindSeat; } } else if (act.isCheck()) { getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isFold()) { getPlayer(s).update(act); if (getNumToAct() == 1) { //This player is the last to act, nextStage must be called this.toAct = -1; } else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isMuck()) { //What should we do with this? } else if (act.isRaise()) { potManager.addToPot(s, act.getAmount() + act.getToCall()); getPlayer(s).update(act); this.numRaises++; this.toAct = nextActivePlayerNotAllIn(s); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isSitout()) { getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isSmallBlind()) { potManager.addToPot(s, getSmallBlindSize()); getPlayer(s).update(act); this.toAct = bigBlindSeat; + this.lastAggressor = s; } else { throw new IllegalArgumentException("Invalid action, possibly unimplemented"); } observersFireActionEvent(s, act); observersFireGameStateChangedEvent(); } /** * checks if the given action is appropriate. * if not (i.e. amounts to high compared to bankroll) it is adjusted to the most similar valid action.<br> * * This is needed because otherwise we get invalid states (like negative bankrolls) - we also don't want * to stop the simulation because of errors. * @param act * @param s * @return */ private Action correctPlayerErrors(Action act, int s) { PublicPlayerInfo player=getPlayer(s); if (act.isCall()) { if (act.getAmount() > player.getBankRoll()) { return Action.callAction(player.getBankRoll()); } } else if (act.isRaise()) { if (Utils.roundToCents(act.getAmount() + act.getToCall()) > player.getBankRoll()) { if (getAmountToCall(s) > player.getBankRoll()) { return Action.callAction(player.getBankRoll()); } else { double raise = Utils.roundToCents(player.getBankRoll() - getAmountToCall(s)); return Action.raiseAction(getAmountToCall(s), raise); } } } return act; } //This method will split the pots up as necessary to the winner(s) protected void handOutWinnings() { //TO DO: implement } private int nextStage(int s) { if (s == Holdem.PREFLOP) return Holdem.FLOP; if (s == Holdem.FLOP) return Holdem.TURN; if (s == Holdem.TURN) return Holdem.RIVER; return -1; } public boolean isRoundOver() { return getCurrentPlayerSeat() == -1; } /** * puts a player to the corresponding seat and informs the player about his this GameInfo.<br> * Please note that a single PlayerInfo-Object cannot be seated at multiple tables * * @param seat * @param player */ public void setPlayer(int seat, PublicPlayerInfo player) { if (!isValidSeat(seat)) { throw new IllegalArgumentException("can't put player on seat " + seat + " is noone put a chair there yet ;).\nCall setNumSeats before"); } if (hasPlayerInSeat(seat)) { throw new IllegalArgumentException("can't put player in seat " + seat + ". Seat is not empty."); } if (player.getGameInfo() != null) { throw new IllegalArgumentException("this player-(object) is already sitting on another table"); } this.players[seat] = player; if (player.getBot() != null) { this.gameObservers.add(player.getBot()); } player.setGame(this); } public void addGameObserver(GameObserver observer) { this.gameObservers.add(observer); } public PotManager getPotManager() { return potManager; } private void observersFireGameStartEvent() { for (GameObserver gameObserver : gameObservers) { gameObserver.gameStartEvent(this); } } private void observersFireStageEvent() { for (GameObserver gameObserver : gameObservers) { gameObserver.stageEvent(this.stage); } } private void observersFireActionEvent(int seat, Action action) { for (GameObserver gameObserver : gameObservers) { gameObserver.actionEvent(seat, action); } } private void observersFireGameStateChangedEvent() { for (GameObserver gameObserver : gameObservers) { gameObserver.gameStateChanged(); } } public void observersFireDealHoleCardsEvent() { for (GameObserver gameObserver : gameObservers) { gameObserver.dealHoleCardsEvent(); } } public void observersFireGameOverEvent() { for (GameObserver gameObserver : gameObservers) { gameObserver.gameOverEvent(); } } public void observersFireWin(int seat, double amount, String hand) { for (GameObserver gameObserver : gameObservers) { gameObserver.winEvent(seat, amount, hand); } } public void observersFireHandShown(int seat, Hand hand) { for (GameObserver gameObserver : gameObservers) { gameObserver.showdownEvent(seat, hand.getFirstCard(), hand.getSecondCard()); } } }
false
true
public void update(Action act, int s) { //UNFINISHED act = correctPlayerErrors(act, s); if (s != getCurrentPlayerSeat()) throw new IllegalArgumentException("Not players turn to act"); if (act.isAllInPass()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isAnte()) { potManager.addToPot(s, getAnte()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isBet()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isBigBlind()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isCall()) { //TO DO: check if call amount < amount to call and split pots potManager.addToPot(s, act.getToCall()); getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); // if someone calls preflop, the bigblind gets a chance to act if (stage == Holdem.PREFLOP && lastToAct == smallBlindSeat && numRaises == 0) { lastToAct = bigBlindSeat; } } else if (act.isCheck()) { getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isFold()) { getPlayer(s).update(act); if (getNumToAct() == 1) { //This player is the last to act, nextStage must be called this.toAct = -1; } else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isMuck()) { //What should we do with this? } else if (act.isRaise()) { potManager.addToPot(s, act.getAmount() + act.getToCall()); getPlayer(s).update(act); this.numRaises++; this.toAct = nextActivePlayerNotAllIn(s); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isSitout()) { getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isSmallBlind()) { potManager.addToPot(s, getSmallBlindSize()); getPlayer(s).update(act); this.toAct = bigBlindSeat; } else { throw new IllegalArgumentException("Invalid action, possibly unimplemented"); } observersFireActionEvent(s, act); observersFireGameStateChangedEvent(); }
public void update(Action act, int s) { //UNFINISHED act = correctPlayerErrors(act, s); if (s != getCurrentPlayerSeat()) throw new IllegalArgumentException("Not players turn to act"); if (act.isAllInPass()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isAnte()) { potManager.addToPot(s, getAnte()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); } else if (act.isBet()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isBigBlind()) { potManager.addToPot(s, act.getAmount()); getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(getCurrentPlayerSeat()); this.lastAggressor = s; } else if (act.isCall()) { //TO DO: check if call amount < amount to call and split pots potManager.addToPot(s, act.getToCall()); getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); // if someone calls preflop, the bigblind gets a chance to act if (stage == Holdem.PREFLOP && lastToAct == smallBlindSeat && numRaises == 0) { lastToAct = bigBlindSeat; } } else if (act.isCheck()) { getPlayer(s).update(act); if (getNumToAct() == 1) //This player is the last to act, nextStage must be called or showdown this.toAct = -1; else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isFold()) { getPlayer(s).update(act); if (getNumToAct() == 1) { //This player is the last to act, nextStage must be called this.toAct = -1; } else this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isMuck()) { //What should we do with this? } else if (act.isRaise()) { potManager.addToPot(s, act.getAmount() + act.getToCall()); getPlayer(s).update(act); this.numRaises++; this.toAct = nextActivePlayerNotAllIn(s); this.lastToAct = previousActivePlayer(s); this.lastAggressor = s; } else if (act.isSitout()) { getPlayer(s).update(act); this.toAct = nextActivePlayerNotAllIn(s); } else if (act.isSmallBlind()) { potManager.addToPot(s, getSmallBlindSize()); getPlayer(s).update(act); this.toAct = bigBlindSeat; this.lastAggressor = s; } else { throw new IllegalArgumentException("Invalid action, possibly unimplemented"); } observersFireActionEvent(s, act); observersFireGameStateChangedEvent(); }
diff --git a/tests/org.bonitasoft.studio.importer.bar.tests/src/org/bonitasoft/studio/importer/bar/tests/messagesImport/CorrelationMigrationTest.java b/tests/org.bonitasoft.studio.importer.bar.tests/src/org/bonitasoft/studio/importer/bar/tests/messagesImport/CorrelationMigrationTest.java index e4fa2afdd5..5f9d631b7c 100644 --- a/tests/org.bonitasoft.studio.importer.bar.tests/src/org/bonitasoft/studio/importer/bar/tests/messagesImport/CorrelationMigrationTest.java +++ b/tests/org.bonitasoft.studio.importer.bar.tests/src/org/bonitasoft/studio/importer/bar/tests/messagesImport/CorrelationMigrationTest.java @@ -1,72 +1,72 @@ /** * Copyright (C) 2012 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * 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.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.importer.bar.tests.messagesImport; import java.io.File; import java.net.URL; import java.util.List; import junit.framework.TestCase; import org.bonitasoft.studio.common.emf.tools.ModelHelper; import org.bonitasoft.studio.common.jface.FileActionDialog; import org.bonitasoft.studio.importer.bar.tests.BarImporterTestUtil; import org.bonitasoft.studio.model.process.MainProcess; import org.bonitasoft.studio.model.process.Message; import org.bonitasoft.studio.model.process.MessageFlow; import org.bonitasoft.studio.model.process.ProcessPackage; import org.eclipse.core.runtime.FileLocator; import org.eclipse.emf.ecore.resource.Resource; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class CorrelationMigrationTest extends TestCase { private static boolean disablepopup; @BeforeClass public static void disablePopup(){ disablepopup = FileActionDialog.getDisablePopup(); FileActionDialog.setDisablePopup(true); } @AfterClass public static void resetdisablePopup(){ FileActionDialog.setDisablePopup(disablepopup); } @Test public void testImportMessage59Bar() throws Exception{ - URL fileURL2 = FileLocator.toFileURL(CorrelationMigrationTest.class.getResource("sendMessage-1.0.bar")); //$NON-NLS-1$ + URL fileURL2 = FileLocator.toFileURL(CorrelationMigrationTest.class.getResource("sendMessage--1.0.bar")); //$NON-NLS-1$ File migratedProcess = BarImporterTestUtil.migrateBar(fileURL2); assertNotNull("Fail to migrate bar file", migratedProcess); assertNotNull("Fail to migrate bar file", migratedProcess.exists()); final Resource resource = BarImporterTestUtil.assertIsLoadable(migratedProcess); final MainProcess mainProcess = BarImporterTestUtil.getMainProcess(resource); final List<MessageFlow> messageFlows = ModelHelper.getAllItemsOfType(mainProcess, ProcessPackage.Literals.MESSAGE_FLOW); assertTrue("main Process should contains 1 messageFlow at least",!messageFlows.isEmpty()); final MessageFlow flow = messageFlows.get(0); final Message message = ModelHelper.findEvent(flow.getTarget(), flow.getName()); assertNotNull("correlation should exist",message.getCorrelation()); assertEquals("2 correlation key should be defined",2,message.getCorrelation().getCorrelationAssociation().getExpressions().size()); } }
true
true
public void testImportMessage59Bar() throws Exception{ URL fileURL2 = FileLocator.toFileURL(CorrelationMigrationTest.class.getResource("sendMessage-1.0.bar")); //$NON-NLS-1$ File migratedProcess = BarImporterTestUtil.migrateBar(fileURL2); assertNotNull("Fail to migrate bar file", migratedProcess); assertNotNull("Fail to migrate bar file", migratedProcess.exists()); final Resource resource = BarImporterTestUtil.assertIsLoadable(migratedProcess); final MainProcess mainProcess = BarImporterTestUtil.getMainProcess(resource); final List<MessageFlow> messageFlows = ModelHelper.getAllItemsOfType(mainProcess, ProcessPackage.Literals.MESSAGE_FLOW); assertTrue("main Process should contains 1 messageFlow at least",!messageFlows.isEmpty()); final MessageFlow flow = messageFlows.get(0); final Message message = ModelHelper.findEvent(flow.getTarget(), flow.getName()); assertNotNull("correlation should exist",message.getCorrelation()); assertEquals("2 correlation key should be defined",2,message.getCorrelation().getCorrelationAssociation().getExpressions().size()); }
public void testImportMessage59Bar() throws Exception{ URL fileURL2 = FileLocator.toFileURL(CorrelationMigrationTest.class.getResource("sendMessage--1.0.bar")); //$NON-NLS-1$ File migratedProcess = BarImporterTestUtil.migrateBar(fileURL2); assertNotNull("Fail to migrate bar file", migratedProcess); assertNotNull("Fail to migrate bar file", migratedProcess.exists()); final Resource resource = BarImporterTestUtil.assertIsLoadable(migratedProcess); final MainProcess mainProcess = BarImporterTestUtil.getMainProcess(resource); final List<MessageFlow> messageFlows = ModelHelper.getAllItemsOfType(mainProcess, ProcessPackage.Literals.MESSAGE_FLOW); assertTrue("main Process should contains 1 messageFlow at least",!messageFlows.isEmpty()); final MessageFlow flow = messageFlows.get(0); final Message message = ModelHelper.findEvent(flow.getTarget(), flow.getName()); assertNotNull("correlation should exist",message.getCorrelation()); assertEquals("2 correlation key should be defined",2,message.getCorrelation().getCorrelationAssociation().getExpressions().size()); }
diff --git a/src/java/org/wings/plaf/css/ProgressBarCG.java b/src/java/org/wings/plaf/css/ProgressBarCG.java index 45cf4ac9..6e80f0ab 100644 --- a/src/java/org/wings/plaf/css/ProgressBarCG.java +++ b/src/java/org/wings/plaf/css/ProgressBarCG.java @@ -1,134 +1,144 @@ // DO NOT EDIT! Your changes will be lost: generated from '/home/hengels/jdevel/wings/src/org/wings/plaf/css1/ProgressBar.plaf' /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * Please see COPYING for the complete licence. */ package org.wings.plaf.css; import org.wings.*; import org.wings.io.Device; import org.wings.plaf.CGManager; import java.io.IOException; public class ProgressBarCG extends AbstractComponentCG implements SConstants, org.wings.plaf.ProgressBarCG { //--- byte array converted template snippets. public void installCG(final SComponent comp) { final SProgressBar component = (SProgressBar) comp; final CGManager manager = component.getSession().getCGManager(); Object value; Object previous; value = manager.getObject("SProgressBar.borderColor", java.awt.Color.class); if (value != null) { component.setBorderColor((java.awt.Color) value); } value = manager.getObject("SProgressBar.filledColor", java.awt.Color.class); if (value != null) { component.setFilledColor((java.awt.Color) value); } value = manager.getObject("SProgressBar.foreground", java.awt.Color.class); if (value != null) { component.setForeground((java.awt.Color) value); } value = manager.getObject("SProgressBar.preferredSize", SDimension.class); if (value != null) { component.setPreferredSize((SDimension) value); } value = manager.getObject("SProgressBar.unfilledColor", java.awt.Color.class); if (value != null) { component.setUnfilledColor((java.awt.Color) value); } } public void uninstallCG(final SComponent comp) { } //--- code from common area in template. private static final SIcon BLIND_ICON = new SResourceIcon("org/wings/icons/blind.gif"); //--- end code from common area in template. public void writeContent(final Device device, final SComponent _c) throws IOException { final SProgressBar component = (SProgressBar) _c; //--- code from write-template. String style = component.getStyle(); SDimension size = component.getPreferredSize(); int width = size != null ? size.getIntWidth() : 200; int height = size != null ? size.getIntHeight() : 5; if (component.isStringPainted()) { device.print("<table><tr><td>"); } if (component.isBorderPainted()) { device.print("<table cellpadding=\"1\"><tr><td"); Utils.optAttribute(device, "bgcolor", component.getBorderColor()); device.print(">"); } device.print("<table>"); device.print("<tr>"); device.print("<td"); - Utils.optAttribute(device, "bgcolor", component.getFilledColor()); + //Utils.optAttribute(device, "bgcolor", component.getFilledColor()); + if (component.getFilledColor() != null) { + device.print(" style=\"background-color: "); + Utils.write(device, component.getFilledColor()); + device.print(";\""); + } device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * component.getPercentComplete())); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\"></td>"); device.print("<td"); - Utils.optAttribute(device, "bgcolor", component.getUnfilledColor()); + //Utils.optAttribute(device, "bgcolor", component.getUnfilledColor()); + if (component.getUnfilledColor() != null) { + device.print(" style=\"background-color: "); + Utils.write(device, component.getUnfilledColor()); + device.print(";\""); + } device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * (1 - component.getPercentComplete()))); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\">"); device.print("</td>"); device.print("</tr>"); device.print("</table>"); if (component.isBorderPainted()) { device.print("</td></tr></table>"); } if (component.isStringPainted()) { device.print("</td></tr><tr><td align=\"center\">"); if (style != null) { device.print("<span class=\""); Utils.write(device, style); device.print("\">"); } Utils.write(device, component.getString()); if (style != null) { device.print("</span>"); } device.print("</td></tr></table>"); } //--- end code from write-template. } }
false
true
public void writeContent(final Device device, final SComponent _c) throws IOException { final SProgressBar component = (SProgressBar) _c; //--- code from write-template. String style = component.getStyle(); SDimension size = component.getPreferredSize(); int width = size != null ? size.getIntWidth() : 200; int height = size != null ? size.getIntHeight() : 5; if (component.isStringPainted()) { device.print("<table><tr><td>"); } if (component.isBorderPainted()) { device.print("<table cellpadding=\"1\"><tr><td"); Utils.optAttribute(device, "bgcolor", component.getBorderColor()); device.print(">"); } device.print("<table>"); device.print("<tr>"); device.print("<td"); Utils.optAttribute(device, "bgcolor", component.getFilledColor()); device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * component.getPercentComplete())); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\"></td>"); device.print("<td"); Utils.optAttribute(device, "bgcolor", component.getUnfilledColor()); device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * (1 - component.getPercentComplete()))); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\">"); device.print("</td>"); device.print("</tr>"); device.print("</table>"); if (component.isBorderPainted()) { device.print("</td></tr></table>"); } if (component.isStringPainted()) { device.print("</td></tr><tr><td align=\"center\">"); if (style != null) { device.print("<span class=\""); Utils.write(device, style); device.print("\">"); } Utils.write(device, component.getString()); if (style != null) { device.print("</span>"); } device.print("</td></tr></table>"); } //--- end code from write-template. }
public void writeContent(final Device device, final SComponent _c) throws IOException { final SProgressBar component = (SProgressBar) _c; //--- code from write-template. String style = component.getStyle(); SDimension size = component.getPreferredSize(); int width = size != null ? size.getIntWidth() : 200; int height = size != null ? size.getIntHeight() : 5; if (component.isStringPainted()) { device.print("<table><tr><td>"); } if (component.isBorderPainted()) { device.print("<table cellpadding=\"1\"><tr><td"); Utils.optAttribute(device, "bgcolor", component.getBorderColor()); device.print(">"); } device.print("<table>"); device.print("<tr>"); device.print("<td"); //Utils.optAttribute(device, "bgcolor", component.getFilledColor()); if (component.getFilledColor() != null) { device.print(" style=\"background-color: "); Utils.write(device, component.getFilledColor()); device.print(";\""); } device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * component.getPercentComplete())); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\"></td>"); device.print("<td"); //Utils.optAttribute(device, "bgcolor", component.getUnfilledColor()); if (component.getUnfilledColor() != null) { device.print(" style=\"background-color: "); Utils.write(device, component.getUnfilledColor()); device.print(";\""); } device.print(">"); device.print("<img"); Utils.optAttribute(device, "src", BLIND_ICON.getURL()); device.print(" width=\""); device.print(String.valueOf(width * (1 - component.getPercentComplete()))); device.print("\""); device.print(" height=\""); device.print(String.valueOf(height)); device.print("\">"); device.print("</td>"); device.print("</tr>"); device.print("</table>"); if (component.isBorderPainted()) { device.print("</td></tr></table>"); } if (component.isStringPainted()) { device.print("</td></tr><tr><td align=\"center\">"); if (style != null) { device.print("<span class=\""); Utils.write(device, style); device.print("\">"); } Utils.write(device, component.getString()); if (style != null) { device.print("</span>"); } device.print("</td></tr></table>"); } //--- end code from write-template. }
diff --git a/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java b/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java index 51336a6..f666d86 100755 --- a/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java +++ b/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java @@ -1,24 +1,24 @@ package com.drtshock.willie.command.misc; import com.drtshock.willie.Willie; import com.drtshock.willie.command.Command; import com.drtshock.willie.command.CommandHandler; import org.pircbotx.Channel; import org.pircbotx.User; public class HelpCommandHandler implements CommandHandler { @Override public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly()) { - if (channel.getOps().contains(sender)) { + if (bot.getConfig().getAdmins().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } } }
true
true
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly()) { if (channel.getOps().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } }
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly()) { if (bot.getConfig().getAdmins().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } }
diff --git a/cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java b/cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java index 84b673e..0171b28 100644 --- a/cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java +++ b/cal10n-api/src/main/java/ch/qos/cal10n/verifier/MessageKeyVerifier.java @@ -1,180 +1,180 @@ /* * Copyright (c) 2009 QOS.ch All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ch.qos.cal10n.verifier; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import ch.qos.cal10n.Cal10nConstants; import ch.qos.cal10n.util.AnnotationExtractor; import ch.qos.cal10n.util.CAL10NResourceBundleFinder; import ch.qos.cal10n.util.MiscUtil; import ch.qos.cal10n.verifier.Cal10nError.ErrorType; /** * Given an enum class, verify that the resource bundles corresponding to a * given locale contains the correct keys. * * @author Ceki Gulcu */ public class MessageKeyVerifier implements IMessageKeyVerifier { Class<? extends Enum<?>> enumType; String enumTypeAsStr; public MessageKeyVerifier(Class<? extends Enum<?>> enumClass) { this.enumType = enumClass; this.enumTypeAsStr = enumClass.getName(); } @SuppressWarnings("unchecked") public MessageKeyVerifier(String enumTypeAsStr) { this.enumTypeAsStr = enumTypeAsStr; String errMsg = "Failed to find enum class [" + enumTypeAsStr + "]"; try { this.enumType = (Class<? extends Enum<?>>) Class.forName(enumTypeAsStr); } catch (ClassNotFoundException e) { throw new IllegalStateException(errMsg, e); } catch (NoClassDefFoundError e) { throw new IllegalStateException(errMsg, e); } } public Class<? extends Enum<?>> getEnumType() { return enumType; } public String getEnumTypeAsStr() { return enumTypeAsStr; } public List<Cal10nError> verify(Locale locale) { List<Cal10nError> errorList = new ArrayList<Cal10nError>(); String baseName = AnnotationExtractor.getBaseName(enumType); if (baseName == null) { errorList.add(new Cal10nError(ErrorType.MISSING_BN_ANNOTATION, "", enumType, locale, "")); // no point in continuing return errorList; } - String charset = AnnotationExtractor.getCharset(enumType, Locale.FRENCH); + String charset = AnnotationExtractor.getCharset(enumType, locale); ResourceBundle rb = CAL10NResourceBundleFinder.getBundle(this.getClass() .getClassLoader(), baseName, locale, charset); ErrorFactory errorFactory = new ErrorFactory(enumType, locale, baseName); if (rb == null) { errorList.add(errorFactory.buildError(ErrorType.FAILED_TO_FIND_RB, "")); // no point in continuing return errorList; } Set<String> rbKeySet = buildKeySetFromEnumeration(rb.getKeys()); if (rbKeySet.size() == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_RB, "")); } Enum<?>[] enumArray = enumType.getEnumConstants(); if (enumArray == null || enumArray.length == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_ENUM, "")); } if (errorList.size() != 0) { return errorList; } for (Enum<?> e : enumArray) { String enumKey = e.toString(); if (rbKeySet.contains(enumKey)) { rbKeySet.remove(enumKey); } else { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_RB, enumKey)); } } for (String rbKey : rbKeySet) { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_ENUM, rbKey)); } return errorList; } private Set<String> buildKeySetFromEnumeration(Enumeration<String> e) { Set<String> set = new HashSet<String>(); while (e.hasMoreElements()) { String s = e.nextElement(); set.add(s); } return set; } public List<String> typeIsolatedVerify(Locale locale) { List<Cal10nError> errorList = verify(locale); List<String> strList = new ArrayList<String>(); for (Cal10nError error : errorList) { strList.add(error.toString()); } return strList; } /*** * Verify all declared locales in one step. */ public List<Cal10nError> verifyAllLocales() { List<Cal10nError> errorList = new ArrayList<Cal10nError>(); String[] localeNameArray = getLocaleNames(); if (localeNameArray == null || localeNameArray.length == 0) { String errMsg = MessageFormat.format(Cal10nConstants.MISSING_LD_ANNOTATION_MESSAGE, enumTypeAsStr); throw new IllegalStateException(errMsg); } for (String localeName : localeNameArray) { Locale locale = MiscUtil.toLocale(localeName); List<Cal10nError> tmpList = verify(locale); errorList.addAll(tmpList); } return errorList; } public String[] getLocaleNames() { String[] localeNameArray = AnnotationExtractor.getLocaleNames(enumType); return localeNameArray; } public String getBaseName() { String rbName = AnnotationExtractor.getBaseName(enumType); return rbName; } }
true
true
public List<Cal10nError> verify(Locale locale) { List<Cal10nError> errorList = new ArrayList<Cal10nError>(); String baseName = AnnotationExtractor.getBaseName(enumType); if (baseName == null) { errorList.add(new Cal10nError(ErrorType.MISSING_BN_ANNOTATION, "", enumType, locale, "")); // no point in continuing return errorList; } String charset = AnnotationExtractor.getCharset(enumType, Locale.FRENCH); ResourceBundle rb = CAL10NResourceBundleFinder.getBundle(this.getClass() .getClassLoader(), baseName, locale, charset); ErrorFactory errorFactory = new ErrorFactory(enumType, locale, baseName); if (rb == null) { errorList.add(errorFactory.buildError(ErrorType.FAILED_TO_FIND_RB, "")); // no point in continuing return errorList; } Set<String> rbKeySet = buildKeySetFromEnumeration(rb.getKeys()); if (rbKeySet.size() == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_RB, "")); } Enum<?>[] enumArray = enumType.getEnumConstants(); if (enumArray == null || enumArray.length == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_ENUM, "")); } if (errorList.size() != 0) { return errorList; } for (Enum<?> e : enumArray) { String enumKey = e.toString(); if (rbKeySet.contains(enumKey)) { rbKeySet.remove(enumKey); } else { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_RB, enumKey)); } } for (String rbKey : rbKeySet) { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_ENUM, rbKey)); } return errorList; }
public List<Cal10nError> verify(Locale locale) { List<Cal10nError> errorList = new ArrayList<Cal10nError>(); String baseName = AnnotationExtractor.getBaseName(enumType); if (baseName == null) { errorList.add(new Cal10nError(ErrorType.MISSING_BN_ANNOTATION, "", enumType, locale, "")); // no point in continuing return errorList; } String charset = AnnotationExtractor.getCharset(enumType, locale); ResourceBundle rb = CAL10NResourceBundleFinder.getBundle(this.getClass() .getClassLoader(), baseName, locale, charset); ErrorFactory errorFactory = new ErrorFactory(enumType, locale, baseName); if (rb == null) { errorList.add(errorFactory.buildError(ErrorType.FAILED_TO_FIND_RB, "")); // no point in continuing return errorList; } Set<String> rbKeySet = buildKeySetFromEnumeration(rb.getKeys()); if (rbKeySet.size() == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_RB, "")); } Enum<?>[] enumArray = enumType.getEnumConstants(); if (enumArray == null || enumArray.length == 0) { errorList.add(errorFactory.buildError(ErrorType.EMPTY_ENUM, "")); } if (errorList.size() != 0) { return errorList; } for (Enum<?> e : enumArray) { String enumKey = e.toString(); if (rbKeySet.contains(enumKey)) { rbKeySet.remove(enumKey); } else { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_RB, enumKey)); } } for (String rbKey : rbKeySet) { errorList.add(errorFactory.buildError(ErrorType.ABSENT_IN_ENUM, rbKey)); } return errorList; }
diff --git a/ponysdk/src-core/main/java/com/ponysdk/core/ApplicationManagerOption.java b/ponysdk/src-core/main/java/com/ponysdk/core/ApplicationManagerOption.java index 223f137d..bcccd43e 100644 --- a/ponysdk/src-core/main/java/com/ponysdk/core/ApplicationManagerOption.java +++ b/ponysdk/src-core/main/java/com/ponysdk/core/ApplicationManagerOption.java @@ -1,18 +1,18 @@ package com.ponysdk.core; import java.util.concurrent.TimeUnit; public class ApplicationManagerOption { public long maxOutOfSyncDuration = -1; public long heartBeatPeriod = 0;// seconds - public void setHeartBeatPreiod(final long heartBeatPeriod, final TimeUnit timeUnit) { + public void setHeartBeatPeriod(final long heartBeatPeriod, final TimeUnit timeUnit) { this.heartBeatPeriod = TimeUnit.SECONDS.convert(heartBeatPeriod, timeUnit); } public long getHeartBeatPeriod() { return heartBeatPeriod; } }
true
true
public void setHeartBeatPreiod(final long heartBeatPeriod, final TimeUnit timeUnit) { this.heartBeatPeriod = TimeUnit.SECONDS.convert(heartBeatPeriod, timeUnit); }
public void setHeartBeatPeriod(final long heartBeatPeriod, final TimeUnit timeUnit) { this.heartBeatPeriod = TimeUnit.SECONDS.convert(heartBeatPeriod, timeUnit); }
diff --git a/src/com/quackware/tric/ui/TricCategoryDetailActivity.java b/src/com/quackware/tric/ui/TricCategoryDetailActivity.java index bea4ebf..57dfd02 100644 --- a/src/com/quackware/tric/ui/TricCategoryDetailActivity.java +++ b/src/com/quackware/tric/ui/TricCategoryDetailActivity.java @@ -1,113 +1,113 @@ package com.quackware.tric.ui; import com.quackware.tric.MyApplication; import com.quackware.tric.R; import com.quackware.tric.stats.Stats; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; public class TricCategoryDetailActivity extends Activity implements OnClickListener{ private static final String TAG = "TricCategoryDetailActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tric_category_detail); String category = getIntent().getExtras().getString("Category"); loadCategory(category); } private void loadCategory(String category) { LinearLayout ll = (LinearLayout)findViewById(R.id.catdetail_ll); for(Stats s : MyApplication.getStats()) { if(s.getType().equals(category) || (s.getType().equals("FacebookStats") && category.equals("SocialStats"))) { Button b = new Button(this); b.setText(s.getPrettyName()); b.setTag(s.getName()); b.setOnClickListener(this); Drawable img = getCategoryDrawable(category,s.getType()); if(img != null) { b.setCompoundDrawablesWithIntrinsicBounds(img, null,null,null); } ll.addView(b); } } } private Drawable getCategoryDrawable(String category, String optionalSocialCategory) { Resources res = getResources(); if(category.equals("SocialStats")) { if(optionalSocialCategory != null) { if(optionalSocialCategory.equals("FacebookStats")) { return resize(res.getDrawable(R.drawable.facebook)); } } return res.getDrawable(R.drawable.gnexus); } else if(category.equals("PhoneStats")) { return resize(res.getDrawable(R.drawable.gnexus)); } else if(category.equals("AppStats")) { return resize(res.getDrawable(R.drawable.android_image)); } - else if(category.equals("TraficStats")) + else if(category.equals("TrafficStats")) { //TODO replace this with a better drawable. return resize(res.getDrawable(R.drawable.gnexus)); } else { return null; } } private Drawable resize(Drawable image) { Bitmap d = ((BitmapDrawable)image).getBitmap(); Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 75, 75, false); return new BitmapDrawable(bitmapOrig); } @Override public void onClick(View view) { String name = (String)view.getTag(); try { Intent intent = new Intent(this,TricDetailActivity.class); intent.putExtra("tricName", name); startActivity(intent); } catch(Exception ex) { Log.e(TAG,"Unable to start tric detail activity with name " + name); return; } } }
true
true
private Drawable getCategoryDrawable(String category, String optionalSocialCategory) { Resources res = getResources(); if(category.equals("SocialStats")) { if(optionalSocialCategory != null) { if(optionalSocialCategory.equals("FacebookStats")) { return resize(res.getDrawable(R.drawable.facebook)); } } return res.getDrawable(R.drawable.gnexus); } else if(category.equals("PhoneStats")) { return resize(res.getDrawable(R.drawable.gnexus)); } else if(category.equals("AppStats")) { return resize(res.getDrawable(R.drawable.android_image)); } else if(category.equals("TraficStats")) { //TODO replace this with a better drawable. return resize(res.getDrawable(R.drawable.gnexus)); } else { return null; } }
private Drawable getCategoryDrawable(String category, String optionalSocialCategory) { Resources res = getResources(); if(category.equals("SocialStats")) { if(optionalSocialCategory != null) { if(optionalSocialCategory.equals("FacebookStats")) { return resize(res.getDrawable(R.drawable.facebook)); } } return res.getDrawable(R.drawable.gnexus); } else if(category.equals("PhoneStats")) { return resize(res.getDrawable(R.drawable.gnexus)); } else if(category.equals("AppStats")) { return resize(res.getDrawable(R.drawable.android_image)); } else if(category.equals("TrafficStats")) { //TODO replace this with a better drawable. return resize(res.getDrawable(R.drawable.gnexus)); } else { return null; } }
diff --git a/org.jboss.reddeer.swt/src/org/jboss/reddeer/swt/impl/tree/AbstractTreeItem.java b/org.jboss.reddeer.swt/src/org/jboss/reddeer/swt/impl/tree/AbstractTreeItem.java index 2dbd6778..901710da 100644 --- a/org.jboss.reddeer.swt/src/org/jboss/reddeer/swt/impl/tree/AbstractTreeItem.java +++ b/org.jboss.reddeer.swt/src/org/jboss/reddeer/swt/impl/tree/AbstractTreeItem.java @@ -1,188 +1,188 @@ package org.jboss.reddeer.swt.impl.tree; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.allOf; import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.swt.widgets.Control; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.reddeer.swt.api.TreeItem; import org.jboss.reddeer.swt.exception.SWTLayerException; import org.jboss.reddeer.swt.lookup.impl.WidgetLookup; public abstract class AbstractTreeItem implements TreeItem { protected final Logger logger = Logger.getLogger(this.getClass()); protected SWTBotTreeItem item; private int treeIndex; protected String[] path; public AbstractTreeItem(Control control) { this(control, 0); } public AbstractTreeItem(Control control, String... treeItemPath) { this(control, 0, treeItemPath); } public AbstractTreeItem(Control control, int treeIndex, String... treeItemPath) { this(control, treeIndex, 0, treeItemPath); } public AbstractTreeItem(Control control, int treeItemIndex) { this(control, 0, treeItemIndex); } public AbstractTreeItem(Control control, int treeIndex, int treeItemIndex) { this(control, treeIndex, treeItemIndex, (String[]) null); } @SuppressWarnings("unchecked") public AbstractTreeItem(Control control, int treeIndex, int treeItemIndex, String... treeItemPath) { SWTBotTree tree = new SWTBotTree((org.eclipse.swt.widgets.Tree) WidgetLookup.getInstance(). activeWidget(allOf(widgetOfType(org.eclipse.swt.widgets.Tree.class)), control, treeIndex)); this.treeIndex=treeIndex; int size = tree.getAllItems().length; if (size - treeItemIndex < 1) { throw new SWTLayerException("No matching tree item found"); } if (treeItemPath == null) { - item = tree.getAllItems()[treeIndex]; + item = tree.getAllItems()[treeItemIndex]; path = new String[] {item.getText()}; } else { List<String> tiPath = new ArrayList<String>(Arrays.asList(treeItemPath)); // wait method maybe will be needed here item = tree.getTreeItem(tiPath.get(0)); tiPath.remove(0); for (String treeItemNode : tiPath) { item.expand(); // wait method maybe will be needed here try { item = item.getNode(treeItemNode); } catch (WidgetNotFoundException wnfe) { /* workaround when item was not expanded */ item.collapse(); item.expand(); } } path = treeItemPath; } } public void select() { item.select(); } public String getText() { String text = item.getText(); return text; } public String getToolTipText() { String toolTipText = item.getToolTipText(); return toolTipText; } @Override public String getCell(int index) { return item.cell(index); } public String[] getPath() { return path; } public void expand(){ logger.debug("Expanding Tree Item"); item.expand(); } public void collapse() { logger.debug("Collapsing Tree Item"); item.collapse(); } protected List<TreeItem> getItems(boolean shellItem) { expand(); List<TreeItem> items = new LinkedList<TreeItem>(); for (SWTBotTreeItem childrenTreeItem : item.getItems()) { String[] treeItemPath = new String[] {childrenTreeItem.getText()}; if (shellItem) { items.add(new ShellTreeItem(treeIndex,joinTwoArrays(getPath(), treeItemPath))); } else { items.add(new ViewTreeItem(treeIndex,joinTwoArrays(getPath(), treeItemPath))); } } return items; } protected TreeItem getItem (String text, boolean shellTreeItem){ expand(); SWTBotTreeItem[] items = item.getItems(); int index = 0; while (index < items.length && !items[index].getText().equals(text)){ index++; } if (index < items.length){ String[] treeItemPath = new String[] {text}; if (shellTreeItem) { return new ShellTreeItem(treeIndex,joinTwoArrays(getPath(), treeItemPath)); } else { return new ViewTreeItem(treeIndex,joinTwoArrays(getPath(), treeItemPath)); } } else{ throw new WidgetNotFoundException("There is no Tree Item with text " + text); } } public void doubleClick(){ logger.debug("Double Click Tree Item " + item.getText()); item.doubleClick(); } public boolean isSelected(){ return item.isSelected(); } @Override public boolean isDisposed() { return item.widget.isDisposed(); } @Override public void setChecked(boolean check) { if (check){ item.check(); } else { item.uncheck(); } } public boolean isChecked() { return item.isChecked(); } public org.eclipse.swt.widgets.TreeItem getSWTWidget() { return item.widget; } private String[] joinTwoArrays(String[] array1, String[] array2) { String[] finalArray= new String[array1.length + array2.length]; System.arraycopy(array1, 0, finalArray, 0, array1.length); System.arraycopy(array2, 0, finalArray, array1.length, array2.length); return finalArray; } }
true
true
public AbstractTreeItem(Control control, int treeIndex, int treeItemIndex, String... treeItemPath) { SWTBotTree tree = new SWTBotTree((org.eclipse.swt.widgets.Tree) WidgetLookup.getInstance(). activeWidget(allOf(widgetOfType(org.eclipse.swt.widgets.Tree.class)), control, treeIndex)); this.treeIndex=treeIndex; int size = tree.getAllItems().length; if (size - treeItemIndex < 1) { throw new SWTLayerException("No matching tree item found"); } if (treeItemPath == null) { item = tree.getAllItems()[treeIndex]; path = new String[] {item.getText()}; } else { List<String> tiPath = new ArrayList<String>(Arrays.asList(treeItemPath)); // wait method maybe will be needed here item = tree.getTreeItem(tiPath.get(0)); tiPath.remove(0); for (String treeItemNode : tiPath) { item.expand(); // wait method maybe will be needed here try { item = item.getNode(treeItemNode); } catch (WidgetNotFoundException wnfe) { /* workaround when item was not expanded */ item.collapse(); item.expand(); } } path = treeItemPath; } }
public AbstractTreeItem(Control control, int treeIndex, int treeItemIndex, String... treeItemPath) { SWTBotTree tree = new SWTBotTree((org.eclipse.swt.widgets.Tree) WidgetLookup.getInstance(). activeWidget(allOf(widgetOfType(org.eclipse.swt.widgets.Tree.class)), control, treeIndex)); this.treeIndex=treeIndex; int size = tree.getAllItems().length; if (size - treeItemIndex < 1) { throw new SWTLayerException("No matching tree item found"); } if (treeItemPath == null) { item = tree.getAllItems()[treeItemIndex]; path = new String[] {item.getText()}; } else { List<String> tiPath = new ArrayList<String>(Arrays.asList(treeItemPath)); // wait method maybe will be needed here item = tree.getTreeItem(tiPath.get(0)); tiPath.remove(0); for (String treeItemNode : tiPath) { item.expand(); // wait method maybe will be needed here try { item = item.getNode(treeItemNode); } catch (WidgetNotFoundException wnfe) { /* workaround when item was not expanded */ item.collapse(); item.expand(); } } path = treeItemPath; } }
diff --git a/src/main/java/org/crosswire/jsword/index/lucene/analysis/ConfigurableSnowballAnalyzer.java b/src/main/java/org/crosswire/jsword/index/lucene/analysis/ConfigurableSnowballAnalyzer.java index b0cc44c7..d47243b8 100644 --- a/src/main/java/org/crosswire/jsword/index/lucene/analysis/ConfigurableSnowballAnalyzer.java +++ b/src/main/java/org/crosswire/jsword/index/lucene/analysis/ConfigurableSnowballAnalyzer.java @@ -1,172 +1,172 @@ /** * Distribution License: * JSword is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License, version 2.1 as published by * the Free Software Foundation. This program is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The License is available on the internet at: * http://www.gnu.org/copyleft/lgpl.html * or by writing to: * Free Software Foundation, Inc. * 59 Temple Place - Suite 330 * Boston, MA 02111-1307, USA * * Copyright: 2007 * The copyright to this program is held by it's authors. * * ID: $Id: $ */ package org.crosswire.jsword.index.lucene.analysis; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Set; import java.util.regex.Pattern; import org.apache.lucene.analysis.LowerCaseTokenizer; import org.apache.lucene.analysis.PorterStemFilter; import org.apache.lucene.analysis.StopAnalyzer; import org.apache.lucene.analysis.StopFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.de.GermanAnalyzer; import org.apache.lucene.analysis.fr.FrenchAnalyzer; import org.apache.lucene.analysis.nl.DutchAnalyzer; import org.apache.lucene.analysis.snowball.SnowballFilter; import org.apache.lucene.util.Version; import org.crosswire.jsword.book.Book; /** * An Analyzer whose {@link TokenStream} is built from a * {@link LowerCaseTokenizer} filtered with {@link SnowballFilter} (optional) * and {@link StopFilter} (optional) Default behavior: Stemming is done, Stop * words not removed A snowball stemmer is configured according to the language * of the Book. Currently it takes following stemmer names (available stemmers * in lucene snowball package net.sf.snowball.ext) * * <pre> * Danish * Dutch * English * Finnish * French * German2 * German * Italian * Kp * Lovins * Norwegian * Porter * Portuguese * Russian * Spanish * Swedish * </pre> * * This list is expected to expand, as and when Snowball project support more * languages * * @see gnu.lgpl.License for license details.<br> * The copyright to this program is held by it's authors. * @author sijo cherian [sijocherian at yahoo dot com] */ public class ConfigurableSnowballAnalyzer extends AbstractBookAnalyzer { public ConfigurableSnowballAnalyzer() { } /** * Filters {@link LowerCaseTokenizer} with {@link StopFilter} if enabled and * {@link SnowballFilter}. */ @Override public final TokenStream tokenStream(String fieldName, Reader reader) { TokenStream result = new LowerCaseTokenizer(reader); if (doStopWords && stopSet != null) { result = new StopFilter(false, result, stopSet); } // Configure Snowball filter based on language/stemmerName if (doStemming) { result = new SnowballFilter(result, stemmerName); } return result; } /* (non-Javadoc) * @see org.apache.lucene.analysis.Analyzer#reusableTokenStream(java.lang.String, java.io.Reader) */ @Override public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { SavedStreams streams = (SavedStreams) getPreviousTokenStream(); if (streams == null) { streams = new SavedStreams(new LowerCaseTokenizer(reader)); if (doStopWords && stopSet != null) { streams.setResult(new StopFilter(StopFilter.getEnablePositionIncrementsVersionDefault(matchVersion), streams.getResult(), stopSet)); } if (doStemming) { - streams.setResult(new PorterStemFilter(streams.getResult())); + streams.setResult(new SnowballFilter(streams.getResult(), stemmerName)); } setPreviousTokenStream(streams); } else { streams.getSource().reset(reader); } return streams.getResult(); } @Override public void setBook(Book newBook) { book = newBook; stemmerName = null; if (book != null) { // stemmer name are same as language name, in most cases pickStemmer(book.getLanguage().getName()); } } /** * Given the name of a stemmer, use that one. * * @param language */ public void pickStemmer(String language) { stemmerName = language; if (stemmerName != null) { // Check for allowed stemmers if (!allowedStemmers.matcher(stemmerName).matches()) { throw new IllegalArgumentException("SnowballAnalyzer configured for unavailable stemmer " + stemmerName); } // Initialize the default stop words if (defaultStopWordMap.containsKey(stemmerName)) { stopSet = defaultStopWordMap.get(stemmerName); } } } /** * The name of the stemmer to use. */ private String stemmerName; private static Pattern allowedStemmers = Pattern .compile("(Danish|Dutch|English|Finnish|French|German2|German|Italian|Kp|Lovins|Norwegian|Porter|Portuguese|Russian|Spanish|Swedish)"); // Maps StemmerName > String array of standard stop words private static HashMap<String, Set<?>> defaultStopWordMap = new HashMap<String, Set<?>>(); static { defaultStopWordMap.put("French", FrenchAnalyzer.getDefaultStopSet()); defaultStopWordMap.put("German", GermanAnalyzer.getDefaultStopSet()); defaultStopWordMap.put("German2", GermanAnalyzer.getDefaultStopSet()); defaultStopWordMap.put("Dutch", DutchAnalyzer.getDefaultStopSet()); defaultStopWordMap.put("English", StopAnalyzer.ENGLISH_STOP_WORDS_SET); defaultStopWordMap.put("Porter", StopAnalyzer.ENGLISH_STOP_WORDS_SET); } private final Version matchVersion = Version.LUCENE_29; }
true
true
public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { SavedStreams streams = (SavedStreams) getPreviousTokenStream(); if (streams == null) { streams = new SavedStreams(new LowerCaseTokenizer(reader)); if (doStopWords && stopSet != null) { streams.setResult(new StopFilter(StopFilter.getEnablePositionIncrementsVersionDefault(matchVersion), streams.getResult(), stopSet)); } if (doStemming) { streams.setResult(new PorterStemFilter(streams.getResult())); } setPreviousTokenStream(streams); } else { streams.getSource().reset(reader); } return streams.getResult(); }
public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { SavedStreams streams = (SavedStreams) getPreviousTokenStream(); if (streams == null) { streams = new SavedStreams(new LowerCaseTokenizer(reader)); if (doStopWords && stopSet != null) { streams.setResult(new StopFilter(StopFilter.getEnablePositionIncrementsVersionDefault(matchVersion), streams.getResult(), stopSet)); } if (doStemming) { streams.setResult(new SnowballFilter(streams.getResult(), stemmerName)); } setPreviousTokenStream(streams); } else { streams.getSource().reset(reader); } return streams.getResult(); }
diff --git a/OsceManager/src/main/java/ch/unibas/medizin/osce/server/upload/ExportStatisticData.java b/OsceManager/src/main/java/ch/unibas/medizin/osce/server/upload/ExportStatisticData.java index 02e824f4..391fbcd6 100644 --- a/OsceManager/src/main/java/ch/unibas/medizin/osce/server/upload/ExportStatisticData.java +++ b/OsceManager/src/main/java/ch/unibas/medizin/osce/server/upload/ExportStatisticData.java @@ -1,471 +1,471 @@ package ch.unibas.medizin.osce.server.upload; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import ch.unibas.medizin.osce.domain.Answer; import ch.unibas.medizin.osce.domain.ChecklistQuestion; import ch.unibas.medizin.osce.domain.ChecklistTopic; import ch.unibas.medizin.osce.domain.Osce; import ch.unibas.medizin.osce.domain.OsceDay; import ch.unibas.medizin.osce.domain.OscePost; import ch.unibas.medizin.osce.domain.OsceSequence; import ch.unibas.medizin.osce.server.OsMaFilePathConstant; public class ExportStatisticData extends HttpServlet{ private static Logger Log = Logger.getLogger(UploadServlet.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { String osceId=request.getParameter("osceId"); String fileName=createCSV(new Long(osceId),request); try{ resp.setContentType("application/x-download"); resp.setHeader("Content-Disposition", "attachment; filename=" + "OsceStatisticData.zip"); Log.info("path :" + fileName); //String file=OsMaFilePathConstant.ROLE_IMAGE_FILEPATH+path; Log.info(" file :" + fileName); OutputStream out = resp.getOutputStream(); FileInputStream in = new FileInputStream(fileName); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); File htmlFile=new File(fileName); htmlFile.delete(); out.flush(); } catch (Exception e) { Log.error(e.getMessage(),e); } } /*public String createCSV(Long osceId,HttpServletRequest request) { String path=getServletConfig().getServletContext().getRealPath(OsMaFilePathConstant.assignmentHTML); String fileName=path+System.currentTimeMillis()+".csv"; Osce osce=Osce.findOsce(osceId); List<OsceDay> osceDays=osce.getOsce_days(); for(int i=0;i<osceDays.size();i++) { OsceDay osceDay=osceDays.get(i); List<OsceSequence> osceSequences=osceDay.getOsceSequences(); for(int a=0;a<osceSequences.size();a++) { OsceSequence osceSeq=osceSequences.get(a); } } try { FileWriter writer = new FileWriter(fileName); //column header[start writer.append("examiners"); writer.append('|'); writer.append("students"); writer.append('|'); //retrieve distinc Item List<ChecklistQuestion> questions=Answer.retrieveDistinctItems(osceId); for(int i=0;i<questions.size();i++) { writer.append("item "+questions.get(i).getId()); writer.append('|'); } writer.append("impression "); writer.append('\n'); //column header end] //generate whatever data you want[Start //retrieve data Long lastCandidateId = 0l; List<Answer> csvData=Answer.retrieveExportCsvData(osceId); System.out.println("CSVDATA SIZE : " + csvData.size()); for(int i=0;i<csvData.size();i++) { Answer answer=csvData.get(i); if (!lastCandidateId.equals(answer.getStudent().getId())) { if (!lastCandidateId.equals(0)) { //impression item String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) writer.append('0');//impression else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(answer.getStudent().getId(), new Long(impressionItemString), osceId); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else writer.append('0'); } } } writer.append('\n'); writer.append(answer.getDoctor().getPreName() + " "+ answer.getDoctor().getName()); writer.append('|'); writer.append(answer.getStudent().getPreName() + " "+ answer.getStudent().getName()); writer.append('|'); lastCandidateId = answer.getStudent().getId(); } writer.append(answer.getChecklistOption().getValue()); writer.append('|'); for(int j=i;j<csvData.size();j++) { writer.append(csvData.get(j).getChecklistOption().getValue()); writer.append('|'); if((j!=csvData.size()-1 && csvData.get(j).getStudent().getId()!=csvData.get(j+1).getStudent().getId() )) { i=j; writer.append('0');//impression writer.append('\n'); break; } } for(int j=0;j<questions.size();j++) { Answer item=Answer.findAnswer(answer.getStudent().getId(), questions.get(j).getId(), osceId); if(item==null)//missing { writer.append('0'); writer.append('|'); } else { writer.append(item.getChecklistOption().getValue()); writer.append('|'); } } //impression item String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) writer.append('0');//impression else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(answer.getStudent().getId(), new Long(impressionItemString), osceId); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else writer.append('0'); } } } //generate whatever data you want end] writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } return fileName; }*/ public String createCSV(Long osceId,HttpServletRequest request) { String fileName = ""; String zipFileName = ""; char alphaSeq = 'A'; List<String> fileNameList = new ArrayList<String>(); Long impressionQueId = null; try { String path=getServletConfig().getServletContext().getRealPath(OsMaFilePathConstant.assignmentHTML); System.out.println("PATH : " + path); //String fileName=path+System.currentTimeMillis()+".csv"; zipFileName = path + "OsceStatisticData.zip"; Osce osce=Osce.findOsce(osceId); List<OsceDay> osceDays=osce.getOsce_days(); for(int i=0;i<osceDays.size();i++) { OsceDay osceDay=osceDays.get(i); List<OsceSequence> osceSequences=osceDay.getOsceSequences(); for(int a=0;a<osceSequences.size();a++) { OsceSequence osceSeq=osceSequences.get(a); List<OscePost> oscePostList = osceSeq.getOscePosts(); for (OscePost oscePost : oscePostList) { fileName = "Day"+ (i+1) + "_" + oscePost.getStandardizedRole().getShortName() + ".csv"; fileName = path + fileName; fileNameList.add(fileName); //System.out.println("FILE PATH : " + fileName); FileWriter writer = new FileWriter(fileName); writer.append("examiners"); writer.append('|'); writer.append("students"); writer.append('|'); List<ChecklistTopic> checklistTopicList = oscePost.getStandardizedRole().getCheckList().getCheckListTopics(); alphaSeq = 'A'; impressionQueId = null; String impressionItemString=request.getParameter("p"+oscePost.getId().toString()); if (impressionItemString != null) impressionQueId=Long.parseLong(impressionItemString); for (ChecklistTopic checklistTopic : checklistTopicList) { List<ChecklistQuestion> questionList = ChecklistQuestion.findCheckListQuestionByTopic(checklistTopic.getId()); int count = 1; for (ChecklistQuestion question : questionList) { - if (impressionQueId == null && question.getIsOveralQuestion() != null && question.getIsOveralQuestion()) + if ((impressionQueId == null || impressionQueId == 0) && question.getIsOveralQuestion() != null && question.getIsOveralQuestion()) { impressionQueId = question.getId(); } writer.append(String.valueOf(alphaSeq) + count++); //writer.append(question.getId().toString()); writer.append('|'); } alphaSeq++; } writer.append("impression "); //writer.append('\n'); List<Answer> answerList = Answer.retrieveExportCsvDataByOscePost(osceDay.getId(), oscePost.getId()); Long lastCandidateId = null; Answer answer = null; for (int j=0; j<answerList.size(); j++) { answer = answerList.get(j); if (lastCandidateId == null || (!lastCandidateId.equals(answer.getStudent().getId()))) { if (lastCandidateId != null) { - if (impressionQueId != null) + if (impressionQueId != null && impressionQueId != 0) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.append('\n'); writer.append(answer.getDoctor().getPreName() + " "+ answer.getDoctor().getName()); writer.append('|'); writer.append(answer.getStudent().getPreName() + " "+ answer.getStudent().getName()); writer.append('|'); lastCandidateId = answer.getStudent().getId(); } writer.append(answer.getChecklistOption().getValue()); //writer.append(answer.getChecklistQuestion().getId().toString()); writer.append('|'); } if (answerList.size() > 0) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*answer = answerList.get(answerList.size() - 1); String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.flush(); writer.close(); } } } createZipFile(zipFileName, fileNameList, path); } catch(Exception e) { Log.error(e.getMessage(),e); } return zipFileName; } public static void createZipFile(String zipFilePath, List<String> fileNameList, String path) { try { ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath)); for (int i = 0 ; i < fileNameList.size() ; i ++) { byte[] buf = new byte[1024]; int len; File file = new File(fileNameList.get(i)); FileInputStream in = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(file.getName())); while ((len = in.read(buf)) > 0) { zipOut.write(buf, 0, len); } zipOut.closeEntry(); } zipOut.close(); Log.info("Done..."); } catch (FileNotFoundException e) { Log.error(e.getMessage(),e); } catch (IOException e) { Log.error(e.getMessage(),e); } } }
false
true
public String createCSV(Long osceId,HttpServletRequest request) { String fileName = ""; String zipFileName = ""; char alphaSeq = 'A'; List<String> fileNameList = new ArrayList<String>(); Long impressionQueId = null; try { String path=getServletConfig().getServletContext().getRealPath(OsMaFilePathConstant.assignmentHTML); System.out.println("PATH : " + path); //String fileName=path+System.currentTimeMillis()+".csv"; zipFileName = path + "OsceStatisticData.zip"; Osce osce=Osce.findOsce(osceId); List<OsceDay> osceDays=osce.getOsce_days(); for(int i=0;i<osceDays.size();i++) { OsceDay osceDay=osceDays.get(i); List<OsceSequence> osceSequences=osceDay.getOsceSequences(); for(int a=0;a<osceSequences.size();a++) { OsceSequence osceSeq=osceSequences.get(a); List<OscePost> oscePostList = osceSeq.getOscePosts(); for (OscePost oscePost : oscePostList) { fileName = "Day"+ (i+1) + "_" + oscePost.getStandardizedRole().getShortName() + ".csv"; fileName = path + fileName; fileNameList.add(fileName); //System.out.println("FILE PATH : " + fileName); FileWriter writer = new FileWriter(fileName); writer.append("examiners"); writer.append('|'); writer.append("students"); writer.append('|'); List<ChecklistTopic> checklistTopicList = oscePost.getStandardizedRole().getCheckList().getCheckListTopics(); alphaSeq = 'A'; impressionQueId = null; String impressionItemString=request.getParameter("p"+oscePost.getId().toString()); if (impressionItemString != null) impressionQueId=Long.parseLong(impressionItemString); for (ChecklistTopic checklistTopic : checklistTopicList) { List<ChecklistQuestion> questionList = ChecklistQuestion.findCheckListQuestionByTopic(checklistTopic.getId()); int count = 1; for (ChecklistQuestion question : questionList) { if (impressionQueId == null && question.getIsOveralQuestion() != null && question.getIsOveralQuestion()) { impressionQueId = question.getId(); } writer.append(String.valueOf(alphaSeq) + count++); //writer.append(question.getId().toString()); writer.append('|'); } alphaSeq++; } writer.append("impression "); //writer.append('\n'); List<Answer> answerList = Answer.retrieveExportCsvDataByOscePost(osceDay.getId(), oscePost.getId()); Long lastCandidateId = null; Answer answer = null; for (int j=0; j<answerList.size(); j++) { answer = answerList.get(j); if (lastCandidateId == null || (!lastCandidateId.equals(answer.getStudent().getId()))) { if (lastCandidateId != null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.append('\n'); writer.append(answer.getDoctor().getPreName() + " "+ answer.getDoctor().getName()); writer.append('|'); writer.append(answer.getStudent().getPreName() + " "+ answer.getStudent().getName()); writer.append('|'); lastCandidateId = answer.getStudent().getId(); } writer.append(answer.getChecklistOption().getValue()); //writer.append(answer.getChecklistQuestion().getId().toString()); writer.append('|'); } if (answerList.size() > 0) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*answer = answerList.get(answerList.size() - 1); String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.flush(); writer.close(); } } } createZipFile(zipFileName, fileNameList, path); } catch(Exception e) { Log.error(e.getMessage(),e); } return zipFileName; }
public String createCSV(Long osceId,HttpServletRequest request) { String fileName = ""; String zipFileName = ""; char alphaSeq = 'A'; List<String> fileNameList = new ArrayList<String>(); Long impressionQueId = null; try { String path=getServletConfig().getServletContext().getRealPath(OsMaFilePathConstant.assignmentHTML); System.out.println("PATH : " + path); //String fileName=path+System.currentTimeMillis()+".csv"; zipFileName = path + "OsceStatisticData.zip"; Osce osce=Osce.findOsce(osceId); List<OsceDay> osceDays=osce.getOsce_days(); for(int i=0;i<osceDays.size();i++) { OsceDay osceDay=osceDays.get(i); List<OsceSequence> osceSequences=osceDay.getOsceSequences(); for(int a=0;a<osceSequences.size();a++) { OsceSequence osceSeq=osceSequences.get(a); List<OscePost> oscePostList = osceSeq.getOscePosts(); for (OscePost oscePost : oscePostList) { fileName = "Day"+ (i+1) + "_" + oscePost.getStandardizedRole().getShortName() + ".csv"; fileName = path + fileName; fileNameList.add(fileName); //System.out.println("FILE PATH : " + fileName); FileWriter writer = new FileWriter(fileName); writer.append("examiners"); writer.append('|'); writer.append("students"); writer.append('|'); List<ChecklistTopic> checklistTopicList = oscePost.getStandardizedRole().getCheckList().getCheckListTopics(); alphaSeq = 'A'; impressionQueId = null; String impressionItemString=request.getParameter("p"+oscePost.getId().toString()); if (impressionItemString != null) impressionQueId=Long.parseLong(impressionItemString); for (ChecklistTopic checklistTopic : checklistTopicList) { List<ChecklistQuestion> questionList = ChecklistQuestion.findCheckListQuestionByTopic(checklistTopic.getId()); int count = 1; for (ChecklistQuestion question : questionList) { if ((impressionQueId == null || impressionQueId == 0) && question.getIsOveralQuestion() != null && question.getIsOveralQuestion()) { impressionQueId = question.getId(); } writer.append(String.valueOf(alphaSeq) + count++); //writer.append(question.getId().toString()); writer.append('|'); } alphaSeq++; } writer.append("impression "); //writer.append('\n'); List<Answer> answerList = Answer.retrieveExportCsvDataByOscePost(osceDay.getId(), oscePost.getId()); Long lastCandidateId = null; Answer answer = null; for (int j=0; j<answerList.size(); j++) { answer = answerList.get(j); if (lastCandidateId == null || (!lastCandidateId.equals(answer.getStudent().getId()))) { if (lastCandidateId != null) { if (impressionQueId != null && impressionQueId != 0) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.append('\n'); writer.append(answer.getDoctor().getPreName() + " "+ answer.getDoctor().getName()); writer.append('|'); writer.append(answer.getStudent().getPreName() + " "+ answer.getStudent().getName()); writer.append('|'); lastCandidateId = answer.getStudent().getId(); } writer.append(answer.getChecklistOption().getValue()); //writer.append(answer.getChecklistQuestion().getId().toString()); writer.append('|'); } if (answerList.size() > 0) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } /*answer = answerList.get(answerList.size() - 1); String impressionItemString=request.getParameter("p"+answer.getOscePostRoom().getOscePost().getId().toString()); if(impressionItemString==null) { if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else { writer.append('0');//impression } } else { if(impressionItemString.equals("0")) writer.append('0'); else { Answer impressionItem=Answer.findAnswer(lastCandidateId, new Long(impressionItemString), osceDay.getId()); if(impressionItem !=null) writer.append(impressionItem.getChecklistOption().getValue()); else if (impressionQueId != null) { Answer impressionItem1=Answer.findAnswer(lastCandidateId, impressionQueId, osceDay.getId()); writer.append(impressionItem1.getChecklistOption().getValue()); } else writer.append('0'); } }*/ } writer.flush(); writer.close(); } } } createZipFile(zipFileName, fileNameList, path); } catch(Exception e) { Log.error(e.getMessage(),e); } return zipFileName; }
diff --git a/nexus/nexus-indexer-lucene/nexus-indexer-lucene-rest-api/src/main/java/org/sonatype/nexus/rest/artifact/InfoArtifactViewProvider.java b/nexus/nexus-indexer-lucene/nexus-indexer-lucene-rest-api/src/main/java/org/sonatype/nexus/rest/artifact/InfoArtifactViewProvider.java index 4dc32336c..5661cbe80 100644 --- a/nexus/nexus-indexer-lucene/nexus-indexer-lucene-rest-api/src/main/java/org/sonatype/nexus/rest/artifact/InfoArtifactViewProvider.java +++ b/nexus/nexus-indexer-lucene/nexus-indexer-lucene-rest-api/src/main/java/org/sonatype/nexus/rest/artifact/InfoArtifactViewProvider.java @@ -1,81 +1,82 @@ package org.sonatype.nexus.rest.artifact; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.sonatype.nexus.index.ArtifactInfo; import org.sonatype.nexus.index.IndexerManager; import org.sonatype.nexus.index.IteratorSearchResponse; import org.sonatype.nexus.proxy.NoSuchRepositoryException; import org.sonatype.nexus.proxy.access.AccessManager; import org.sonatype.nexus.proxy.attributes.inspectors.DigestCalculatingInspector; import org.sonatype.nexus.proxy.item.StorageFileItem; import org.sonatype.nexus.proxy.item.StorageItem; import org.sonatype.nexus.rest.ArtifactViewProvider; import org.sonatype.nexus.rest.model.ArtifactInfoResource; import org.sonatype.nexus.rest.model.ArtifactInfoResourceResponse; @Component( role = ArtifactViewProvider.class, hint = "info" ) public class InfoArtifactViewProvider extends AbstractLogEnabled implements ArtifactViewProvider { @Requirement private IndexerManager indexerManager; public Object retrieveView( StorageItem item ) throws IOException { if ( !( item instanceof StorageFileItem ) ) { return null; } StorageFileItem fileItem = (StorageFileItem) item; Set<String> repositories = new LinkedHashSet<String>(); try { IteratorSearchResponse searchResponse = indexerManager.searchArtifactSha1ChecksumIterator( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ), null, null, null, null, null ); for ( Iterator<ArtifactInfo> iterator = searchResponse.iterator(); iterator.hasNext(); ) { ArtifactInfo info = iterator.next(); repositories.add( info.repository ); } } catch ( NoSuchRepositoryException e ) { // should never trigger this exception since I'm searching on all repositories getLogger().error( e.getMessage(), e ); } ArtifactInfoResourceResponse result = new ArtifactInfoResourceResponse(); ArtifactInfoResource resource = new ArtifactInfoResource(); resource.setRepositoryId( item.getRepositoryItemUid().getRepository().getId() ); resource.setRepositoryName( item.getRepositoryItemUid().getRepository().getName() ); resource.setRepositoryPath( item.getRepositoryItemUid().getPath() ); + resource.setMd5Hash( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_MD5_KEY ) ); resource.setSha1Hash( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ) ); resource.setLastChanged( fileItem.getModified() ); resource.setRepositories( new ArrayList<String>( repositories ) ); resource.setSize( fileItem.getLength() ); resource.setUploaded( fileItem.getCreated() ); resource.setUploader( fileItem.getAttributes().get( AccessManager.REQUEST_USER ) ); resource.setMimeType( fileItem.getMimeType() ); result.setData( resource ); return result; } }
true
true
public Object retrieveView( StorageItem item ) throws IOException { if ( !( item instanceof StorageFileItem ) ) { return null; } StorageFileItem fileItem = (StorageFileItem) item; Set<String> repositories = new LinkedHashSet<String>(); try { IteratorSearchResponse searchResponse = indexerManager.searchArtifactSha1ChecksumIterator( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ), null, null, null, null, null ); for ( Iterator<ArtifactInfo> iterator = searchResponse.iterator(); iterator.hasNext(); ) { ArtifactInfo info = iterator.next(); repositories.add( info.repository ); } } catch ( NoSuchRepositoryException e ) { // should never trigger this exception since I'm searching on all repositories getLogger().error( e.getMessage(), e ); } ArtifactInfoResourceResponse result = new ArtifactInfoResourceResponse(); ArtifactInfoResource resource = new ArtifactInfoResource(); resource.setRepositoryId( item.getRepositoryItemUid().getRepository().getId() ); resource.setRepositoryName( item.getRepositoryItemUid().getRepository().getName() ); resource.setRepositoryPath( item.getRepositoryItemUid().getPath() ); resource.setSha1Hash( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ) ); resource.setLastChanged( fileItem.getModified() ); resource.setRepositories( new ArrayList<String>( repositories ) ); resource.setSize( fileItem.getLength() ); resource.setUploaded( fileItem.getCreated() ); resource.setUploader( fileItem.getAttributes().get( AccessManager.REQUEST_USER ) ); resource.setMimeType( fileItem.getMimeType() ); result.setData( resource ); return result; }
public Object retrieveView( StorageItem item ) throws IOException { if ( !( item instanceof StorageFileItem ) ) { return null; } StorageFileItem fileItem = (StorageFileItem) item; Set<String> repositories = new LinkedHashSet<String>(); try { IteratorSearchResponse searchResponse = indexerManager.searchArtifactSha1ChecksumIterator( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ), null, null, null, null, null ); for ( Iterator<ArtifactInfo> iterator = searchResponse.iterator(); iterator.hasNext(); ) { ArtifactInfo info = iterator.next(); repositories.add( info.repository ); } } catch ( NoSuchRepositoryException e ) { // should never trigger this exception since I'm searching on all repositories getLogger().error( e.getMessage(), e ); } ArtifactInfoResourceResponse result = new ArtifactInfoResourceResponse(); ArtifactInfoResource resource = new ArtifactInfoResource(); resource.setRepositoryId( item.getRepositoryItemUid().getRepository().getId() ); resource.setRepositoryName( item.getRepositoryItemUid().getRepository().getName() ); resource.setRepositoryPath( item.getRepositoryItemUid().getPath() ); resource.setMd5Hash( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_MD5_KEY ) ); resource.setSha1Hash( fileItem.getAttributes().get( DigestCalculatingInspector.DIGEST_SHA1_KEY ) ); resource.setLastChanged( fileItem.getModified() ); resource.setRepositories( new ArrayList<String>( repositories ) ); resource.setSize( fileItem.getLength() ); resource.setUploaded( fileItem.getCreated() ); resource.setUploader( fileItem.getAttributes().get( AccessManager.REQUEST_USER ) ); resource.setMimeType( fileItem.getMimeType() ); result.setData( resource ); return result; }
diff --git a/src/main/java/org/atlasapi/equiv/tasks/BrandEquivUpdateTaskRunner.java b/src/main/java/org/atlasapi/equiv/tasks/BrandEquivUpdateTaskRunner.java index 71ecc8faf..770f323fb 100644 --- a/src/main/java/org/atlasapi/equiv/tasks/BrandEquivUpdateTaskRunner.java +++ b/src/main/java/org/atlasapi/equiv/tasks/BrandEquivUpdateTaskRunner.java @@ -1,75 +1,75 @@ package org.atlasapi.equiv.tasks; import static com.metabroadcast.common.persistence.mongo.MongoBuilders.where; import java.util.List; import org.atlasapi.media.entity.Brand; import org.atlasapi.media.entity.Content; import org.atlasapi.media.entity.Publisher; import org.atlasapi.persistence.content.ScheduleResolver; import org.atlasapi.persistence.content.mongo.MongoDbBackedContentStore; import org.atlasapi.persistence.logging.AdapterLog; import org.atlasapi.persistence.logging.AdapterLogEntry; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.PeriodFormat; import com.google.common.collect.Iterables; import com.metabroadcast.common.persistence.mongo.MongoQueryBuilder; import com.metabroadcast.common.time.Clock; import com.metabroadcast.common.time.DateTimeZones; import com.metabroadcast.common.time.SystemClock; public class BrandEquivUpdateTaskRunner implements Runnable { private static final int BATCH_SIZE = 10; private final Clock clock; private final MongoDbBackedContentStore contentStore; private final ScheduleResolver scheduleResolver; private final AdapterLog log; private final EquivCleaner cleaner; public BrandEquivUpdateTaskRunner(MongoDbBackedContentStore contentStore, ScheduleResolver scheduleResolver, AdapterLog log) { this(contentStore, scheduleResolver, log, new SystemClock()); } public BrandEquivUpdateTaskRunner(MongoDbBackedContentStore contentStore, ScheduleResolver scheduleResolver, AdapterLog log, Clock clock) { this.contentStore = contentStore; this.scheduleResolver = scheduleResolver; this.log = log; this.clock = clock; this.cleaner = new EquivCleaner(contentStore, contentStore); } @Override public void run() { log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription("Starting equivalence task")); DateTime start = new DateTime(DateTimeZones.UTC); int processed = 0; String lastId = null; List<Content> contents; do { - contents = contentStore.iterate(queryFor(clock.now()), lastId, -BATCH_SIZE); + contents = contentStore.iterateOverContent(queryFor(clock.now()), lastId, -BATCH_SIZE); for (Brand brand : Iterables.filter(contents, Brand.class)) { processed++; try { cleaner.cleanEquivalences(brand); new BrandEquivUpdateTask(brand, scheduleResolver, contentStore, log).writesResults(true).call(); } catch (Exception e) { log.record(AdapterLogEntry.errorEntry().withCause(e).withSource(getClass()).withDescription("Exception updating equivalence for "+brand.getCanonicalUri())); } } lastId = contents.isEmpty() ? lastId : Iterables.getLast(contents).getCanonicalUri(); } while (!contents.isEmpty()); String runTime = new Period(start, new DateTime(DateTimeZones.UTC)).toString(PeriodFormat.getDefault()); log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription(String.format("Finish equivalence task in %s. %s brands processed", runTime, processed))); } private MongoQueryBuilder queryFor(DateTime now) { return where().fieldEquals("publisher", Publisher.PA.key())/*.fieldAfter("lastFetched", now.minus(Duration.standardDays(1)))*/; } }
true
true
public void run() { log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription("Starting equivalence task")); DateTime start = new DateTime(DateTimeZones.UTC); int processed = 0; String lastId = null; List<Content> contents; do { contents = contentStore.iterate(queryFor(clock.now()), lastId, -BATCH_SIZE); for (Brand brand : Iterables.filter(contents, Brand.class)) { processed++; try { cleaner.cleanEquivalences(brand); new BrandEquivUpdateTask(brand, scheduleResolver, contentStore, log).writesResults(true).call(); } catch (Exception e) { log.record(AdapterLogEntry.errorEntry().withCause(e).withSource(getClass()).withDescription("Exception updating equivalence for "+brand.getCanonicalUri())); } } lastId = contents.isEmpty() ? lastId : Iterables.getLast(contents).getCanonicalUri(); } while (!contents.isEmpty()); String runTime = new Period(start, new DateTime(DateTimeZones.UTC)).toString(PeriodFormat.getDefault()); log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription(String.format("Finish equivalence task in %s. %s brands processed", runTime, processed))); }
public void run() { log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription("Starting equivalence task")); DateTime start = new DateTime(DateTimeZones.UTC); int processed = 0; String lastId = null; List<Content> contents; do { contents = contentStore.iterateOverContent(queryFor(clock.now()), lastId, -BATCH_SIZE); for (Brand brand : Iterables.filter(contents, Brand.class)) { processed++; try { cleaner.cleanEquivalences(brand); new BrandEquivUpdateTask(brand, scheduleResolver, contentStore, log).writesResults(true).call(); } catch (Exception e) { log.record(AdapterLogEntry.errorEntry().withCause(e).withSource(getClass()).withDescription("Exception updating equivalence for "+brand.getCanonicalUri())); } } lastId = contents.isEmpty() ? lastId : Iterables.getLast(contents).getCanonicalUri(); } while (!contents.isEmpty()); String runTime = new Period(start, new DateTime(DateTimeZones.UTC)).toString(PeriodFormat.getDefault()); log.record(AdapterLogEntry.infoEntry().withSource(getClass()).withDescription(String.format("Finish equivalence task in %s. %s brands processed", runTime, processed))); }
diff --git a/src/main/java/es/rchavarria/raccount/frontend/expensesReport/gui/ExpensesReportResultController.java b/src/main/java/es/rchavarria/raccount/frontend/expensesReport/gui/ExpensesReportResultController.java index 77f8c8a..cfda4b4 100644 --- a/src/main/java/es/rchavarria/raccount/frontend/expensesReport/gui/ExpensesReportResultController.java +++ b/src/main/java/es/rchavarria/raccount/frontend/expensesReport/gui/ExpensesReportResultController.java @@ -1,31 +1,31 @@ package es.rchavarria.raccount.frontend.expensesReport.gui; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import es.rchavarria.raccount.frontend.expensesReport.models.ExpensesReportResultTableModel; import es.rchavarria.raccount.frontend.gui.view.GuiView; import es.rchavarria.raccount.model.ExpensesByConcept; public class ExpensesReportResultController { private final static Logger log = LoggerFactory.getLogger(ExpensesReportResultController.class); private ExpensesReportResultView view; public ExpensesReportResultController() { view = new ExpensesReportResultView(); } public GuiView getView() { return view; } public void load(List<ExpensesByConcept> expenses) { - log.info("loading %s expenses", expenses.size()); + log.info("loading {} expenses", expenses.size()); view.setTableModel(new ExpensesReportResultTableModel(expenses)); } }
true
true
public void load(List<ExpensesByConcept> expenses) { log.info("loading %s expenses", expenses.size()); view.setTableModel(new ExpensesReportResultTableModel(expenses)); }
public void load(List<ExpensesByConcept> expenses) { log.info("loading {} expenses", expenses.size()); view.setTableModel(new ExpensesReportResultTableModel(expenses)); }
diff --git a/src/me/libraryaddict/Hungergames/Abilities/Crafter.java b/src/me/libraryaddict/Hungergames/Abilities/Crafter.java index df88c02..236a459 100644 --- a/src/me/libraryaddict/Hungergames/Abilities/Crafter.java +++ b/src/me/libraryaddict/Hungergames/Abilities/Crafter.java @@ -1,71 +1,71 @@ package me.libraryaddict.Hungergames.Abilities; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import me.libraryaddict.Hungergames.Events.PlayerKilledEvent; import me.libraryaddict.Hungergames.Types.AbilityListener; import me.libraryaddict.Hungergames.Types.HungergamesApi; import me.libraryaddict.Hungergames.Types.FakeFurnace; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_5_R3.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_5_R3.inventory.CraftItemStack; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; public class Crafter extends AbilityListener { private transient Map<ItemStack, FakeFurnace> furnaces = new HashMap<ItemStack, FakeFurnace>(); public String craftingStarItemName = ChatColor.WHITE + "Crafting Star"; public String furnacePowderItemName = ChatColor.WHITE + "Furnace Powder"; public int furnacePowderItemId = Material.BLAZE_POWDER.getId(); public int craftingStarItemId = Material.NETHER_STAR.getId(); public Crafter() { Bukkit.getScheduler().scheduleSyncRepeatingTask(HungergamesApi.getHungergames(), new Runnable() { public void run() { for (FakeFurnace furnace : furnaces.values()) furnace.tick(); } }, 1, 1); } @EventHandler public void onInteract(PlayerInteractEvent event) { ItemStack item = event.getItem(); if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR)) { Player p = event.getPlayer(); - if (isSpecialItem(item, craftingStarItemName) && furnacePowderItemId == item.getTypeId()) { + if (isSpecialItem(item, craftingStarItemName) && craftingStarItemId == item.getTypeId()) { p.openWorkbench(null, true); } else if (isSpecialItem(item, furnacePowderItemName) && furnacePowderItemId == item.getTypeId()) { if (!furnaces.containsKey(item)) { furnaces.put(item, new FakeFurnace()); } ((CraftPlayer) p).getHandle().openFurnace(furnaces.get(item)); } } } @EventHandler public void onKilled(PlayerKilledEvent event) { Iterator<ItemStack> itel = event.getDrops().iterator(); while (itel.hasNext()) { ItemStack item = itel.next(); if (item != null && furnaces.containsKey(item)) { FakeFurnace furnace = furnaces.remove(item); if (furnace != null) { for (net.minecraft.server.v1_5_R3.ItemStack i : furnace.getContents()) event.getDrops().add(CraftItemStack.asBukkitCopy(i)); } } } } }
true
true
public void onInteract(PlayerInteractEvent event) { ItemStack item = event.getItem(); if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR)) { Player p = event.getPlayer(); if (isSpecialItem(item, craftingStarItemName) && furnacePowderItemId == item.getTypeId()) { p.openWorkbench(null, true); } else if (isSpecialItem(item, furnacePowderItemName) && furnacePowderItemId == item.getTypeId()) { if (!furnaces.containsKey(item)) { furnaces.put(item, new FakeFurnace()); } ((CraftPlayer) p).getHandle().openFurnace(furnaces.get(item)); } } }
public void onInteract(PlayerInteractEvent event) { ItemStack item = event.getItem(); if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR)) { Player p = event.getPlayer(); if (isSpecialItem(item, craftingStarItemName) && craftingStarItemId == item.getTypeId()) { p.openWorkbench(null, true); } else if (isSpecialItem(item, furnacePowderItemName) && furnacePowderItemId == item.getTypeId()) { if (!furnaces.containsKey(item)) { furnaces.put(item, new FakeFurnace()); } ((CraftPlayer) p).getHandle().openFurnace(furnaces.get(item)); } } }
diff --git a/src/nu/validator/htmlparser/impl/Tokenizer.java b/src/nu/validator/htmlparser/impl/Tokenizer.java index f9cc0a8..d7804cf 100755 --- a/src/nu/validator/htmlparser/impl/Tokenizer.java +++ b/src/nu/validator/htmlparser/impl/Tokenizer.java @@ -1,5262 +1,5262 @@ /* * Copyright (c) 2005, 2006, 2007 Henri Sivonen * Copyright (c) 2007-2008 Mozilla Foundation * Portions of comments Copyright 2004-2007 Apple Computer, Inc., Mozilla * Foundation, and Opera Software ASA. * * 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. */ /* * The comments following this one that use the same comment syntax as this * comment are quotes from the WHATWG HTML 5 spec as of 2 June 2007 * amended as of June 18 2008. * That document came with this statement: * "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and * Opera Software ASA. You are granted a license to use, reproduce and * create derivative works of this document." */ package nu.validator.htmlparser.impl; import nu.validator.htmlparser.annotation.Local; import nu.validator.htmlparser.annotation.NoLength; import nu.validator.htmlparser.common.EncodingDeclarationHandler; import nu.validator.htmlparser.common.TokenHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * An implementation of * http://www.whatwg.org/specs/web-apps/current-work/multipage/section-tokenisation.html * * This class implements the <code>Locator</code> interface. This is not an * incidental implementation detail: Users of this class are encouraged to make * use of the <code>Locator</code> nature. * * By default, the tokenizer may report data that XML 1.0 bans. The tokenizer * can be configured to treat these conditions as fatal or to coerce the infoset * to something that XML 1.0 allows. * * @version $Id$ * @author hsivonen */ public final class Tokenizer implements Locator { private static final int DATA = 0; private static final int RCDATA = 1; private static final int CDATA = 2; private static final int PLAINTEXT = 3; private static final int TAG_OPEN = 49; private static final int CLOSE_TAG_OPEN_PCDATA = 50; private static final int TAG_NAME = 58; private static final int BEFORE_ATTRIBUTE_NAME = 4; private static final int ATTRIBUTE_NAME = 5; private static final int AFTER_ATTRIBUTE_NAME = 6; private static final int BEFORE_ATTRIBUTE_VALUE = 7; private static final int ATTRIBUTE_VALUE_DOUBLE_QUOTED = 8; private static final int ATTRIBUTE_VALUE_SINGLE_QUOTED = 9; private static final int ATTRIBUTE_VALUE_UNQUOTED = 10; private static final int AFTER_ATTRIBUTE_VALUE_QUOTED = 11; private static final int BOGUS_COMMENT = 12; private static final int MARKUP_DECLARATION_OPEN = 13; private static final int DOCTYPE = 14; private static final int BEFORE_DOCTYPE_NAME = 15; private static final int DOCTYPE_NAME = 16; private static final int AFTER_DOCTYPE_NAME = 17; private static final int BEFORE_DOCTYPE_PUBLIC_IDENTIFIER = 18; private static final int DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED = 19; private static final int DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED = 20; private static final int AFTER_DOCTYPE_PUBLIC_IDENTIFIER = 21; private static final int BEFORE_DOCTYPE_SYSTEM_IDENTIFIER = 22; private static final int DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED = 23; private static final int DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED = 24; private static final int AFTER_DOCTYPE_SYSTEM_IDENTIFIER = 25; private static final int BOGUS_DOCTYPE = 26; private static final int COMMENT_START = 27; private static final int COMMENT_START_DASH = 28; private static final int COMMENT = 29; private static final int COMMENT_END_DASH = 30; private static final int COMMENT_END = 31; private static final int CLOSE_TAG_OPEN_NOT_PCDATA = 32; private static final int MARKUP_DECLARATION_HYPHEN = 33; private static final int MARKUP_DECLARATION_OCTYPE = 34; private static final int DOCTYPE_UBLIC = 35; private static final int DOCTYPE_YSTEM = 36; private static final int CONSUME_CHARACTER_REFERENCE = 37; private static final int CONSUME_NCR = 38; private static final int CHARACTER_REFERENCE_LOOP = 39; private static final int HEX_NCR_LOOP = 41; private static final int DECIMAL_NRC_LOOP = 42; private static final int HANDLE_NCR_VALUE = 43; private static final int SELF_CLOSING_START_TAG = 44; private static final int CDATA_START = 45; private static final int CDATA_SECTION = 46; private static final int CDATA_RSQB = 47; private static final int CDATA_RSQB_RSQB = 48; private static final int TAG_OPEN_NON_PCDATA = 51; private static final int ESCAPE_EXCLAMATION = 52; private static final int ESCAPE_EXCLAMATION_HYPHEN = 53; private static final int ESCAPE = 54; private static final int ESCAPE_HYPHEN = 55; private static final int ESCAPE_HYPHEN_HYPHEN = 56; private static final int BOGUS_COMMENT_HYPHEN = 57; /** * Magic value for UTF-16 operations. */ private static final int LEAD_OFFSET = 0xD800 - (0x10000 >> 10); /** * Magic value for UTF-16 operations. */ private static final int SURROGATE_OFFSET = 0x10000 - (0xD800 << 10) - 0xDC00; /** * UTF-16 code unit array containing less than and greater than for emitting * those characters on certain parse errors. */ private static final @NoLength char[] LT_GT = { '<', '>' }; /** * UTF-16 code unit array containing less than and solidus for emitting * those characters on certain parse errors. */ private static final @NoLength char[] LT_SOLIDUS = { '<', '/' }; /** * UTF-16 code unit array containing ]] for emitting those characters on * state transitions. */ private static final @NoLength char[] RSQB_RSQB = { ']', ']' }; /** * Array version of U+FFFD. */ private static final char[] REPLACEMENT_CHARACTER = { '\uFFFD' }; /** * Array version of space. */ private static final char[] SPACE = { ' ' }; /** * Array version of line feed. */ private static final char[] LF = { '\n' }; /** * Buffer growth parameter. */ private static final int BUFFER_GROW_BY = 1024; /** * "CDATA[" as <code>char[]</code> */ private static final @NoLength char[] CDATA_LSQB = "CDATA[".toCharArray(); /** * "octype" as <code>char[]</code> */ private static final @NoLength char[] OCTYPE = "octype".toCharArray(); /** * "ublic" as <code>char[]</code> */ private static final @NoLength char[] UBLIC = "ublic".toCharArray(); /** * "ystem" as <code>char[]</code> */ private static final @NoLength char[] YSTEM = "ystem".toCharArray(); private final EncodingDeclarationHandler encodingDeclarationHandler; /** * The token handler. */ private final TokenHandler tokenHandler; /** * The error handler. */ private ErrorHandler errorHandler; /** * The previous <code>char</code> read from the buffer with infoset * alteration applied except for CR. Used for CRLF normalization and * surrogate pair checking. */ private char prev; /** * The current line number in the current resource being parsed. (First line * is 1.) Passed on as locator data. */ private int line; private int linePrev; /** * The current column number in the current resource being tokenized. (First * column is 1, counted by UTF-16 code units.) Passed on as locator data. */ private int col; private int colPrev; private boolean nextCharOnNewLine; private int stateSave; private int returnStateSave; private int index; private boolean forceQuirks; private char additional; private int entCol; private int lo; private int hi; private int candidate; private int strBufMark; private int prevValue; private int value; private boolean seenDigits; private int pos; private int end; private @NoLength char[] buf; private int cstart; /** * The SAX public id for the resource being tokenized. (Only passed to back * as part of locator data.) */ private String publicId; /** * The SAX system id for the resource being tokenized. (Only passed to back * as part of locator data.) */ private String systemId; /** * Buffer for short identifiers. */ private char[] strBuf; /** * Number of significant <code>char</code>s in <code>strBuf</code>. */ private int strBufLen = 0; /** * <code>-1</code> to indicate that <code>strBuf</code> is used or * otherwise an offset to the main buffer. */ private int strBufOffset = -1; /** * Buffer for long strings. */ private char[] longStrBuf; /** * Number of significant <code>char</code>s in <code>longStrBuf</code>. */ private int longStrBufLen = 0; /** * <code>-1</code> to indicate that <code>longStrBuf</code> is used or * otherwise an offset to the main buffer. */ private int longStrBufOffset = -1; /** * The attribute holder. */ private HtmlAttributes attributes; /** * Buffer for expanding NCRs falling into the Basic Multilingual Plane. */ private final char[] bmpChar = new char[1]; /** * Buffer for expanding astral NCRs. */ private final char[] astralChar = new char[2]; /** * Keeps track of PUA warnings. */ private boolean alreadyWarnedAboutPrivateUseCharacters; /** * http://www.whatwg.org/specs/web-apps/current-work/#content2 */ private ContentModelFlag contentModelFlag = ContentModelFlag.PCDATA; /** * The element whose end tag closes the current CDATA or RCDATA element. */ private ElementName contentModelElement = null; /** * <code>true</code> if tokenizing an end tag */ private boolean endTag; /** * The current tag token name. */ private ElementName tagName = null; /** * The current attribute name. */ private AttributeName attributeName = null; /** * Whether comment tokens are emitted. */ private boolean wantsComments = false; /** * If <code>false</code>, <code>addAttribute*()</code> are no-ops. */ private boolean shouldAddAttributes; /** * <code>true</code> when HTML4-specific additional errors are requested. */ private boolean html4; /** * Used together with <code>nonAsciiProhibited</code>. */ private boolean alreadyComplainedAboutNonAscii; /** * Whether the stream is past the first 512 bytes. */ private boolean metaBoundaryPassed; /** * The name of the current doctype token. */ private @Local String doctypeName; /** * The public id of the current doctype token. */ private String publicIdentifier; /** * The system id of the current doctype token. */ private String systemIdentifier; // [NOCPP[ /** * The policy for vertical tab and form feed. */ private XmlViolationPolicy contentSpacePolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for non-space non-XML characters. */ private XmlViolationPolicy contentNonXmlCharPolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for comments. */ private XmlViolationPolicy commentPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy xmlnsPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET; private boolean html4ModeCompatibleWithXhtml1Schemata; private final boolean newAttributesEachTime; // ]NOCPP] private int mappingLangToXmlLang; private boolean shouldSuspend; private Confidence confidence; private PushedLocation pushedLocation; /** * The constructor. * * @param tokenHandler * the handler for receiving tokens */ public Tokenizer(TokenHandler tokenHandler) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = null; this.newAttributesEachTime = false; } public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = encodingDeclarationHandler; this.newAttributesEachTime = false; } public void initLocation(String newPublicId, String newSystemId) { this.systemId = newSystemId; this.publicId = newPublicId; } // [NOCPP[ public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler, boolean newAttributesEachTime) { this.tokenHandler = tokenHandler; this.encodingDeclarationHandler = encodingDeclarationHandler; this.newAttributesEachTime = newAttributesEachTime; } // ]NOCPP] /** * Returns the mappingLangToXmlLang. * * @return the mappingLangToXmlLang */ public boolean isMappingLangToXmlLang() { return mappingLangToXmlLang == AttributeName.HTML_LANG; } /** * Sets the mappingLangToXmlLang. * * @param mappingLangToXmlLang * the mappingLangToXmlLang to set */ public void setMappingLangToXmlLang(boolean mappingLangToXmlLang) { this.mappingLangToXmlLang = mappingLangToXmlLang ? AttributeName.HTML_LANG : AttributeName.HTML; } /** * Sets the error handler. * * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ public void setErrorHandler(ErrorHandler eh) { this.errorHandler = eh; } public ErrorHandler getErrorHandler() { return this.errorHandler; } // [NOCPP[ /** * Sets the commentPolicy. * * @param commentPolicy * the commentPolicy to set */ public void setCommentPolicy(XmlViolationPolicy commentPolicy) { this.commentPolicy = commentPolicy; } /** * Sets the contentNonXmlCharPolicy. * * @param contentNonXmlCharPolicy * the contentNonXmlCharPolicy to set */ public void setContentNonXmlCharPolicy( XmlViolationPolicy contentNonXmlCharPolicy) { this.contentNonXmlCharPolicy = contentNonXmlCharPolicy; } /** * Sets the contentSpacePolicy. * * @param contentSpacePolicy * the contentSpacePolicy to set */ public void setContentSpacePolicy(XmlViolationPolicy contentSpacePolicy) { this.contentSpacePolicy = contentSpacePolicy; } /** * Sets the xmlnsPolicy. * * @param xmlnsPolicy * the xmlnsPolicy to set */ public void setXmlnsPolicy(XmlViolationPolicy xmlnsPolicy) { if (xmlnsPolicy == XmlViolationPolicy.FATAL) { throw new IllegalArgumentException("Can't use FATAL here."); } this.xmlnsPolicy = xmlnsPolicy; } public void setNamePolicy(XmlViolationPolicy namePolicy) { this.namePolicy = namePolicy; } /** * Sets the html4ModeCompatibleWithXhtml1Schemata. * * @param html4ModeCompatibleWithXhtml1Schemata * the html4ModeCompatibleWithXhtml1Schemata to set */ public void setHtml4ModeCompatibleWithXhtml1Schemata( boolean html4ModeCompatibleWithXhtml1Schemata) { this.html4ModeCompatibleWithXhtml1Schemata = html4ModeCompatibleWithXhtml1Schemata; } // ]NOCPP] // For the token handler to call /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, @Local String contentModelElement) { this.contentModelFlag = contentModelFlag; char[] asArray = Portability.newCharArrayFromLocal(contentModelElement); this.contentModelElement = ElementName.elementNameByBuffer(asArray, 0, asArray.length); } /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, ElementName contentModelElement) { this.contentModelFlag = contentModelFlag; this.contentModelElement = contentModelElement; } // start Locator impl /** * @see org.xml.sax.Locator#getPublicId() */ public String getPublicId() { return publicId; } /** * @see org.xml.sax.Locator#getSystemId() */ public String getSystemId() { return systemId; } /** * @see org.xml.sax.Locator#getLineNumber() */ public int getLineNumber() { if (line > 0) { return line; } else { return -1; } } /** * @see org.xml.sax.Locator#getColumnNumber() */ public int getColumnNumber() { if (col > 0) { return col; } else { return -1; } } // end Locator impl // end public API public void notifyAboutMetaBoundary() { metaBoundaryPassed = true; } // [NOCPP[ void turnOnAdditionalHtml4Errors() { html4 = true; } // ]NOCPP] HtmlAttributes emptyAttributes() { // [NOCPP[ if (newAttributesEachTime) { return new HtmlAttributes(mappingLangToXmlLang); } else { // ]NOCPP] return HtmlAttributes.EMPTY_ATTRIBUTES; // [NOCPP[ } // ]NOCPP] } private void detachStrBuf() { // if (strBufOffset == -1) { // return; // } // if (strBufLen > 0) { // if (strBuf.length < strBufLen) { // Portability.releaseArray(strBuf); // strBuf = new char[strBufLen + (strBufLen >> 1)]; // } // System.arraycopy(buf, strBufOffset, strBuf, 0, strBufLen); // } // strBufOffset = -1; } private void detachLongStrBuf() { // if (longStrBufOffset == -1) { // return; // } // if (longStrBufLen > 0) { // if (longStrBuf.length < longStrBufLen) { // Portability.releaseArray(longStrBuf); // longStrBuf = new char[longStrBufLen + (longStrBufLen >> 1)]; // } // System.arraycopy(buf, longStrBufOffset, longStrBuf, 0, // longStrBufLen); // } // longStrBufOffset = -1; } private void clearStrBufAndAppendCurrentC(char c) { strBuf[0] = c; strBufLen = 1; // strBufOffset = pos; } private void clearStrBufAndAppendForceWrite(char c) { strBuf[0] = c; // test strBufLen = 1; // strBufOffset = pos; // buf[pos] = c; } private void clearStrBufForNextState() { strBufLen = 0; // strBufOffset = pos + 1; } /** * Appends to the smaller buffer. * * @param c * the UTF-16 code unit to append */ private void appendStrBuf(char c) { // if (strBufOffset != -1) { // strBufLen++; // } else { if (strBufLen == strBuf.length) { char[] newBuf = new char[strBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length); strBuf = newBuf; } strBuf[strBufLen++] = c; // } } /** * Appends to the smaller buffer. * * @param c * the UTF-16 code unit to append */ private void appendStrBufForceWrite(char c) { // if (strBufOffset != -1) { // strBufLen++; // buf[pos] = c; // } else { if (strBufLen == strBuf.length) { char[] newBuf = new char[strBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length); strBuf = newBuf; } strBuf[strBufLen++] = c; // } } /** * The smaller buffer as a String. * * @return the smaller buffer as a string */ private String strBufToString() { // if (strBufOffset != -1) { // return Portability.newStringFromBuffer(buf, strBufOffset, strBufLen); // } else { return Portability.newStringFromBuffer(strBuf, 0, strBufLen); // } } /** * Emits the smaller buffer as character tokens. * * @throws SAXException * if the token handler threw */ private void emitStrBuf() throws SAXException { if (strBufLen > 0) { // if (strBufOffset != -1) { // tokenHandler.characters(buf, strBufOffset, strBufLen); // } else { tokenHandler.characters(strBuf, 0, strBufLen); // } } } private void clearLongStrBufForNextState() { // longStrBufOffset = pos + 1; longStrBufLen = 0; } private void clearLongStrBuf() { // longStrBufOffset = pos; longStrBufLen = 0; } private void clearLongStrBufAndAppendCurrentC() { longStrBuf[0] = buf[pos]; longStrBufLen = 1; // longStrBufOffset = pos; } private void clearLongStrBufAndAppendToComment(char c) { longStrBuf[0] = c; // longStrBufOffset = pos; longStrBufLen = 1; } /** * Appends to the larger buffer. * * @param c * the UTF-16 code unit to append */ private void appendLongStrBuf(char c) { // if (longStrBufOffset != -1) { // longStrBufLen++; // } else { if (longStrBufLen == longStrBuf.length) { char[] newBuf = new char[longStrBufLen + (longStrBufLen >> 1)]; System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length); Portability.releaseArray(longStrBuf); longStrBuf = newBuf; } longStrBuf[longStrBufLen++] = c; // } } private void appendSecondHyphenToBogusComment() throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); appendLongStrBuf(' '); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); appendLongStrBuf('-'); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); break; } } private void maybeAppendSpaceToBogusComment() throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); appendLongStrBuf(' '); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment."); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment."); break; } } private void adjustDoubleHyphenAndAppendToLongStrBuf(char c) throws SAXException { switch (commentPolicy) { case ALTER_INFOSET: // detachLongStrBuf(); longStrBufLen--; appendLongStrBuf(' '); appendLongStrBuf('-'); // FALLTHROUGH case ALLOW: warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); appendLongStrBuf(c); break; case FATAL: fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment."); break; } } private void appendLongStrBuf(char[] buffer, int offset, int length) { int reqLen = longStrBufLen + length; if (longStrBuf.length < reqLen) { char[] newBuf = new char[reqLen + (reqLen >> 1)]; System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length); Portability.releaseArray(longStrBuf); longStrBuf = newBuf; } System.arraycopy(buffer, offset, longStrBuf, longStrBufLen, length); longStrBufLen = reqLen; } /** * Appends to the larger buffer. * * @param arr * the UTF-16 code units to append */ private void appendLongStrBuf(char[] arr) { // assert longStrBufOffset == -1; appendLongStrBuf(arr, 0, arr.length); } /** * Append the contents of the smaller buffer to the larger one. */ private void appendStrBufToLongStrBuf() { // assert longStrBufOffset == -1; // if (strBufOffset != -1) { // appendLongStrBuf(buf, strBufOffset, strBufLen); // } else { appendLongStrBuf(strBuf, 0, strBufLen); // } } /** * The larger buffer as a string. * * @return the larger buffer as a string */ private String longStrBufToString() { // if (longStrBufOffset != -1) { // return Portability.newStringFromBuffer(buf, longStrBufOffset, // longStrBufLen); // } else { return Portability.newStringFromBuffer(longStrBuf, 0, longStrBufLen); // } } /** * Emits the current comment token. * * @throws SAXException */ private void emitComment(int provisionalHyphens) throws SAXException { if (wantsComments) { // if (longStrBufOffset != -1) { // tokenHandler.comment(buf, longStrBufOffset, longStrBufLen // - provisionalHyphens); // } else { tokenHandler.comment(longStrBuf, 0, longStrBufLen - provisionalHyphens); // } } cstart = pos + 1; } // [NOCPP[ private String toUPlusString(char c) { String hexString = Integer.toHexString(c); switch (hexString.length()) { case 1: return "U+000" + hexString; case 2: return "U+00" + hexString; case 3: return "U+0" + hexString; case 4: return "U+" + hexString; default: throw new RuntimeException("Unreachable."); } } // ]NOCPP] /** * Emits a warning about private use characters if the warning has not been * emitted yet. * * @throws SAXException */ private void warnAboutPrivateUseChar() throws SAXException { if (!alreadyWarnedAboutPrivateUseCharacters) { warn("Document uses the Unicode Private Use Area(s), which should not be used in publicly exchanged documents. (Charmod C073)"); alreadyWarnedAboutPrivateUseCharacters = true; } } /** * Tells if the argument is a BMP PUA character. * * @param c * the UTF-16 code unit to check * @return <code>true</code> if PUA character */ private boolean isPrivateUse(char c) { return c >= '\uE000' && c <= '\uF8FF'; } /** * Tells if the argument is an astral PUA character. * * @param c * the code point to check * @return <code>true</code> if astral private use */ private boolean isAstralPrivateUse(int c) { return (c >= 0xF0000 && c <= 0xFFFFD) || (c >= 0x100000 && c <= 0x10FFFD); } /** * Tells if the argument is a non-character (works for BMP and astral). * * @param c * the code point to check * @return <code>true</code> if non-character */ private boolean isNonCharacter(int c) { return (c & 0xFFFE) == 0xFFFE; } /** * Flushes coalesced character tokens. * * @throws SAXException */ private void flushChars() throws SAXException { if (pos > cstart) { int currLine = line; int currCol = col; line = linePrev; col = colPrev; tokenHandler.characters(buf, cstart, pos - cstart); line = currLine; col = currCol; } cstart = Integer.MAX_VALUE; } /** * Reports an condition that would make the infoset incompatible with XML * 1.0 as fatal. * * @param message * the message * @throws SAXException * @throws SAXParseException */ public void fatal(String message) throws SAXException { SAXParseException spe = new SAXParseException(message, this); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } /** * Reports a Parse Error. * * @param message * the message * @throws SAXException */ public void err(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.error(spe); } public void errTreeBuilder(String message) throws SAXException { ErrorHandler eh = null; if (tokenHandler instanceof TreeBuilder<?>) { TreeBuilder<?> treeBuilder = (TreeBuilder<?>) tokenHandler; eh = treeBuilder.getErrorHandler(); } if (eh == null) { eh = errorHandler; } if (eh == null) { return; } SAXParseException spe = new SAXParseException(message, this); eh.error(spe); } /** * Reports a warning * * @param message * the message * @throws SAXException */ public void warn(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.warning(spe); } /** * */ private void resetAttributes() { // [NOCPP[ if (newAttributesEachTime) { attributes = null; } else { // ]NOCPP] attributes.clear(); // [NOCPP[ } // ]NOCPP] } private ElementName strBufToElementNameString() { // if (strBufOffset != -1) { // return ElementName.elementNameByBuffer(buf, strBufOffset, strBufLen); // } else { return ElementName.elementNameByBuffer(strBuf, 0, strBufLen); // } } private int emitCurrentTagToken(boolean selfClosing) throws SAXException { cstart = pos + 1; if (selfClosing && endTag) { err("Stray \u201C/\u201D at the end of an end tag."); } int rv = Tokenizer.DATA; HtmlAttributes attrs = (attributes == null ? HtmlAttributes.EMPTY_ATTRIBUTES : attributes); if (endTag) { /* * When an end tag token is emitted, the content model flag must be * switched to the PCDATA state. */ contentModelFlag = ContentModelFlag.PCDATA; if (attrs.getLength() != 0) { /* * When an end tag token is emitted with attributes, that is a * parse error. */ err("End tag had attributes."); } tokenHandler.endTag(tagName); } else { tokenHandler.startTag(tagName, attrs, selfClosing); switch (contentModelFlag) { case PCDATA: rv = Tokenizer.DATA; break; case CDATA: rv = Tokenizer.CDATA; break; case RCDATA: rv = Tokenizer.RCDATA; break; case PLAINTEXT: rv = Tokenizer.PLAINTEXT; } } resetAttributes(); return rv; } private void attributeNameComplete() throws SAXException { // if (strBufOffset != -1) { // attributeName = AttributeName.nameByBuffer(buf, strBufOffset, // strBufLen, namePolicy != XmlViolationPolicy.ALLOW); // } else { attributeName = AttributeName.nameByBuffer(strBuf, 0, strBufLen, namePolicy != XmlViolationPolicy.ALLOW); // } // [NOCPP[ if (attributes == null) { attributes = new HtmlAttributes(mappingLangToXmlLang); } // ]NOCPP] /* * When the user agent leaves the attribute name state (and before * emitting the tag token, if appropriate), the complete attribute's * name must be compared to the other attributes on the same token; if * there is already an attribute on the token with the exact same name, * then this is a parse error and the new attribute must be dropped, * along with the value that gets associated with it (if any). */ if (attributes.contains(attributeName)) { shouldAddAttributes = false; err("Duplicate attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D."); } else { shouldAddAttributes = true; // if (namePolicy == XmlViolationPolicy.ALLOW) { // shouldAddAttributes = true; // } else { // if (NCName.isNCName(attributeName)) { // shouldAddAttributes = true; // } else { // if (namePolicy == XmlViolationPolicy.FATAL) { // fatal("Attribute name \u201C" + attributeName // + "\u201D is not an NCName."); // } else { // shouldAddAttributes = false; // warn("Attribute name \u201C" // + attributeName // + "\u201D is not an NCName. Ignoring the attribute."); // } // } // } } } private void addAttributeWithoutValue() throws SAXException { // [NOCPP[ if (metaBoundaryPassed && AttributeName.CHARSET == attributeName && ElementName.META == tagName) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } // ]NOCPP] if (shouldAddAttributes) { // [NOCPP[ if (html4) { if (attributeName.isBoolean()) { if (html4ModeCompatibleWithXhtml1Schemata) { attributes.addAttribute(attributeName, attributeName.getLocal(AttributeName.HTML), xmlnsPolicy); } else { attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { err("Attribute value omitted for a non-boolean attribute. (HTML4-only error.)"); attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { if (AttributeName.SRC == attributeName || AttributeName.HREF == attributeName) { warn("Attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D without an explicit value seen. The attribute may be dropped by IE7."); } // ]NOCPP] attributes.addAttribute(attributeName, "", xmlnsPolicy); // [NOCPP[ } // ]NOCPP] } } private void addAttributeWithValue() throws SAXException { // [NOCPP[ if (metaBoundaryPassed && ElementName.META == tagName && AttributeName.CHARSET == attributeName) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } // ]NOCPP] if (shouldAddAttributes) { String value = longStrBufToString(); // [NOCPP[ if (!endTag && html4 && html4ModeCompatibleWithXhtml1Schemata && attributeName.isCaseFolded()) { value = newAsciiLowerCaseStringFromString(value); } // ]NOCPP] attributes.addAttribute(attributeName, value, xmlnsPolicy); } } // [NOCPP[ private static String newAsciiLowerCaseStringFromString(String str) { if (str == null) { return null; } char[] buf = new char[str.length()]; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 'A' && c <= 'Z') { c += 0x20; } buf[i] = c; } return new String(buf); } // ]NOCPP] public void start() throws SAXException { strBuf = new char[64]; longStrBuf = new char[1024]; alreadyComplainedAboutNonAscii = false; contentModelFlag = ContentModelFlag.PCDATA; line = linePrev = 0; col = colPrev = 1; nextCharOnNewLine = true; prev = '\u0000'; html4 = false; alreadyWarnedAboutPrivateUseCharacters = false; metaBoundaryPassed = false; tokenHandler.startTokenization(this); wantsComments = tokenHandler.wantsComments(); switch (contentModelFlag) { case PCDATA: stateSave = Tokenizer.DATA; break; case CDATA: stateSave = Tokenizer.CDATA; break; case RCDATA: stateSave = Tokenizer.RCDATA; break; case PLAINTEXT: stateSave = Tokenizer.PLAINTEXT; } index = 0; forceQuirks = false; additional = '\u0000'; entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; prevValue = -1; value = 0; seenDigits = false; shouldSuspend = false; // [NOCPP[ if (!newAttributesEachTime) { // ]NOCPP] attributes = new HtmlAttributes(mappingLangToXmlLang); // [NOCPP[ } // ]NOCPP] } public boolean tokenizeBuffer(UTF16Buffer buffer) throws SAXException { buf = buffer.getBuffer(); int state = stateSave; int returnState = returnStateSave; char c = '\u0000'; shouldSuspend = false; int start = buffer.getStart(); /** * The index of the last <code>char</code> read from <code>buf</code>. */ pos = start - 1; /** * The index of the first <code>char</code> in <code>buf</code> that * is part of a coalesced run of character tokens or * <code>Integer.MAX_VALUE</code> if there is not a current run being * coalesced. */ switch (state) { case DATA: case RCDATA: case CDATA: case PLAINTEXT: case CDATA_SECTION: case ESCAPE: case ESCAPE_EXCLAMATION: case ESCAPE_EXCLAMATION_HYPHEN: case ESCAPE_HYPHEN: case ESCAPE_HYPHEN_HYPHEN: cstart = start; break; default: cstart = Integer.MAX_VALUE; break; } /** * The number of <code>char</code>s in <code>buf</code> that have * meaning. (The rest of the array is garbage and should not be * examined.) */ end = buffer.getEnd(); boolean reconsume = false; stateLoop(state, c, reconsume, returnState); detachStrBuf(); detachLongStrBuf(); if (pos == end) { // exiting due to end of buffer buffer.setStart(pos); } else { buffer.setStart(pos + 1); } if (prev == '\r') { prev = ' '; return true; } else { return false; } } // WARNING When editing this, makes sure the bytecode length shown by javap // stays under 8000 bytes! private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case DATA: dataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: tagopenloop: for (;;) { /* * The behavior of this state depends on the content * model flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ c = read(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A * LATIN CAPITAL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's * code point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A * LATIN SMALL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } switch (c) { case '\u0000': break stateloop; case '!': /* * U+0021 EXCLAMATION MARK (!) Switch to the * markup declaration open state. */ state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the close tag * open state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; case '?': /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment('?'); state = Tokenizer.BOGUS_COMMENT; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token * and a U+003E GREATER-THAN SIGN character * token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } } // FALL THROUGH DON'T REORDER case TAG_NAME: tagnameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; break tagnameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_NAME: beforeattributenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; break beforeattributenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_NAME: attributenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; break attributenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_VALUE: beforeattributevalueloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; break beforeattributevalueloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ clearLongStrBuf(); state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ clearLongStrBufAndAppendCurrentC(); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_VALUE_DOUBLE_QUOTED: attributevaluedoublequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; break attributevaluedoublequotedloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the * additional allowed character being U+0022 * QUOTATION MARK ("). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_ATTRIBUTE_VALUE_QUOTED: afterattributevaluequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; break afterattributevaluequotedloop; // continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before * attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with no + * additional allowed character. */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } // XXX reorder point case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after attribute name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } // XXX reorder point case BOGUS_COMMENT: boguscommentloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to and including the first * U+003E GREATER-THAN SIGN character (>) or the end of * the file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the * character immediately before the last consumed * character (i.e. up to the character just before the * U+003E or EOF character). (If the comment was started * by the end of the file (EOF), the token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT_HYPHEN; break boguscommentloop; default: appendLongStrBuf(c); continue; } } // FALLTHRU DON'T REORDER case BOGUS_COMMENT_HYPHEN: boguscommenthyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '>': maybeAppendSpaceToBogusComment(); emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendSecondHyphenToBogusComment(); continue boguscommenthyphenloop; default: appendLongStrBuf(c); continue stateloop; } } // XXX reorder point case MARKUP_DECLARATION_OPEN: markupdeclarationopenloop: for (;;) { c = read(); /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * If the next two characters are both U+002D * HYPHEN-MINUS (-) characters, consume those two * characters, create a comment token whose data is the * empty string, and switch to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE * state. * * Otherwise, if the insertion mode is "in foreign * content" and the current node is not an element in * the HTML namespace and the next seven characters are * a case-sensitive match for the string "[CDATA[" (the * five uppercase letters "CDATA" with a U+005B LEFT * SQUARE BRACKET character before and after), then * consume those characters and switch to the CDATA * section state (which is unrelated to the content * model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, * if any, is the first character that will be in the * comment. */ switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufAndAppendToComment(c); state = Tokenizer.MARKUP_DECLARATION_HYPHEN; break markupdeclarationopenloop; // continue stateloop; case 'd': case 'D': clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); clearLongStrBuf(); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case MARKUP_DECLARATION_HYPHEN: markupdeclarationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufForNextState(); state = Tokenizer.COMMENT_START; break markupdeclarationhyphenloop; // continue stateloop; default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_START: commentstartloop: for (;;) { c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ appendLongStrBuf(c); state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(0); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; break commentstartloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT: commentloop: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END_DASH; break commentloop; // continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Stay in the comment state. */ continue; } } // FALLTHRU DON'T REORDER case COMMENT_END_DASH: commentenddashloop: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; break commentenddashloop; // continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS * (-) character and the input character to the * comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(2); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // XXX reorder point case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(1); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } // XXX reorder point case MARKUP_DECLARATION_OCTYPE: markupdeclarationdoctypeloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // OCTYPE.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; break markupdeclarationdoctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE: doctypeloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; break doctypeloop; // continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; break doctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_NAME: beforedoctypenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ /* * Set the token's name name to the current * input character. */ clearStrBufAndAppendCurrentC(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; break beforedoctypenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_NAME: doctypenameloop: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after DOCTYPE name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; break doctypenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_NAME: afterdoctypenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; break afterdoctypenameloop; // continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_UBLIC: doctypeublicloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < 5) { // UBLIC.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { bogusDoctype(); // forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; break doctypeublicloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: beforedoctypepublicidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE public identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; break beforedoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: doctypepublicidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; break doctypepublicidentifierdoublequotedloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: afterdoctypepublicidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; break afterdoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: doctypesystemidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: afterdoctypesystemidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ bogusDoctypeWithoutQuirks(); state = Tokenizer.BOGUS_DOCTYPE; break afterdoctypesystemidentifierloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BOGUS_DOCTYPE: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } // XXX reorder point case DOCTYPE_YSTEM: doctypeystemloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before * DOCTYPE system identifier state. */ if (index < 5) { // YSTEM.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { bogusDoctype(); state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; break doctypeystemloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: beforedoctypesystemidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE system identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; break beforedoctypesystemidentifierloop; // continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // XXX reorder point case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } // XXX reorder point case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // CDATA_LSQB.length if (c == Tokenizer.CDATA_LSQB[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_SECTION; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_SECTION: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_SINGLE_QUOTED: attributevaluesinglequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the + * additional allowed character being U+0027 * APOSTROPHE ('). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; break attributevaluesinglequotedloop; // continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the * character reference fails. */ /* * This section defines how to consume a character * reference. This definition is used when parsing character * references in text and in attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references * table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { // if (strBufOffset != -1) { // ch = buf[strBufOffset + strBufMark]; // } else { ch = strBuf[strBufMark]; // } } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if (strBufOffset != -1) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(buf[strBufOffset + i]); } } else { tokenHandler.characters(buf, strBufOffset + strBufMark, strBufLen - strBufMark); } } else { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } // XXX reorder point case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; if ((returnState & (~1)) == 0) { cstart = pos + 1; } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; // XXX reorder point case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } // XXX reorder point case PLAINTEXT: plaintextloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBufForNextState(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: escapeexclamationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapeexclamationhyphenloop; // continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: escapehyphenhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; break escapehyphenhyphenloop; // continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokenizer (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020 * SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS * (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. - if (index < contentModelElement.name.length()) { - char e = contentModelElement.name.charAt(index); + if (index < contentModelElement.nameAsArray.length) { + char e = contentModelElement.nameAsArray[index]; char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { // [NOCPP[ if (html4) { if (ElementName.IFRAME != contentModelElement) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" - + contentModelElement + + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { // ]NOCPP] warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" - + contentModelElement + + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but this did not close the element."); // [NOCPP[ } // ]NOCPP] } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C FORM FEED (FF) U+0020 * SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = returnState; continue stateloop; } } } // XXX reorder point case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } } } flushChars(); if (prev == '\r' && pos != end) { pos--; col--; } // Save locals stateSave = state; returnStateSave = returnState; } private void bogusDoctype() throws SAXException { err("Bogus doctype."); forceQuirks = true; } private void bogusDoctypeWithoutQuirks() throws SAXException { err("Bogus doctype."); forceQuirks = false; } private void emitOrAppendStrBuf(int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendStrBufToLongStrBuf(); } else { emitStrBuf(); } } private void handleNcrValue(int returnState) throws SAXException { /* * If one or more characters match the range, then take them all and * interpret the string of characters as a number (either hexadecimal or * decimal as appropriate). */ if (value >= 0x80 && value <= 0x9f) { /* * If that number is one of the numbers in the first column of the * following table, then this is a parse error. */ err("A numeric character reference expanded to the C1 controls range."); /* * Find the row with that number in the first column, and return a * character token for the Unicode character given in the second * column of that row. */ char[] val = NamedCharacters.WINDOWS_1252[value - 0x80]; emitOrAppend(val, returnState); } else if (value == 0x0D) { err("A numeric character reference expanded to carriage return."); emitOrAppend(Tokenizer.LF, returnState); } else if (value == 0xC && contentSpacePolicy != XmlViolationPolicy.ALLOW) { if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) { emitOrAppend(Tokenizer.SPACE, returnState); } else if (contentSpacePolicy == XmlViolationPolicy.FATAL) { fatal("A character reference expanded to a form feed which is not legal XML 1.0 white space."); } } else if (value == 0xB && contentNonXmlCharPolicy != XmlViolationPolicy.ALLOW) { if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) { emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (contentSpacePolicy == XmlViolationPolicy.FATAL) { fatal("A character reference expanded to a vtab which is not a legal XML 1.0 character."); } } else if ((value >= 0x0000 && value <= 0x0008) || (value >= 0x000E && value <= 0x001F) || value == 0x007F) { /* * Otherwise, if the number is in the range 0x0000 to 0x0008, 0x000E * to 0x001F, 0x007F to 0x009F, 0xD800 to 0xDFFF , 0xFDD0 to 0xFDDF, * or is one of 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, * 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, * 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, * 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, * 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or * 0x10FFFF, or is higher than 0x10FFFF, then this is a parse error; * return a character token for the U+FFFD REPLACEMENT CHARACTER * character instead. */ err("Character reference expands to a control character (" + toUPlusString((char) value) + ")."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if ((value & 0xF800) == 0xD800) { err("Character reference expands to a surrogate."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (isNonCharacter(value)) { err("Character reference expands to a non-character."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (value <= 0xFFFF) { /* * Otherwise, return a character token for the Unicode character * whose code point is that number. */ char ch = (char) value; if (errorHandler != null && isPrivateUse(ch)) { warnAboutPrivateUseChar(); } bmpChar[0] = ch; emitOrAppend(bmpChar, returnState); } else if (value <= 0x10FFFF) { if (errorHandler != null && isAstralPrivateUse(value)) { warnAboutPrivateUseChar(); } astralChar[0] = (char) (Tokenizer.LEAD_OFFSET + (value >> 10)); astralChar[1] = (char) (0xDC00 + (value & 0x3FF)); emitOrAppend(astralChar, returnState); } else { err("Character reference outside the permissible Unicode range."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } } public void eof() throws SAXException { int state = stateSave; int returnState = returnStateSave; eofloop: for (;;) { switch (state) { case TAG_OPEN_NON_PCDATA: /* * Otherwise, emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case TAG_OPEN: /* * The behavior of this state depends on the content model * flag. */ /* * Anything else Parse error. */ err("End of file in the tag open state."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case CLOSE_TAG_OPEN_NOT_PCDATA: break eofloop; case CLOSE_TAG_OPEN_PCDATA: /* EOF Parse error. */ err("Saw \u201C</\u201D immediately before end of file."); /* * Emit a U+003C LESS-THAN SIGN character token and a U+002F * SOLIDUS character token. */ tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); /* * Reconsume the EOF character in the data state. */ break eofloop; case TAG_NAME: /* * EOF Parse error. */ err("End of file seen when looking for tag name"); /* * Emit the current tag token. */ tagName = strBufToElementNameString(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case BEFORE_ATTRIBUTE_NAME: case AFTER_ATTRIBUTE_VALUE_QUOTED: case SELF_CLOSING_START_TAG: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case ATTRIBUTE_NAME: /* * EOF Parse error. */ err("End of file occurred in an attribute name."); /* * Emit the current tag token. */ attributeNameComplete(); addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_ATTRIBUTE_NAME: case BEFORE_ATTRIBUTE_VALUE: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case ATTRIBUTE_VALUE_DOUBLE_QUOTED: case ATTRIBUTE_VALUE_SINGLE_QUOTED: case ATTRIBUTE_VALUE_UNQUOTED: /* EOF Parse error. */ err("End of file reached when inside an attribute value."); /* Emit the current tag token. */ addAttributeWithValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case BOGUS_COMMENT: emitComment(0); break eofloop; case BOGUS_COMMENT_HYPHEN: maybeAppendSpaceToBogusComment(); emitComment(0); break eofloop; case MARKUP_DECLARATION_OPEN: err("Bogus comment."); clearLongStrBuf(); emitComment(0); break eofloop; case MARKUP_DECLARATION_HYPHEN: err("Bogus comment."); emitComment(0); break eofloop; case MARKUP_DECLARATION_OCTYPE: err("Bogus comment."); emitComment(0); break eofloop; case COMMENT_START: case COMMENT: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(0); /* * Reconsume the EOF character in the data state. */ break eofloop; case COMMENT_END: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(2); /* * Reconsume the EOF character in the data state. */ break eofloop; case COMMENT_END_DASH: case COMMENT_START_DASH: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(1); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE: case BEFORE_DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Create a new DOCTYPE token. Set its force-quirks flag to * on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_UBLIC: case DOCTYPE_YSTEM: case AFTER_DOCTYPE_NAME: case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside public identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside system identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case BOGUS_DOCTYPE: /* * Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Reconsume the EOF character in the data state. */ break eofloop; case CONSUME_CHARACTER_REFERENCE: /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the entity * fails. */ /* * This section defines how to consume an entity. This * definition is used when parsing entities in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ emitOrAppendStrBuf(returnState); state = returnState; continue; case CHARACTER_REFERENCE_LOOP: outer: for (;;) { char c = '\u0000'; entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references * table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\201D."); emitOrAppendStrBuf(returnState); state = returnState; continue eofloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = '\u0000'; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; continue eofloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } state = returnState; continue eofloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: case DECIMAL_NRC_LOOP: case HEX_NCR_LOOP: /* * If no characters match the range, then don't consume any * characters (and unconsume the U+0023 NUMBER SIGN * character and, if appropriate, the X character). This is * a parse error; nothing is returned. * * Otherwise, if the next character is a U+003B SEMICOLON, * consume that too. If it isn't, there is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); state = returnState; continue; } else { err("Character reference was not terminated by a semicolon."); // FALL THROUGH continue stateloop; } // WARNING previous state sets reconsume handleNcrValue(returnState); state = returnState; continue; case DATA: default: break eofloop; } } // case DATA: /* * EOF Emit an end-of-file token. */ tokenHandler.eof(); return; } private char read() throws SAXException { char c; pos++; if (pos == end) { return '\u0000'; } linePrev = line; colPrev = col; if (nextCharOnNewLine) { line++; col = 1; nextCharOnNewLine = false; } else { col++; } c = buf[pos]; // [NOCPP[ if (errorHandler == null && contentNonXmlCharPolicy == XmlViolationPolicy.ALLOW) { // ]NOCPP] switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ c = buf[pos] = '\uFFFD'; break; } // [NOCPP[ } else { if (confidence == Confidence.TENTATIVE && !alreadyComplainedAboutNonAscii && c > '\u007F') { complainAboutNonAscii(); alreadyComplainedAboutNonAscii = true; } switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ err("Found U+0000 in the character stream."); c = buf[pos] = '\uFFFD'; break; case '\u000C': if (contentNonXmlCharPolicy == XmlViolationPolicy.FATAL) { fatal("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } else { if (contentNonXmlCharPolicy == XmlViolationPolicy.ALTER_INFOSET) { c = buf[pos] = ' '; } warn("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } break; default: if ((c & 0xFC00) == 0xDC00) { // Got a low surrogate. See if prev was high // surrogate if ((prev & 0xFC00) == 0xD800) { int intVal = (prev << 10) + c + Tokenizer.SURROGATE_OFFSET; if (isNonCharacter(intVal)) { err("Astral non-character."); } if (isAstralPrivateUse(intVal)) { warnAboutPrivateUseChar(); } } else { // XXX figure out what to do about lone high // surrogates err("Found low surrogate without high surrogate."); // c = buf[pos] = '\uFFFD'; } } else if ((c < ' ' || isNonCharacter(c)) && (c != '\t')) { switch (contentNonXmlCharPolicy) { case FATAL: fatal("Forbidden code point " + toUPlusString(c) + "."); break; case ALTER_INFOSET: c = buf[pos] = '\uFFFD'; // fall through case ALLOW: err("Forbidden code point " + toUPlusString(c) + "."); } } else if ((c >= '\u007F') && (c <= '\u009F') || (c >= '\uFDD0') && (c <= '\uFDDF')) { err("Forbidden code point " + toUPlusString(c) + "."); } else if (isPrivateUse(c)) { warnAboutPrivateUseChar(); } } } // ]NOCPP] prev = c; return c; } private void complainAboutNonAscii() throws SAXException { String encoding = ""; if (true) { err("The character encoding of the document was not explicit but the document contains non-ASCII."); } else { err("No explicit character encoding declaration has been seen yet (assumed \u201C" + encoding + "\u201D) but the document contains non-ASCII."); } } public void internalEncodingDeclaration(String internalCharset) throws SAXException { if (encodingDeclarationHandler != null) { encodingDeclarationHandler.internalEncodingDeclaration(internalCharset); } } /** * @param val * @throws SAXException */ private void emitOrAppend(char[] val, int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendLongStrBuf(val); } else { tokenHandler.characters(val, 0, val.length); } } public void end() throws SAXException { strBuf = null; longStrBuf = null; systemIdentifier = null; publicIdentifier = null; doctypeName = null; tagName = null; attributeName = null; tokenHandler.endTokenization(); if (attributes != null) { attributes.clear(); attributes.release(); } } public void requestSuspension() { shouldSuspend = true; } /** * Returns the alreadyComplainedAboutNonAscii. * * @return the alreadyComplainedAboutNonAscii */ public boolean isAlreadyComplainedAboutNonAscii() { return alreadyComplainedAboutNonAscii; } }
false
true
private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case DATA: dataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: tagopenloop: for (;;) { /* * The behavior of this state depends on the content * model flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ c = read(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A * LATIN CAPITAL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's * code point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A * LATIN SMALL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } switch (c) { case '\u0000': break stateloop; case '!': /* * U+0021 EXCLAMATION MARK (!) Switch to the * markup declaration open state. */ state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the close tag * open state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; case '?': /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment('?'); state = Tokenizer.BOGUS_COMMENT; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token * and a U+003E GREATER-THAN SIGN character * token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } } // FALL THROUGH DON'T REORDER case TAG_NAME: tagnameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; break tagnameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_NAME: beforeattributenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; break beforeattributenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_NAME: attributenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; break attributenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_VALUE: beforeattributevalueloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; break beforeattributevalueloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ clearLongStrBuf(); state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ clearLongStrBufAndAppendCurrentC(); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_VALUE_DOUBLE_QUOTED: attributevaluedoublequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; break attributevaluedoublequotedloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the * additional allowed character being U+0022 * QUOTATION MARK ("). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_ATTRIBUTE_VALUE_QUOTED: afterattributevaluequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; break afterattributevaluequotedloop; // continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before * attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with no + * additional allowed character. */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } // XXX reorder point case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after attribute name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } // XXX reorder point case BOGUS_COMMENT: boguscommentloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to and including the first * U+003E GREATER-THAN SIGN character (>) or the end of * the file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the * character immediately before the last consumed * character (i.e. up to the character just before the * U+003E or EOF character). (If the comment was started * by the end of the file (EOF), the token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT_HYPHEN; break boguscommentloop; default: appendLongStrBuf(c); continue; } } // FALLTHRU DON'T REORDER case BOGUS_COMMENT_HYPHEN: boguscommenthyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '>': maybeAppendSpaceToBogusComment(); emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendSecondHyphenToBogusComment(); continue boguscommenthyphenloop; default: appendLongStrBuf(c); continue stateloop; } } // XXX reorder point case MARKUP_DECLARATION_OPEN: markupdeclarationopenloop: for (;;) { c = read(); /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * If the next two characters are both U+002D * HYPHEN-MINUS (-) characters, consume those two * characters, create a comment token whose data is the * empty string, and switch to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE * state. * * Otherwise, if the insertion mode is "in foreign * content" and the current node is not an element in * the HTML namespace and the next seven characters are * a case-sensitive match for the string "[CDATA[" (the * five uppercase letters "CDATA" with a U+005B LEFT * SQUARE BRACKET character before and after), then * consume those characters and switch to the CDATA * section state (which is unrelated to the content * model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, * if any, is the first character that will be in the * comment. */ switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufAndAppendToComment(c); state = Tokenizer.MARKUP_DECLARATION_HYPHEN; break markupdeclarationopenloop; // continue stateloop; case 'd': case 'D': clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); clearLongStrBuf(); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case MARKUP_DECLARATION_HYPHEN: markupdeclarationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufForNextState(); state = Tokenizer.COMMENT_START; break markupdeclarationhyphenloop; // continue stateloop; default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_START: commentstartloop: for (;;) { c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ appendLongStrBuf(c); state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(0); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; break commentstartloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT: commentloop: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END_DASH; break commentloop; // continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Stay in the comment state. */ continue; } } // FALLTHRU DON'T REORDER case COMMENT_END_DASH: commentenddashloop: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; break commentenddashloop; // continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS * (-) character and the input character to the * comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(2); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // XXX reorder point case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(1); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } // XXX reorder point case MARKUP_DECLARATION_OCTYPE: markupdeclarationdoctypeloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // OCTYPE.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; break markupdeclarationdoctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE: doctypeloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; break doctypeloop; // continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; break doctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_NAME: beforedoctypenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ /* * Set the token's name name to the current * input character. */ clearStrBufAndAppendCurrentC(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; break beforedoctypenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_NAME: doctypenameloop: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after DOCTYPE name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; break doctypenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_NAME: afterdoctypenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; break afterdoctypenameloop; // continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_UBLIC: doctypeublicloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < 5) { // UBLIC.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { bogusDoctype(); // forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; break doctypeublicloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: beforedoctypepublicidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE public identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; break beforedoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: doctypepublicidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; break doctypepublicidentifierdoublequotedloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: afterdoctypepublicidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; break afterdoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: doctypesystemidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: afterdoctypesystemidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ bogusDoctypeWithoutQuirks(); state = Tokenizer.BOGUS_DOCTYPE; break afterdoctypesystemidentifierloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BOGUS_DOCTYPE: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } // XXX reorder point case DOCTYPE_YSTEM: doctypeystemloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before * DOCTYPE system identifier state. */ if (index < 5) { // YSTEM.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { bogusDoctype(); state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; break doctypeystemloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: beforedoctypesystemidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE system identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; break beforedoctypesystemidentifierloop; // continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // XXX reorder point case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } // XXX reorder point case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // CDATA_LSQB.length if (c == Tokenizer.CDATA_LSQB[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_SECTION; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_SECTION: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_SINGLE_QUOTED: attributevaluesinglequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the + * additional allowed character being U+0027 * APOSTROPHE ('). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; break attributevaluesinglequotedloop; // continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the * character reference fails. */ /* * This section defines how to consume a character * reference. This definition is used when parsing character * references in text and in attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references * table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { // if (strBufOffset != -1) { // ch = buf[strBufOffset + strBufMark]; // } else { ch = strBuf[strBufMark]; // } } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if (strBufOffset != -1) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(buf[strBufOffset + i]); } } else { tokenHandler.characters(buf, strBufOffset + strBufMark, strBufLen - strBufMark); } } else { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } // XXX reorder point case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; if ((returnState & (~1)) == 0) { cstart = pos + 1; } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; // XXX reorder point case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } // XXX reorder point case PLAINTEXT: plaintextloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBufForNextState(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: escapeexclamationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapeexclamationhyphenloop; // continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: escapehyphenhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; break escapehyphenhyphenloop; // continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokenizer (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020 * SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS * (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.name.length()) { char e = contentModelElement.name.charAt(index); char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { // [NOCPP[ if (html4) { if (ElementName.IFRAME != contentModelElement) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { // ]NOCPP] warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); // [NOCPP[ } // ]NOCPP] } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C FORM FEED (FF) U+0020 * SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = returnState; continue stateloop; } } } // XXX reorder point case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } } } flushChars(); if (prev == '\r' && pos != end) { pos--; col--; } // Save locals stateSave = state; returnStateSave = returnState; }
private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case DATA: dataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: tagopenloop: for (;;) { /* * The behavior of this state depends on the content * model flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ c = read(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A * LATIN CAPITAL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's * code point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A * LATIN SMALL LETTER Z Create a new start tag * token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will * be filled in before it is emitted.) */ break tagopenloop; // continue stateloop; } switch (c) { case '\u0000': break stateloop; case '!': /* * U+0021 EXCLAMATION MARK (!) Switch to the * markup declaration open state. */ state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the close tag * open state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; case '?': /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment('?'); state = Tokenizer.BOGUS_COMMENT; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token * and a U+003E GREATER-THAN SIGN character * token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } } // FALL THROUGH DON'T REORDER case TAG_NAME: tagnameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; break tagnameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_NAME: beforeattributenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; break beforeattributenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_NAME: attributenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; break attributenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBufForceWrite((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } // FALLTHRU DON'T REORDER case BEFORE_ATTRIBUTE_VALUE: beforeattributevalueloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; break beforeattributevalueloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ clearLongStrBuf(); state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ clearLongStrBufForNextState(); state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ clearLongStrBufAndAppendCurrentC(); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } // FALLTHRU DON'T REORDER case ATTRIBUTE_VALUE_DOUBLE_QUOTED: attributevaluedoublequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; break attributevaluedoublequotedloop; // continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the * additional allowed character being U+0022 * QUOTATION MARK ("). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_ATTRIBUTE_VALUE_QUOTED: afterattributevaluequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; break afterattributevaluequotedloop; // continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before * attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with no + * additional allowed character. */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } // XXX reorder point case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after attribute name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ clearStrBufAndAppendCurrentC(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } // XXX reorder point case BOGUS_COMMENT: boguscommentloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to and including the first * U+003E GREATER-THAN SIGN character (>) or the end of * the file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the * character immediately before the last consumed * character (i.e. up to the character just before the * U+003E or EOF character). (If the comment was started * by the end of the file (EOF), the token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT_HYPHEN; break boguscommentloop; default: appendLongStrBuf(c); continue; } } // FALLTHRU DON'T REORDER case BOGUS_COMMENT_HYPHEN: boguscommenthyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '>': maybeAppendSpaceToBogusComment(); emitComment(0); state = Tokenizer.DATA; continue stateloop; case '-': appendSecondHyphenToBogusComment(); continue boguscommenthyphenloop; default: appendLongStrBuf(c); continue stateloop; } } // XXX reorder point case MARKUP_DECLARATION_OPEN: markupdeclarationopenloop: for (;;) { c = read(); /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * If the next two characters are both U+002D * HYPHEN-MINUS (-) characters, consume those two * characters, create a comment token whose data is the * empty string, and switch to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE * state. * * Otherwise, if the insertion mode is "in foreign * content" and the current node is not an element in * the HTML namespace and the next seven characters are * a case-sensitive match for the string "[CDATA[" (the * five uppercase letters "CDATA" with a U+005B LEFT * SQUARE BRACKET character before and after), then * consume those characters and switch to the CDATA * section state (which is unrelated to the content * model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, * if any, is the first character that will be in the * comment. */ switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufAndAppendToComment(c); state = Tokenizer.MARKUP_DECLARATION_HYPHEN; break markupdeclarationopenloop; // continue stateloop; case 'd': case 'D': clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { clearLongStrBufAndAppendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); clearLongStrBuf(); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case MARKUP_DECLARATION_HYPHEN: markupdeclarationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': clearLongStrBufForNextState(); state = Tokenizer.COMMENT_START; break markupdeclarationhyphenloop; // continue stateloop; default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_START: commentstartloop: for (;;) { c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ appendLongStrBuf(c); state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(0); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; break commentstartloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT: commentloop: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END_DASH; break commentloop; // continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendLongStrBuf(c); /* * Stay in the comment state. */ continue; } } // FALLTHRU DON'T REORDER case COMMENT_END_DASH: commentenddashloop: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; break commentenddashloop; // continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS * (-) character and the input character to the * comment token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // FALLTHRU DON'T REORDER case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(2); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ adjustDoubleHyphenAndAppendToLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } // XXX reorder point case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ appendLongStrBuf(c); state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(1); /* * Switch to the data state. */ state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendLongStrBuf(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } // XXX reorder point case MARKUP_DECLARATION_OCTYPE: markupdeclarationdoctypeloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // OCTYPE.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; break markupdeclarationdoctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE: doctypeloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the before DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; break doctypeloop; // continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; break doctypeloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_NAME: beforedoctypenameloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ /* * Set the token's name name to the current * input character. */ clearStrBufAndAppendCurrentC(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; break beforedoctypenameloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_NAME: doctypenameloop: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE * Switch to the after DOCTYPE name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; break doctypenameloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_NAME: afterdoctypenameloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; break afterdoctypenameloop; // continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_UBLIC: doctypeublicloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < 5) { // UBLIC.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { bogusDoctype(); // forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; break doctypeublicloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: beforedoctypepublicidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE public identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; break beforedoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: doctypepublicidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; break doctypepublicidentifierdoublequotedloop; // continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: afterdoctypepublicidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; break afterdoctypepublicidentifierloop; // continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: doctypesystemidentifierdoublequotedloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // FALLTHRU DON'T REORDER case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: afterdoctypesystemidentifierloop: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the after DOCTYPE system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ bogusDoctypeWithoutQuirks(); state = Tokenizer.BOGUS_DOCTYPE; break afterdoctypesystemidentifierloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BOGUS_DOCTYPE: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } // XXX reorder point case DOCTYPE_YSTEM: doctypeystemloop: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before * DOCTYPE system identifier state. */ if (index < 5) { // YSTEM.length char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { bogusDoctype(); state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; break doctypeystemloop; // continue stateloop; } } // FALLTHRU DON'T REORDER case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: beforedoctypesystemidentifierloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay * in the before DOCTYPE system identifier * state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty string * (not missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not * missing), */ clearLongStrBufForNextState(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; break beforedoctypesystemidentifierloop; // continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: bogusDoctype(); /* * Set the DOCTYPE token's force-quirks flag to * on. */ // done by bogusDoctype(); /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } // FALLTHRU DON'T REORDER case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } // XXX reorder point case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } // XXX reorder point case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < 6) { // CDATA_LSQB.length if (c == Tokenizer.CDATA_LSQB[index]) { appendLongStrBuf(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_SECTION; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_SECTION: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_SECTION; reconsume = true; continue stateloop; } // XXX reorder point case ATTRIBUTE_VALUE_SINGLE_QUOTED: attributevaluesinglequotedloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character * reference in attribute value state, with the + * additional allowed character being U+0027 * APOSTROPHE ('). */ detachLongStrBuf(); clearStrBufAndAppendCurrentC(c); additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; break attributevaluesinglequotedloop; // continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } // FALLTHRU DON'T REORDER case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the * character reference fails. */ /* * This section defines how to consume a character * reference. This definition is used when parsing character * references in text and in attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references * table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { // if (strBufOffset != -1) { // ch = buf[strBufOffset + strBufMark]; // } else { ch = strBuf[strBufMark]; // } } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references * table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if (strBufOffset != -1) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(buf[strBufOffset + i]); } } else { tokenHandler.characters(buf, strBufOffset + strBufMark, strBufLen - strBufMark); } } else { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } // XXX reorder point case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; if ((returnState & (~1)) == 0) { cstart = pos + 1; } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; // XXX reorder point case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } // XXX reorder point case PLAINTEXT: plaintextloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBufForNextState(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: escapeexclamationhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapeexclamationhyphenloop; // continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: escapehyphenhyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; break escapehyphenhyphenloop; // continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokenizer (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020 * SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS * (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.nameAsArray.length) { char e = contentModelElement.nameAsArray[index]; char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { // [NOCPP[ if (html4) { if (ElementName.IFRAME != contentModelElement) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { // ]NOCPP] warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement.name + "\u201D contained the string \u201C</\u201D, but this did not close the element."); // [NOCPP[ } // ]NOCPP] } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C FORM FEED (FF) U+0020 * SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = returnState; continue stateloop; } } } // XXX reorder point case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBufAndAppendForceWrite((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; /* * set its tag name to the input character, */ clearStrBufAndAppendCurrentC(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBufAndAppendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (reconsume) { reconsume = false; } else { c = read(); } switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. * Otherwise: treat it as per the "anything * else" entry below. */ flushChars(); clearStrBufAndAppendCurrentC(c); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } } } flushChars(); if (prev == '\r' && pos != end) { pos--; col--; } // Save locals stateSave = state; returnStateSave = returnState; }
diff --git a/src/main/java/com/axiomalaska/sos/example/CnfaicObservationRetriever.java b/src/main/java/com/axiomalaska/sos/example/CnfaicObservationRetriever.java index 08383d3..1f10abf 100644 --- a/src/main/java/com/axiomalaska/sos/example/CnfaicObservationRetriever.java +++ b/src/main/java/com/axiomalaska/sos/example/CnfaicObservationRetriever.java @@ -1,165 +1,166 @@ package com.axiomalaska.sos.example; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.axiomalaska.phenomena.Phenomena; import com.axiomalaska.phenomena.Phenomenon; import com.axiomalaska.sos.ObservationRetriever; import com.axiomalaska.sos.data.ObservationCollection; import com.axiomalaska.sos.data.SosSensor; import com.axiomalaska.sos.data.SosStation; import com.axiomalaska.sos.tools.HttpSender; public class CnfaicObservationRetriever implements ObservationRetriever { // ------------------------------------------------------------------------- // Private Data // ------------------------------------------------------------------------- private final static int DATE_INDEX = 2; private final static int AIR_TEMPERATURE_INDEX = 3; private final static int RELATIVE_HUMIDITY_INDEX = 4; private final static int WIND_SPEED_INDEX = 5; private final static int WIND_DIRECTION_INDEX = 6; private final static int WIND_GUST_INDEX = 7; private HttpSender httpSender = new HttpSender(); private SimpleDateFormat parseDate = new SimpleDateFormat("yyyy-MM-dd HH"); // ------------------------------------------------------------------------- // Public ObservationRetriever // ------------------------------------------------------------------------- @Override public ObservationCollection getObservationCollection(SosStation station, SosSensor sensor, Phenomenon phenomenon, Calendar startDate) { String hoursText = calculatedDifferenceFromNow(startDate); try { String rawObservationData = httpSender.sendGetMessage( "http://www.cnfaic.org/library/grabbers/nws_feed.php?hours=" + hoursText); Phenomenon airTemperaturePhenomenon = Phenomena.instance().AIR_TEMPERATURE; Phenomenon relativeHumidityPhenomenon = Phenomena.instance().RELATIVE_HUMIDITY; Phenomenon windSpeedPhenomenon = Phenomena.instance().WIND_SPEED; Phenomenon windfromDirectionPhenomenon = Phenomena.instance().WIND_FROM_DIRECTION; Phenomenon windSpeedofGustPhenomenon = Phenomena.instance().WIND_SPEED_OF_GUST; + String foreignId = station.getId().replace("cnfaic:", ""); Pattern observationParser = - Pattern.compile(station.getId() + + Pattern.compile(foreignId + ",((\\d{4}-\\d{2}-\\d{2} \\d{2}):\\d{2}:\\d{2},(\\d+.\\d+),(\\d+),(\\d+),(\\d+),(\\d+))"); Matcher matcher = observationParser.matcher(rawObservationData); List<Calendar> dateValues = new ArrayList<Calendar>(); List<Double> dataValues = new ArrayList<Double>(); while(matcher.find()){ String rawDate = matcher.group(DATE_INDEX); Calendar date = createDate(rawDate); if (date.after(startDate)) { dateValues.add(date); if (phenomenon.getId().equals( airTemperaturePhenomenon.getId())) { String airTemperatureRaw = matcher .group(AIR_TEMPERATURE_INDEX); double airTemperature = Double .parseDouble(airTemperatureRaw); dataValues.add(airTemperature); } else if (phenomenon.getId().equals( relativeHumidityPhenomenon.getId())) { String relativeHumidityRaw = matcher .group(RELATIVE_HUMIDITY_INDEX); double relativeHumidity = Double .parseDouble(relativeHumidityRaw); dataValues.add(relativeHumidity); } else if (phenomenon.getId().equals( windSpeedPhenomenon.getId())) { String windSpeedRaw = matcher.group(WIND_SPEED_INDEX); double windSpeed = Double.parseDouble(windSpeedRaw); dataValues.add(windSpeed); } else if (phenomenon.getId().equals( windfromDirectionPhenomenon.getId())) { String windDirectionRaw = matcher .group(WIND_DIRECTION_INDEX); double windDirection = Double .parseDouble(windDirectionRaw); dataValues.add(windDirection); } else if (phenomenon.getId().equals( windSpeedofGustPhenomenon.getId())) { String windGustRaw = matcher.group(WIND_GUST_INDEX); double windGust = Double.parseDouble(windGustRaw); dataValues.add(windGust); } } } ObservationCollection observationCollection = new ObservationCollection(); observationCollection.setObservationDates(dateValues); observationCollection.setObservationValues(dataValues); observationCollection.setSensor(sensor); observationCollection.setStation(station); observationCollection.setPhenomenon(phenomenon); return observationCollection; } catch (Exception e) { System.out.println(e.getMessage()); return null; } } // ------------------------------------------------------------------------- // Private Members // ------------------------------------------------------------------------- @SuppressWarnings("deprecation") private Calendar createDate(String rawDate) throws ParseException { Date date = parseDate.parse(rawDate); Calendar calendar = Calendar.getInstance(TimeZone .getTimeZone("US/Alaska")); calendar.set(Calendar.YEAR, date.getYear() + 1900); calendar.set(Calendar.MONTH, date.getMonth()); calendar.set(Calendar.DAY_OF_MONTH, date.getDate()); calendar.set(Calendar.HOUR_OF_DAY, date.getHours()); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); // The time is not able to be changed from the // setTimezone if this is not set. Java Error calendar.getTime(); return calendar; } private String calculatedDifferenceFromNow(Calendar calendar) { Calendar copyCalendar = (Calendar) calendar.clone(); copyCalendar.setTimeZone(TimeZone.getTimeZone("US/Alaska")); Calendar now = Calendar.getInstance(TimeZone.getTimeZone("US/Alaska")); long diff = now.getTime().getTime() - calendar.getTime().getTime(); int hourDiff = Math.round(diff / (1000 * 60 * 60)); if(hourDiff > 720){ return "720"; } else{ return hourDiff + ""; } } }
false
true
public ObservationCollection getObservationCollection(SosStation station, SosSensor sensor, Phenomenon phenomenon, Calendar startDate) { String hoursText = calculatedDifferenceFromNow(startDate); try { String rawObservationData = httpSender.sendGetMessage( "http://www.cnfaic.org/library/grabbers/nws_feed.php?hours=" + hoursText); Phenomenon airTemperaturePhenomenon = Phenomena.instance().AIR_TEMPERATURE; Phenomenon relativeHumidityPhenomenon = Phenomena.instance().RELATIVE_HUMIDITY; Phenomenon windSpeedPhenomenon = Phenomena.instance().WIND_SPEED; Phenomenon windfromDirectionPhenomenon = Phenomena.instance().WIND_FROM_DIRECTION; Phenomenon windSpeedofGustPhenomenon = Phenomena.instance().WIND_SPEED_OF_GUST; Pattern observationParser = Pattern.compile(station.getId() + ",((\\d{4}-\\d{2}-\\d{2} \\d{2}):\\d{2}:\\d{2},(\\d+.\\d+),(\\d+),(\\d+),(\\d+),(\\d+))"); Matcher matcher = observationParser.matcher(rawObservationData); List<Calendar> dateValues = new ArrayList<Calendar>(); List<Double> dataValues = new ArrayList<Double>(); while(matcher.find()){ String rawDate = matcher.group(DATE_INDEX); Calendar date = createDate(rawDate); if (date.after(startDate)) { dateValues.add(date); if (phenomenon.getId().equals( airTemperaturePhenomenon.getId())) { String airTemperatureRaw = matcher .group(AIR_TEMPERATURE_INDEX); double airTemperature = Double .parseDouble(airTemperatureRaw); dataValues.add(airTemperature); } else if (phenomenon.getId().equals( relativeHumidityPhenomenon.getId())) { String relativeHumidityRaw = matcher .group(RELATIVE_HUMIDITY_INDEX); double relativeHumidity = Double .parseDouble(relativeHumidityRaw); dataValues.add(relativeHumidity); } else if (phenomenon.getId().equals( windSpeedPhenomenon.getId())) { String windSpeedRaw = matcher.group(WIND_SPEED_INDEX); double windSpeed = Double.parseDouble(windSpeedRaw); dataValues.add(windSpeed); } else if (phenomenon.getId().equals( windfromDirectionPhenomenon.getId())) { String windDirectionRaw = matcher .group(WIND_DIRECTION_INDEX); double windDirection = Double .parseDouble(windDirectionRaw); dataValues.add(windDirection); } else if (phenomenon.getId().equals( windSpeedofGustPhenomenon.getId())) { String windGustRaw = matcher.group(WIND_GUST_INDEX); double windGust = Double.parseDouble(windGustRaw); dataValues.add(windGust); } } } ObservationCollection observationCollection = new ObservationCollection(); observationCollection.setObservationDates(dateValues); observationCollection.setObservationValues(dataValues); observationCollection.setSensor(sensor); observationCollection.setStation(station); observationCollection.setPhenomenon(phenomenon); return observationCollection; } catch (Exception e) { System.out.println(e.getMessage()); return null; } }
public ObservationCollection getObservationCollection(SosStation station, SosSensor sensor, Phenomenon phenomenon, Calendar startDate) { String hoursText = calculatedDifferenceFromNow(startDate); try { String rawObservationData = httpSender.sendGetMessage( "http://www.cnfaic.org/library/grabbers/nws_feed.php?hours=" + hoursText); Phenomenon airTemperaturePhenomenon = Phenomena.instance().AIR_TEMPERATURE; Phenomenon relativeHumidityPhenomenon = Phenomena.instance().RELATIVE_HUMIDITY; Phenomenon windSpeedPhenomenon = Phenomena.instance().WIND_SPEED; Phenomenon windfromDirectionPhenomenon = Phenomena.instance().WIND_FROM_DIRECTION; Phenomenon windSpeedofGustPhenomenon = Phenomena.instance().WIND_SPEED_OF_GUST; String foreignId = station.getId().replace("cnfaic:", ""); Pattern observationParser = Pattern.compile(foreignId + ",((\\d{4}-\\d{2}-\\d{2} \\d{2}):\\d{2}:\\d{2},(\\d+.\\d+),(\\d+),(\\d+),(\\d+),(\\d+))"); Matcher matcher = observationParser.matcher(rawObservationData); List<Calendar> dateValues = new ArrayList<Calendar>(); List<Double> dataValues = new ArrayList<Double>(); while(matcher.find()){ String rawDate = matcher.group(DATE_INDEX); Calendar date = createDate(rawDate); if (date.after(startDate)) { dateValues.add(date); if (phenomenon.getId().equals( airTemperaturePhenomenon.getId())) { String airTemperatureRaw = matcher .group(AIR_TEMPERATURE_INDEX); double airTemperature = Double .parseDouble(airTemperatureRaw); dataValues.add(airTemperature); } else if (phenomenon.getId().equals( relativeHumidityPhenomenon.getId())) { String relativeHumidityRaw = matcher .group(RELATIVE_HUMIDITY_INDEX); double relativeHumidity = Double .parseDouble(relativeHumidityRaw); dataValues.add(relativeHumidity); } else if (phenomenon.getId().equals( windSpeedPhenomenon.getId())) { String windSpeedRaw = matcher.group(WIND_SPEED_INDEX); double windSpeed = Double.parseDouble(windSpeedRaw); dataValues.add(windSpeed); } else if (phenomenon.getId().equals( windfromDirectionPhenomenon.getId())) { String windDirectionRaw = matcher .group(WIND_DIRECTION_INDEX); double windDirection = Double .parseDouble(windDirectionRaw); dataValues.add(windDirection); } else if (phenomenon.getId().equals( windSpeedofGustPhenomenon.getId())) { String windGustRaw = matcher.group(WIND_GUST_INDEX); double windGust = Double.parseDouble(windGustRaw); dataValues.add(windGust); } } } ObservationCollection observationCollection = new ObservationCollection(); observationCollection.setObservationDates(dateValues); observationCollection.setObservationValues(dataValues); observationCollection.setSensor(sensor); observationCollection.setStation(station); observationCollection.setPhenomenon(phenomenon); return observationCollection; } catch (Exception e) { System.out.println(e.getMessage()); return null; } }
diff --git a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java index 93a275d2..b958dc29 100644 --- a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java +++ b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java @@ -1,4487 +1,4487 @@ package gov.nih.nci.evs.browser.utils; import java.io.*; import java.util.*; import java.sql.*; import org.apache.commons.lang.*; import org.apache.log4j.*; import org.LexGrid.LexBIG.DataModel.Collections.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.Exceptions.*; import org.LexGrid.LexBIG.LexBIGService.*; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.*; import org.LexGrid.LexBIG.Utility.*; import org.LexGrid.concepts.*; import org.LexGrid.LexBIG.DataModel.InterfaceElements.*; import org.LexGrid.LexBIG.Utility.Iterators.*; import org.LexGrid.codingSchemes.*; import org.LexGrid.commonTypes.*; import org.LexGrid.relations.*; import org.LexGrid.naming.*; import org.LexGrid.LexBIG.DataModel.Core.types.*; import org.LexGrid.LexBIG.Extensions.Generic.*; import gov.nih.nci.evs.browser.properties.*; import gov.nih.nci.evs.browser.utils.test.*; import org.LexGrid.lexevs.metabrowser.*; import org.LexGrid.lexevs.metabrowser.MetaBrowserService.*; import org.LexGrid.lexevs.metabrowser.model.*; import org.LexGrid.concepts.Entity; import gov.nih.nci.evs.browser.common.*; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history Initial implementation [email protected] * */ public class DataUtils { private static Logger _logger = Logger.getLogger(DataUtils.class); private static Vector<String> _sourceListData = null; private LocalNameList _noopList = Constructors.createLocalNameList("_noop_"); private static SortOptionList _sortByCode = Constructors.createSortOptionList(new String[] { "code" }); private Connection _con; private Statement _stmt; private ResultSet _rs; private List _supportedStandardReportList = new ArrayList(); private static List _standardReportTemplateList = null; private static List _adminTaskList = null; private static List _userTaskList = null; private static List _propertyTypeList = null; private static List _ontologies = null; private static org.LexGrid.LexBIG.LexBIGService.LexBIGService _lbSvc = null; public org.LexGrid.LexBIG.Utility.ConvenienceMethods _lbConvMethods = null; public CodingSchemeRenderingList _csrl = null; private Vector _supportedCodingSchemes = null; private static HashMap _codingSchemeMap = null; private Vector _codingSchemes = null; private static HashMap _csnv2codingSchemeNameMap = null; private static HashMap _csnv2VersionMap = null; private static List _directionList = null; private static String[] ASSOCIATION_NAMES = null; public final static String INCOMPLETE = "INCOMPLETE"; // ================================================================================== // For customized query use private static String SOURCE_OF = "outbound associations"; private static String TARGET_OF = "inbound associations"; public static final int ALL = 0; public static final int PREFERRED_ONLY = 1; public static final int NON_PREFERRED_ONLY = 2; private static final int RESOLVE_SOURCE = 1; private static final int RESOLVE_TARGET = -1; private static final int RESTRICT_SOURCE = -1; private static final int RESTRICT_TARGET = 1; public static final int SEARCH_NAME_CODE = 1; public static final int SEARCH_DEFINITION = 2; public static final int SEARCH_PROPERTY_VALUE = 3; public static final int SEARCH_ROLE_VALUE = 6; public static final int SEARCH_ASSOCIATION_VALUE = 7; private static final List<String> STOP_WORDS = Arrays.asList(new String[] { "a", "an", "and", "by", "for", "of", "on", "in", "nos", "the", "to", "with" }); public static String TYPE_ROLE = "type_role"; public static String TYPE_ASSOCIATION = "type_association"; public static String TYPE_SUPERCONCEPT = "type_superconcept"; public static String TYPE_SUBCONCEPT = "type_subconcept"; public static String TYPE_SIBLINGCONCEPT = "type_siblingconcept"; public static String TYPE_BROADERCONCEPT = "type_broaderconcept"; public static String TYPE_NARROWERCONCEPT = "type_narrowerconcept"; public String _ncicbContactURL = null; public String _terminologySubsetDownloadURL = null; public String _ncimBuildInfo = null; public String _ncimAppVersion = null; public String _ncitAnthillBuildTagBuilt = null; public String _evsServiceURL = null; public String _ncitURL = null; private static String[] _hierAssocToParentNodes = new String[] { "PAR", "isa", "branch_of", "part_of", "tributary_of" }; private static String[] _hierAssocToChildNodes = new String[] { "CHD", "inverse_isa" }; private static String[] _assocToSiblingNodes = new String[] { "SIB" }; private static String[] _assocToBTNodes = new String[] { "RB" }; private static String[] _assocToNTNodes = new String[] { "RN" }; private static String[] _relationshipCategories = new String[] { "Parent", "Child", "Broader", "Narrower", "Sibling", "Other" }; private static String SOURCE = "source"; private static String[] META_ASSOCIATIONS = new String[] { "AQ", "CHD", "RB", "RO", "RQ", "SIB", "SY" }; public static HashMap _formalName2MetadataHashMap = null; public DataUtils() { // Do nothing _formalName2MetadataHashMap = null; } public static void setFormalName2MetadataHashMap(HashMap hmap) { _formalName2MetadataHashMap = hmap; } public static HashMap getFormalName2MetadataHashMap() { if (_formalName2MetadataHashMap != null) return _formalName2MetadataHashMap; MetadataUtils.initialize(); return _formalName2MetadataHashMap; } /* * public static HashMap getFormalName2MetadataHashMap() { if * (formalName2MetadataHashMap != null) return formalName2MetadataHashMap; * * try { formalName2MetadataHashMap = new HashMap(); LexBIGService lbSvc = * RemoteServerUtil.createLexBIGService(true); if (lbSvc == null) { * _logger.warn * ("WARNING: Unable to connect to instantiate LexBIGService ???"); } * CodingSchemeRenderingList csrl = null; try { csrl = * lbSvc.getSupportedCodingSchemes(); } catch (LBInvocationException ex) { * ex.printStackTrace(); * _logger.error("lbSvc.getSupportedCodingSchemes() FAILED..." + * ex.getCause() ); return null; } * * CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int * i=0; i<csrs.length; i++) { int j = i+1; CodingSchemeRendering csr = * csrs[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); String * formalname = css.getFormalName(); _logger.debug("(" + j + "): " + * formalname); * * Boolean isActive = null; if (csr == null) { * _logger.debug("\tcsr == null???"); } else if (csr.getRenderingDetail() == * null) { _logger.debug("\tcsr.getRenderingDetail() == null"); } else if * (csr.getRenderingDetail().getVersionStatus() == null) { * _logger.debug("\tcsr.getRenderingDetail().getVersionStatus() == null"); } * else { isActive = * csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus * .ACTIVE); } * * String representsVersion = css.getRepresentsVersion(); boolean * includeInactive = false; if ((includeInactive && isActive == null) || * (isActive != null && isActive.equals(Boolean.TRUE)) || (includeInactive * && (isActive != null && isActive.equals(Boolean.FALSE)))) { * CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); * vt.setVersion(representsVersion); try { CodingScheme cs = * lbSvc.resolveCodingScheme(formalname, vt); * * if (cs != null) { NameAndValue[] nvList = * MetadataUtils.getMetadataProperties(cs); if (nvList != null) { Vector * metadataProperties = new Vector(); for (int k=0; k<nvList.length; k++) { * NameAndValue nv = (NameAndValue) nvList[k]; * metadataProperties.add(nv.getName() + "|" + nv.getContent()); } * formalName2MetadataHashMap.put(formalname, metadataProperties); } } } * catch (Exception ex) { * _logger.warn("\tWARNING: Unable to resolve coding scheme " + formalname + * " possibly due to missing security token."); * _logger.warn("\t\tAccess to " + formalname + " denied."); } } else { * _logger.warn("\tWARNING: setCodingSchemeMap discards " + formalname); * _logger.warn("\t\trepresentsVersion " + representsVersion); } } } catch * (Exception e) { e.printStackTrace(); } * * return formalName2MetadataHashMap; } */ public static String[] getAllAssociationNames() { if (ASSOCIATION_NAMES != null) return null; Vector<String> v = getSupportedAssociationNames(Constants.CODING_SCHEME_NAME, null); ASSOCIATION_NAMES = new String[v.size()]; for (int i = 0; i < v.size(); i++) { String s = (String) v.elementAt(i); ASSOCIATION_NAMES[i] = s; } return ASSOCIATION_NAMES; } public static Vector<String> getSupportedAssociationNames( String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) { _logger.warn("scheme is NULL"); return null; } Vector<String> v = new Vector<String>(); SupportedAssociation[] assos = scheme.getMappings().getSupportedAssociation(); for (int i = 0; i < assos.length; i++) { SupportedAssociation sa = (SupportedAssociation) assos[i]; v.add(sa.getLocalId()); } return v; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector<String> getPropertyNameListData( String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyNameListData = new Vector<String>(); SupportedProperty[] properties = scheme.getMappings().getSupportedProperty(); for (int i = 0; i < properties.length; i++) { SupportedProperty property = properties[i]; propertyNameListData.add(property.getLocalId()); } return propertyNameListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String getCodingSchemeName(String key) { return (String) _csnv2codingSchemeNameMap.get(key); } public static String getCodingSchemeVersion(String key) { return (String) _csnv2VersionMap.get(key); } public static Vector<String> getRepresentationalFormListData(String key) { String codingSchemeName = (String) _csnv2codingSchemeNameMap.get(key); if (codingSchemeName == null) return null; String version = (String) _csnv2VersionMap.get(key); if (version == null) return null; return getRepresentationalFormListData(codingSchemeName, version); } public static Vector<String> getRepresentationalFormListData( String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyNameListData = new Vector<String>(); SupportedRepresentationalForm[] forms = scheme.getMappings().getSupportedRepresentationalForm(); if (forms != null) { for (int i = 0; i < forms.length; i++) { SupportedRepresentationalForm form = forms[i]; propertyNameListData.add(form.getLocalId()); } } return propertyNameListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector<String> getPropertyQualifierListData(String key) { String codingSchemeName = (String) _csnv2codingSchemeNameMap.get(key); if (codingSchemeName == null) return null; String version = (String) _csnv2VersionMap.get(key); if (version == null) return null; return getPropertyQualifierListData(codingSchemeName, version); } public static Vector<String> getPropertyQualifierListData( String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyQualifierListData = new Vector<String>(); SupportedPropertyQualifier[] qualifiers = scheme.getMappings().getSupportedPropertyQualifier(); for (int i = 0; i < qualifiers.length; i++) { SupportedPropertyQualifier qualifier = qualifiers[i]; propertyQualifierListData.add(qualifier.getLocalId()); } return propertyQualifierListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector<String> getSourceListData(String codingSchemeName, String version) { if (_sourceListData != null) return _sourceListData; CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); if (lbSvc == null) return null; scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; _sourceListData = new Vector<String>(); if (scheme.getMappings() == null) return null; _sourceListData.add("ALL"); // Insert your code here SupportedSource[] sources = scheme.getMappings().getSupportedSource(); if (sources == null) return null; for (int i = 0; i < sources.length; i++) { SupportedSource source = sources[i]; _sourceListData.add(source.getLocalId()); } return _sourceListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String int2String(Integer int_obj) { if (int_obj == null) { return null; } String retstr = Integer.toString(int_obj); return retstr; } public static Entity getConceptByCode(String codingSchemeName, String vers, String ltag, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList(new String[] { code }, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); cns = cns.restrictToCodes(crefs); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { _logger.debug("Concept not found."); return null; } int count = matches.getResolvedConceptReferenceCount(); // Analyze the result ... if (count == 0) return null; if (count > 0) { try { ResolvedConceptReference ref = (ResolvedConceptReference) matches .enumerateResolvedConceptReference() .nextElement(); Entity entry = ref.getReferencedEntry(); return entry; } catch (Exception ex1) { _logger.error("Exception entry == null"); return null; } } } catch (Exception e1) { e1.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } public static CodedNodeSet restrictToSource(CodedNodeSet cns, String source) { if (cns == null) return cns; if (source == null || source.compareTo("*") == 0 || source.compareTo("") == 0 || source.compareTo("ALL") == 0) return cns; LocalNameList contextList = null; LocalNameList sourceLnL = null; NameAndValueList qualifierList = null; Vector<String> w2 = new Vector<String>(); w2.add(source); sourceLnL = vector2LocalNameList(w2); LocalNameList propertyLnL = null; CodedNodeSet.PropertyType[] types = new PropertyType[] { PropertyType.PRESENTATION }; try { cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList); } catch (Exception ex) { _logger.error("restrictToSource throws exceptions."); return null; } return cns; } public static Entity getConceptByCode(String codingSchemeName, String vers, String ltag, String code, String source) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList(new String[] { code }, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); } catch (Exception e1) { // e1.printStackTrace(); } cns = cns.restrictToCodes(crefs); cns = restrictToSource(cns, source); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { _logger.warn("Concept not found."); return null; } // Analyze the result ... if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches .enumerateResolvedConceptReference().nextElement(); Entity entry = ref.getReferencedEntry(); return entry; } } catch (Exception e) { // e.printStackTrace(); return null; } return null; } public static NameAndValueList createNameAndValueList(String[] names, String[] values) { NameAndValueList nvList = new NameAndValueList(); for (int i = 0; i < names.length; i++) { NameAndValue nv = new NameAndValue(); nv.setName(names[i]); if (values != null) { nv.setContent(values[i]); } nvList.addNameAndValue(nv); } return nvList; } public ResolvedConceptReferenceList getNext( ResolvedConceptReferencesIterator iterator) { return iterator.getNext(); } public Vector getParentCodes(String scheme, String version, String code) { Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0) { return null; } String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); // KLO, 01/23/2009 // Vector<Concept> superconcept_vec = util.getAssociationSources(scheme, // version, code, hierarchicalAssoName); Vector superconcept_vec = getAssociationSourceCodes(scheme, version, code, hierarchicalAssoName); if (superconcept_vec == null) return null; // SortUtils.quickSort(superconcept_vec, SortUtils.SORT_BY_CODE); return superconcept_vec; } public Vector getAssociationSourceCodes(String scheme, String version, String code, String assocName) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList(new String[] { assocName }, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = NCImBrowserProperties._maxToReturn; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), false, true, 1, 1, new LocalNameList(), null, null, maxToReturn); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<? extends ResolvedConceptReference> refEnum = matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); Association[] associations = targetof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; // KLO assoc = processForAnonomousNodes(assoc); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; v.add(ac.getReferencedEntry().getEntityCode()); } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; } public static ConceptReferenceList createConceptReferenceList( String[] codes, String codingSchemeName) { if (codes == null) { return null; } ConceptReferenceList list = new ConceptReferenceList(); for (int i = 0; i < codes.length; i++) { ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(codingSchemeName); cr.setConceptCode(codes[i]); list.addConceptReference(cr); } return list; } public Vector getSubconceptCodes(String scheme, String version, String code) { // throws // LBException{ Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm .createCodeNodeSet(new String[] { code }, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0).getEntityDescription() .getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = null; associations = null; try { associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null); } catch (Exception e) { _logger .error("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext "); return v; } for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { // ex.printStackTrace(); } return v; } public Vector getSuperconceptCodes(String scheme, String version, String code) { // throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm .createCodeNodeSet(new String[] { code }, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0).getEntityDescription() .getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { _logger .debug("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; String version = null; int knt = 0; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { version = css.getRepresentsVersion(); knt++; if (ltag == null) return version; RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); // KLO, 102409 if (tags == null) return version; if (tags != null && tags.length > 0) { for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return version; } } } } } } catch (Exception e) { // e.printStackTrace(); } if (ltag != null && ltag.compareToIgnoreCase("PRODUCTION") == 0 & knt == 1) { _logger.debug("\tUse " + version + " as default."); return version; } return null; } public static Vector<String> getVersionListData(String codingSchemeName) { Vector<String> v = new Vector(); try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if (csrl == null) _logger.warn("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i = 0; i < csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals( CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); if (formalname.compareTo(codingSchemeName) == 0) { String representsVersion = css.getRepresentsVersion(); v.add(representsVersion); } } } } catch (Exception ex) { } return v; } public static String getFileName(String pathname) { File file = new File(pathname); String filename = file.getName(); return filename; } protected static Association processForAnonomousNodes(Association assoc) { // clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for (int i = 0; i < assoc.getAssociatedConcepts() .getAssociatedConceptCount(); i++) { // Conditionals to deal with anonymous nodes and UMLS top nodes // "V-X" // The first three allow UMLS traversal to top node. // The last two are specific to owl anonymous nodes which can act // like false // top nodes. if (assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@@")) { // do nothing } else { temp.getAssociatedConcepts().addAssociatedConcept( assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } public static LocalNameList vector2LocalNameList(Vector<String> v) { if (v == null) return null; LocalNameList list = new LocalNameList(); for (int i = 0; i < v.size(); i++) { String vEntry = (String) v.elementAt(i); list.addEntry(vEntry); } return list; } protected static NameAndValueList createNameAndValueList(Vector names, Vector values) { if (names == null) return null; NameAndValueList nvList = new NameAndValueList(); for (int i = 0; i < names.size(); i++) { String name = (String) names.elementAt(i); String value = (String) values.elementAt(i); NameAndValue nv = new NameAndValue(); nv.setName(name); if (value != null) { nv.setContent(value); } nvList.addNameAndValue(nv); } return nvList; } protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { ex.printStackTrace(); } return cs; } public static Vector<SupportedProperty> getSupportedProperties( CodingScheme cs) { if (cs == null) return null; Vector<SupportedProperty> v = new Vector<SupportedProperty>(); SupportedProperty[] properties = cs.getMappings().getSupportedProperty(); for (int i = 0; i < properties.length; i++) { SupportedProperty sp = (SupportedProperty) properties[i]; v.add(sp); } return v; } public static Vector<String> getSupportedPropertyNames(CodingScheme cs) { Vector w = getSupportedProperties(cs); if (w == null) return null; Vector<String> v = new Vector<String>(); for (int i = 0; i < w.size(); i++) { SupportedProperty sp = (SupportedProperty) w.elementAt(i); v.add(sp.getLocalId()); } return v; } public static Vector<String> getSupportedPropertyNames(String codingScheme, String version) { CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { CodingScheme cs = getCodingScheme(codingScheme, versionOrTag); return getSupportedPropertyNames(cs); } catch (Exception ex) { } return null; } public static Vector getPropertyNamesByType(Entity concept, String property_type) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } if (properties == null || properties.length == 0) return v; HashSet hset = new HashSet(); for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; String nm = p.getPropertyName(); if (!hset.contains(nm)) { hset.add(nm); v.add(p.getPropertyName()); } } hset.clear(); return v; } public static Vector getPropertyValues(Entity concept, String property_type, String property_name) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } /* * else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0) { * properties = concept.getInstruction(); } */ else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } else { _logger .warn("WARNING: property_type not found -- " + property_type); } if (properties == null || properties.length == 0) return v; for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; if (property_name.compareTo(p.getPropertyName()) == 0) { String t = p.getValue().getContent(); Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; t = t + "|" + src.getContent(); } else { if (property_name.compareToIgnoreCase("definition") == 0) { _logger.warn("*** WARNING: " + property_name + " with no source data: " + p.getValue().getContent()); PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); // _logger.debug("\t*** qualifier_name: " + // qualifier_name); // _logger.debug("\t*** qualifier_value: " // + qualifier_value); if (qualifier_name.compareTo("source") == 0) { t = t + "|" + qualifier_value; // _logger.debug("*** SOURCE: " + // qualifier_value); break; } } } else { _logger .warn("*** SOURCE NOT FOUND IN qualifiers neither. "); } } } v.add(t); } } return v; } // ===================================================================================== public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); List list = new ArrayList(); try { CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); Relations[] relations = cs.getRelations(); for (int i = 0; i < relations.length; i++) { Relations relation = relations[i]; if (relation.getContainerName().compareToIgnoreCase("roles") == 0) { AssociationPredicate[] asso_array = relation.getAssociationPredicate(); for (int j = 0; j < asso_array.length; j++) { AssociationPredicate association = (AssociationPredicate) asso_array[j]; list.add(association.getAssociationName()); } } } } catch (Exception ex) { } return list; } public static void sortArray(ArrayList list) { String tmp; if (list.size() <= 1) return; for (int i = 0; i < list.size(); i++) { String s1 = (String) list.get(i); for (int j = i + 1; j < list.size(); j++) { String s2 = (String) list.get(j); if (s1.compareToIgnoreCase(s2) > 0) { tmp = s1; list.set(i, s2); list.set(j, tmp); } } } } public static void sortArray(String[] strArray) { String tmp; if (strArray.length <= 1) return; for (int i = 0; i < strArray.length; i++) { for (int j = i + 1; j < strArray.length; j++) { if (strArray[i].compareToIgnoreCase(strArray[j]) > 0) { tmp = strArray[i]; strArray[i] = strArray[j]; strArray[j] = tmp; } } } } public String[] getSortedKeys(HashMap map) { if (map == null) return null; Set keyset = map.keySet(); String[] names = new String[keyset.size()]; Iterator it = keyset.iterator(); int i = 0; while (it.hasNext()) { String s = (String) it.next(); names[i] = s; i++; } sortArray(names); return names; } public String getPreferredName(Entity c) { Presentation[] presentations = c.getPresentation(); for (int i = 0; i < presentations.length; i++) { Presentation p = presentations[i]; if (p.getPropertyName().compareTo("Preferred_Name") == 0) { return p.getValue().getContent(); } } return null; } public HashMap getRelationshipHashMap(String scheme, String version, String code) { return getRelationshipHashMap(scheme, version, code, null); } protected static String getDirectionalLabel( LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, boolean navigatedFwd) throws LBException { String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(assoc .getAssociationName(), scheme, csvt) : lbscm .getAssociationReverseName(assoc.getAssociationName(), scheme, csvt); if (StringUtils.isBlank(assocLabel)) assocLabel = (navigatedFwd ? "" : "[Inverse]") + assoc.getAssociationName(); return assocLabel; } public LexBIGServiceConvenienceMethods createLexBIGServiceConvenienceMethods( LexBIGService lbSvc) { LexBIGServiceConvenienceMethods lbscm = null; try { lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { ex.printStackTrace(); } return lbscm; } public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab) { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); // Perform the query ... ResolvedConceptReferenceList matches = null; List list = new ArrayList();// getSupportedRoleNames(lbSvc, scheme, // version); ArrayList roleList = new ArrayList(); ArrayList associationList = new ArrayList(); ArrayList superconceptList = new ArrayList(); ArrayList siblingList = new ArrayList(); ArrayList subconceptList = new ArrayList(); ArrayList btList = new ArrayList(); ArrayList ntList = new ArrayList(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); HashMap map = new HashMap(); try { // LexBIGServiceConvenienceMethods lbscm = // createLexBIGServiceConvenienceMethods(lbSvc); /* * LexBIGServiceConvenienceMethods lbscm = * (LexBIGServiceConvenienceMethods) lbSvc * .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); */ CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); if (sab != null) { cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); } int maxToReturn = NCImBrowserProperties._maxToReturn; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), true, false, 1, 1, _noopList, null, null, null, maxToReturn, false); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); Association[] associations = sourceof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = assoc.getAssociationName(); // String associationName = // lbscm.getAssociationNameFromAssociationCode(scheme, // csvt, assoc.getAssociationName()); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; EntityDescription ed = ac.getEntityDescription(); String name = "No Description"; if (ed != null) name = ed.getContent(); String pt = name; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { String s = associationName + "|" + pt + "|" + ac.getConceptCode(); if (!parent_asso_vec.contains(associationName) && !child_asso_vec .contains(associationName)) { if (sibling_asso_vec .contains(associationName)) { siblingList.add(s); } else if (bt_vec.contains(associationName)) { btList.add(s); } else if (nt_vec.contains(associationName)) { ntList.add(s); } else { associationList.add(s); } } } } } } } if (roleList.size() > 0) { SortUtils.quickSort(roleList); } if (associationList.size() > 0) { // KLO, 052909 associationList = removeRedundantRelationships(associationList, "RO"); SortUtils.quickSort(associationList); } if (siblingList.size() > 0) { SortUtils.quickSort(siblingList); } if (btList.size() > 0) { SortUtils.quickSort(btList); } if (ntList.size() > 0) { SortUtils.quickSort(ntList); } map.put(TYPE_ROLE, roleList); map.put(TYPE_ASSOCIATION, associationList); map.put(TYPE_SIBLINGCONCEPT, siblingList); map.put(TYPE_BROADERCONCEPT, btList); map.put(TYPE_NARROWERCONCEPT, ntList); Vector superconcept_vec = getSuperconcepts(scheme, version, code); for (int i = 0; i < superconcept_vec.size(); i++) { Entity c = (Entity) superconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); superconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(superconceptList); map.put(TYPE_SUPERCONCEPT, superconceptList); Vector subconcept_vec = getSubconcepts(scheme, version, code); for (int i = 0; i < subconcept_vec.size(); i++) { Entity c = (Entity) subconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); subconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(subconceptList); map.put(TYPE_SUBCONCEPT, subconceptList); } catch (Exception ex) { ex.printStackTrace(); } return map; } public Vector getSuperconcepts(String scheme, String version, String code) { return getAssociationSources(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public Vector getSubconcepts(String scheme, String version, String code) { return getAssociationTargets(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = false; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator( CodedNodeGraph cng, ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn) { CodedNodeSet cns = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator toNodeList "); cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); if (cns == null) { _logger.warn("cng.toNodeList returns null???"); return null; } SortOptionList sortCriteria = null; // Constructors.createSortOptionList(new String[]{"matchToQuery", // "code"}); LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; ResolvedConceptReferencesIterator iterator = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve "); iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes); System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve DONE "); } catch (Exception e) { e.printStackTrace(); } if (iterator == null) { _logger.warn("cns.resolve returns null???"); } return iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn) { return resolveIterator(iterator, maxToReturn, null); } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code) { Vector v = new Vector(); if (iterator == null) { _logger.debug("No match."); return v; } try { int iteration = 0; while (iterator.hasNext()) { iteration++; iterator = iterator.scroll(maxToReturn); ResolvedConceptReferenceList rcrl = iterator.getNext(); ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference(); for (int i = 0; i < rcra.length; i++) { ResolvedConceptReference rcr = rcra[i]; org.LexGrid.concepts.Entity ce = rcr.getReferencedEntry(); if (code == null) { v.add(ce); } else { if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } } } catch (Exception e) { e.printStackTrace(); } return v; } public static Vector<String> parseData(String line) { return parseData(line, "|"); } public static Vector<String> parseData(String line, String tab) { Vector data_vec = new Vector(); StringTokenizer st = new StringTokenizer(line, tab); while (st.hasMoreTokens()) { String value = st.nextToken(); if (value.compareTo("null") == 0) value = " "; data_vec.add(value); } return data_vec; } public static String getHyperlink(String url, String codingScheme, String code) { codingScheme = codingScheme.replace(" ", "%20"); String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code; return link; } public List getHierarchyRoots(String scheme, String version, String hierarchyID) throws LBException { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); return getHierarchyRoots(scheme, csvt, hierarchyID); } public List getHierarchyRoots(String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); List list = ResolvedConceptReferenceList2List(roots); SortUtils.quickSort(list); return list; } public List ResolvedConceptReferenceList2List( ResolvedConceptReferenceList rcrl) { ArrayList list = new ArrayList(); for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); list.add(rcr); } return list; } public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, sab); } public static Vector getSynonyms(String scheme, String version, String tag, String code) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept) { return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept, String sab) { if (concept == null) return null; Vector v = new Vector(); Presentation[] properties = concept.getPresentation(); int n = 0; for (int i = 0; i < properties.length; i++) { Presentation p = properties[i]; // name String term_name = p.getValue().getContent(); String term_type = "null"; String term_source = "null"; String term_source_code = "null"; // source-code PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source-code") == 0) { term_source_code = qualifier_value; break; } } } // term type term_type = p.getRepresentationalForm(); // source Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; term_source = src.getContent(); } String t = null; if (sab == null) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } else if (term_source != null && sab.compareTo(term_source) == 0) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } } SortUtils.quickSort(v); return v; } public String getNCICBContactURL() { if (_ncicbContactURL != null) { return _ncicbContactURL; } String default_url = "[email protected]"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncicbContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL); if (_ncicbContactURL == null) { _ncicbContactURL = default_url; } } catch (Exception ex) { } _logger.debug("getNCICBContactURL returns " + _ncicbContactURL); return _ncicbContactURL; } public String getTerminologySubsetDownloadURL() { NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _terminologySubsetDownloadURL = properties .getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } catch (Exception ex) { } return _terminologySubsetDownloadURL; } public String getNCIMBuildInfo() { if (_ncimBuildInfo != null) { return _ncimBuildInfo; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO); if (_ncimBuildInfo == null) { _ncimBuildInfo = default_info; } } catch (Exception ex) { } _logger.debug("getNCIMBuildInfo returns " + _ncimBuildInfo); return _ncimBuildInfo; } public String getApplicationVersion() { if (_ncimAppVersion != null) { return _ncimAppVersion; } String default_info = "1.0"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimAppVersion = properties.getProperty(NCImBrowserProperties.NCIM_APP_VERSION); if (_ncimAppVersion == null) { _ncimAppVersion = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncimAppVersion; } - public String getNCITAnthillBuildTagBuilt() { + public String getNCITAppBuildTag() { if (_ncitAnthillBuildTagBuilt != null) { return _ncitAnthillBuildTagBuilt; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitAnthillBuildTagBuilt = properties .getProperty(NCImBrowserProperties.APP_BUILD_TAG); if (_ncitAnthillBuildTagBuilt == null) { _ncitAnthillBuildTagBuilt = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncitAnthillBuildTagBuilt; } public String getEVSServiceURL() { if (_evsServiceURL != null) { return _evsServiceURL; } String default_info = "Local LexEVS"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _evsServiceURL = properties.getProperty(NCImBrowserProperties.EVS_SERVICE_URL); if (_evsServiceURL == null) { _evsServiceURL = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _evsServiceURL; } public String getNCItURL() { if (_ncitURL != null) { return _ncitURL; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitURL = properties.getProperty(NCImBrowserProperties.NCIT_URL); if (_ncitURL == null) { _ncitURL = default_info; } } catch (Exception ex) { } return _ncitURL; } public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) { Vector<String> v = new Vector<String>(); v.add("String"); v.add("Code"); v.add("CUI"); return v; } public static Vector getSources(String scheme, String version, String tag, String code) { Vector sources = getSynonyms(scheme, version, tag, code); // GLIOBLASTOMA MULTIFORME|DI|DXP|U000721 HashSet hset = new HashSet(); Vector source_vec = new Vector(); for (int i = 0; i < sources.size(); i++) { String s = (String) sources.elementAt(i); Vector ret_vec = DataUtils.parseData(s, "|"); String name = (String) ret_vec.elementAt(0); String type = (String) ret_vec.elementAt(1); String src = (String) ret_vec.elementAt(2); String srccode = (String) ret_vec.elementAt(3); if (!hset.contains(src)) { hset.add(src); source_vec.add(src); } } SortUtils.quickSort(source_vec); return source_vec; } public static boolean containSource(Vector sources, String source) { if (sources == null || sources.size() == 0) return false; String s = null; for (int i = 0; i < sources.size(); i++) { s = (String) sources.elementAt(i); if (s.compareTo(source) == 0) return true; } return false; } public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); // NameAndValueList nameAndValueList = // ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } SortUtils.quickSort(v); return v; } protected boolean isValidForSAB(AssociatedConcept ac, String sab) { for (NameAndValue qualifier : ac.getAssociationQualifiers() .getNameAndValue()) if (SOURCE.equalsIgnoreCase(qualifier.getContent()) && sab.equalsIgnoreCase(qualifier.getName())) return true; return false; } public Vector sortSynonyms(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String key = term_name + delim + term_source + delim + term_source_code + delim + term_type; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getAssociatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, false, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } hmap.put(associationName, v); } } } } } cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), Constructors.createNameAndValueList("source", source)); } else { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), null); } matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), false, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } if (associationName.compareTo("CHD") == 0) { associationName = "PAR"; } hmap.put(associationName, v); } } } } } } catch (Exception ex) { } return hmap; } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getRelatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { Debug.println("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches != null) { java.lang.Boolean incomplete = matches.getIncomplete(); // _logger.debug("(*) Number of matches: " + // matches.getResolvedConceptReferenceCount()); // _logger.debug("(*) Incomplete? " + incomplete); hmap.put(INCOMPLETE, incomplete.toString()); } if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; String directionalLabel = associationName; boolean navigatedFwd = true; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); } catch (Exception e) { Debug .println("(*) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) { String directionalLabel = associationName; boolean navigatedFwd = false; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); // Debug.println("(**) directionalLabel: associationName " // + associationName + // " directionalLabel: " + // directionalLabel); } catch (Exception e) { Debug .println("(**) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { // associationName = // qualifier_value; // // replace associationName // by Rela value asso_label = qualifier_value; break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } } } } } catch (Exception ex) { } return hmap; } private String findRepresentativeTerm(Entity c, String sab) { Vector synonyms = getSynonyms(c, sab); if (synonyms == null || synonyms.size() == 0) { // return null; // t = term_name + "|" + term_type + "|" + term_source + "|" + // term_source_code; return c.getEntityDescription().getContent() + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + Constants.EXTERNAL_TERM_SOURCE + "|" + Constants.EXTERNAL_TERM_SOURCE_CODE; } return NCImBrowserProperties.getHighestTermGroupRank(synonyms); } String getAssociationDirectionalName(LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String associationName, boolean navigatedFwd) { String assocLabel = null; try { assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(associationName, scheme, csvt) : lbscm.getAssociationReverseName( associationName, scheme, csvt); } catch (Exception ex) { } return assocLabel; } // Method for populating By Source tab relationships table public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay = 0; String action = "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; ms_all = System.currentTimeMillis(); while (it.hasNext()) { ms_categorization = System.currentTimeMillis(); String rel_rela = (String) it.next(); // _logger.debug("rel_rela: " + rel_rela); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; /* * if (parent_asso_vec.contains(rel)) category = "Child"; else * if (child_asso_vec.contains(rel)) category = "Parent"; else * if (bt_vec.contains(rel)) category = "Narrower"; else if * (nt_vec.contains(rel)) category = "Broader"; */ else if (sibling_asso_vec.contains(rel)) category = "Sibling"; ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization); Object obj = hmap.get(rel_rela); if (obj != null) { Vector v = (Vector) obj; // For each related concept: for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); Entity c = ac.getReferencedEntry(); if (!hset.contains(c.getEntityCode())) { hset.add(c.getEntityCode()); // Find the highest ranked atom data ms_find_highest_rank_atom = System.currentTimeMillis(); String t = findRepresentativeTerm(c, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); t = t + "|" + c.getEntityCode() + "|" + rela + "|" + category; // _logger.debug(t); w.add(t); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && category.compareTo("RO") != 0) { if (rel_hset.contains(c.getEntityCode())) { rel_hset.add(c.getEntityCode()); } } if (category.compareTo("Child") == 0 && category.compareTo("CHD") != 0) { if (hasSubtype_hset.contains(c.getEntityCode())) { hasSubtype_hset.add(c.getEntityCode()); } } } } } } } Vector u = new Vector(); // Remove redundant RO relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("RO") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } // Remove redundant CHD relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("CHD") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } ms_all_delay = System.currentTimeMillis() - ms_all; action = "categorizing relationships into six categories"; Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay); DBG.debugDetails(ms_categorization_delay, action, "getNeighborhoodSynonyms"); action = "finding highest ranked atoms"; Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay; action = "removing redundant RO relationships"; Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay); DBG.debugDetails(ms_remove_RO_delay, action, "getNeighborhoodSynonyms"); // Initial sort (refer to sortSynonymData method for sorting by a // specific column) long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); DBG.debugDetails("Max Return", NCImBrowserProperties._maxToReturn); return u; } public static String getRelationshipCode(String id) { if (id.compareTo("Parent") == 0) return "1"; else if (id.compareTo("Child") == 0) return "2"; else if (id.compareTo("Broader") == 0) return "3"; else if (id.compareTo("Narrower") == 0) return "4"; else if (id.compareTo("Sibling") == 0) return "5"; else return "6"; } public static boolean containsAllUpperCaseChars(String s) { for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch < 65 || ch > 90) return false; } return true; } public static Vector sortSynonymData(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String rel_type = (String) synonym_data.elementAt(6); String rel_type_str = getRelationshipCode(rel_type); String key = term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel") == 0) { String rel_key = rel; if (containsAllUpperCaseChars(rel)) rel_key = "|"; key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel_type_str; } if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } // KLO, 052909 private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) { ArrayList a = new ArrayList(); HashSet target_set = new HashSet(); for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { String associationTargetCode = w.elementAt(2); target_set.add(associationTargetCode); } } for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { a.add(s); } else { String associationTargetCode = w.elementAt(2); if (!target_set.contains(associationTargetCode)) { a.add(s); } } } return a; } public static Vector sortRelationshipData(Vector relationships, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < relationships.size(); n++) { String s = (String) relationships.elementAt(n); Vector ret_vec = DataUtils.parseData(s, "|"); String relationship_name = (String) ret_vec.elementAt(0); String target_concept_name = (String) ret_vec.elementAt(1); String target_concept_code = (String) ret_vec.elementAt(2); String rel_sab = (String) ret_vec.elementAt(3); String key = target_concept_name + delim + relationship_name + delim + target_concept_code + delim + rel_sab; if (sortBy.compareTo("source") == 0) { key = rel_sab + delim + target_concept_name + delim + relationship_name + delim + target_concept_code; } else if (sortBy.compareTo("rela") == 0) { key = relationship_name + delim + target_concept_name + delim + target_concept_code + delim + rel_sab; } else if (sortBy.compareTo("code") == 0) { key = target_concept_code + delim + target_concept_name + delim + relationship_name + delim + rel_sab; } hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public void removeRedundantRecords(HashMap hmap) { Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); while (it.hasNext()) { String rel = (String) it.next(); Vector v = (Vector) hmap.get(rel); HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } hmap.put(rel, u); } } public Vector removeRedundantRecords(Vector v) { HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } return u; } /* * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code, Vector sort_option) { * * Debug.println("(*) DataUtils getAssociationTargetHashMap "); Vector * parent_asso_vec = new Vector(Arrays .asList(hierAssocToParentNodes_)); * Vector child_asso_vec = new Vector(Arrays * .asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new * Vector(Arrays .asList(assocToSiblingNodes_)); Vector bt_vec = new * Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new * Vector(Arrays.asList(assocToNTNodes_)); Vector category_vec = new * Vector(Arrays.asList(relationshipCategories_)); * * HashMap rel_hmap = new HashMap(); for (int k = 0; k < * category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); Vector vec = new Vector(); * rel_hmap.put(category, vec); } * * Vector w = new Vector(); HashSet hset = new HashSet(); * * long ms = System.currentTimeMillis(), delay = 0; String action = * "Retrieving all relationships from the server"; HashMap hmap = * getRelatedConceptsHashMap(scheme, version, code, null, 0); // * resolveCodedEntryDepth // = // 0; delay = System.currentTimeMillis() - * ms; Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); * * // Categorize relationships into six categories and find association // * source data ms = System.currentTimeMillis(); action = * "Categorizing relationships into six categories; finding source data for each relationship" * ; while (it.hasNext()) { String rel_rela = (String) it.next(); if * (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = * DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); * String rela = (String) u.elementAt(1); * * String category = "Other"; if (parent_asso_vec.contains(rel)) category = * "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else * if (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; else if * (sibling_asso_vec.contains(rel)) category = "Sibling"; Vector v = * (Vector) hmap.get(rel_rela); * * for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = * (AssociatedConcept) v.elementAt(i); EntityDescription ed = * ac.getEntityDescription(); String source = "unspecified"; * * for (NameAndValue qualifier : ac.getAssociationQualifiers() * .getNameAndValue()) { if (SOURCE.equalsIgnoreCase(qualifier.getName())) { * source = qualifier.getContent(); w = (Vector) rel_hmap.get(category); if * (w == null) { w = new Vector(); } String str = rela + "|" + * ac.getEntityDescription().getContent() + "|" + ac.getCode() + "|" + * source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } * } } } } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * // Remove redundant RO relationships ms = System.currentTimeMillis(); * action = "Removing redundant RO and CHD relationships"; * * HashSet other_hset = new HashSet(); Vector w2 = (Vector) * rel_hmap.get("Other"); for (int k = 0; k < w2.size(); k++) { String s = * (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); Vector * ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } Vector w3 = new Vector(); for (int k = 0; k < * w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = * DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); * String name = (String) ret_vec.elementAt(1); String target_code = * (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { * // RO String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); * * other_hset = new HashSet(); w2 = (Vector) rel_hmap.get("Child"); for (int * k = 0; k < w2.size(); k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } w3 = new Vector(); for (int k = 0; k < w2.size(); * k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else * { String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); * delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * ms = System.currentTimeMillis(); action = * "Sorting relationships by sort options (columns)"; * * // Sort relationships by sort options (columns) if (sort_option == null) * { for (int k = 0; k < category_vec.size(); k++) { String category = * (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); * SortUtils.quickSort(w); rel_hmap.put(category, w); } } else { for (int k * = 0; k < category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); String * sortOption = (String) sort_option.elementAt(k); // * SortUtils.quickSort(w); w = sortRelationshipData(w, sortOption); * rel_hmap.put(category, w); } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * removeRedundantRecords(rel_hmap); String incomplete = (String) * hmap.get(INCOMPLETE); if (incomplete != null) rel_hmap.put(INCOMPLETE, * incomplete); return rel_hmap; } * * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code) { return getAssociationTargetHashMap(scheme, version, code, * null); } */ public Vector hashSet2Vector(HashSet hset) { if (hset == null) return null; Vector v = new Vector(); Iterator it = hset.iterator(); while (it.hasNext()) { String t = (String) it.next(); v.add(t); } return v; } // For relationships tab public HashMap getAssociationTargetHashMap(String CUI, Vector sort_option) { Debug.println("(*) DataUtils getAssociationTargetHashMap "); long ms, delay = 0; String action = null; ms = System.currentTimeMillis(); action = "Initializing member variables"; List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector category_vec = new Vector(Arrays.asList(_relationshipCategories)); HashMap rel_hmap = new HashMap(); for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); HashSet hset = new HashSet(); rel_hmap.put(category, hset); } HashSet w = new HashSet(); Map<String, List<RelationshipTabResults>> map = null; Map<String, List<RelationshipTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); try { _logger.info("************** metabrowser-extension *****************"); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); if (mbs == null) { _logger.error("Error! metabrowser-extension is null!"); return null; } ms = System.currentTimeMillis(); action = "Retrieving " + SOURCE_OF; ms = System.currentTimeMillis(); _logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); _logger.info("CUI: " + CUI); _logger.info("Direction: " + Direction.SOURCEOF); map = mbs.getRelationshipsDisplay(CUI, null, Direction.SOURCEOF); _logger.info("Done !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Retrieving " + TARGET_OF; ms = System.currentTimeMillis(); map2 = mbs.getRelationshipsDisplay(CUI, par_chd_assoc_list, Direction.TARGETOF); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); } catch (Exception ex) { ex.printStackTrace(); return null; } // Categorize relationships into six categories and find association // source data ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } for (String rel : map2.keySet()) { List<RelationshipTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // Remove redundant RO relationships ms = System.currentTimeMillis(); action = "Removing redundant RO and CHD relationships"; HashSet other_hset = new HashSet(); HashSet w2 = (HashSet) rel_hmap.get("Other"); Iterator it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } HashSet w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Other"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { // RO String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); other_hset = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Sorting relationships by sort options (columns)"; HashMap new_rel_hmap = new HashMap(); // Sort relationships by sort options (columns) if (sort_option == null) { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); SortUtils.quickSort(rel_v); new_rel_hmap.put(category, rel_v); } } else { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); String sortOption = (String) sort_option.elementAt(k); rel_v = sortRelationshipData(rel_v, sortOption); new_rel_hmap.put(category, rel_v); } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // KLO, testing Vector sibling_vector = getSiblings(CUI); if (sort_option != null) { sibling_vector = sortRelationshipData(sibling_vector, (String) sort_option.elementAt(4)); } //new_rel_hmap.put("Sibling", getSiblings(CUI)); new_rel_hmap.put("Sibling", sibling_vector); removeRedundantRecords(new_rel_hmap); String incomplete = (String) new_rel_hmap.get(INCOMPLETE); if (incomplete != null) { new_rel_hmap.put(INCOMPLETE, incomplete); } return new_rel_hmap; } public HashMap createCUI2SynonymsHahMap( Map<String, List<BySourceTabResults>> map, Map<String, List<BySourceTabResults>> map2) { HashMap hmap = new HashMap(); for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } return hmap; } public static BySourceTabResults findHighestRankedAtom( Vector<BySourceTabResults> v, String source) { if (v == null) return null; if (v.size() == 0) return null; if (v.size() == 1) return (BySourceTabResults) v.elementAt(0); BySourceTabResults target = null; for (int i = 0; i < v.size(); i++) { BySourceTabResults r = (BySourceTabResults) v.elementAt(i); if (source != null) { if (r.getSource().compareTo(source) == 0) { if (target == null) { target = r; } else { // select the higher ranked one as target String idx_target = NCImBrowserProperties.getRank(target.getType(), target.getSource()); String idx_atom = NCImBrowserProperties.getRank(r.getType(), r .getSource()); if (idx_atom != null && idx_atom.compareTo(idx_target) > 0) { target = r; } } } } else { return r; } } return target; } public Vector getNeighborhoodSynonyms(String CUI, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); // par_chd_assoc_list.add("RN"); Vector ret_vec = new Vector(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; String action_overall = "By source delay (total time)"; ms_all = System.currentTimeMillis(); long ms = System.currentTimeMillis(), delay = 0; String action = null;// "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); // HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); Map<String, List<BySourceTabResults>> map = null; Map<String, List<BySourceTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; try { action = "Retrieve data from browser extension"; ms = System.currentTimeMillis(); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); // String actionTmp = "Getting " + SOURCE_OF; // long msTmp = System.currentTimeMillis(); map = mbs.getBySourceTabDisplay(CUI, sab, null, Direction.SOURCEOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); // actionTmp = "Getting " + TARGET_OF; // msTmp = System.currentTimeMillis(); // to be modified: BT and PAR only??? map2 = mbs.getBySourceTabDisplay(CUI, sab, par_chd_assoc_list, Direction.TARGETOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); } catch (Exception ex) { } action = "Sort synonyms by CUI"; ms = System.currentTimeMillis(); Vector u = new Vector(); HashMap cui2SynonymsMap = createCUI2SynonymsHahMap(map, map2); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); HashSet CUI_hashset = new HashSet(); ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; ms_find_highest_rank_atom_delay = 0; String t = null; for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { // check CUI_hashmap containsKey(rel$code)??? if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } t = t + "|" + code + "|" + * rela + "|" + category; * * w.add(t); */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } // *** do the same for map2 for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } // w.add(t); CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } long total_categorization_delay = System.currentTimeMillis() - ms; String action_atom = "Find highest rank atom delay"; Debug.println("Run time (ms) for " + action_atom + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action_atom, "getNeighborhoodSynonyms"); long absolute_categorization_delay = total_categorization_delay - ms_find_highest_rank_atom_delay; Debug.println("Run time (ms) for " + action + " " + absolute_categorization_delay); DBG.debugDetails(absolute_categorization_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = System.currentTimeMillis(); action = "Remove redundant relationships"; for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); int j = i + 1; Vector<String> v = parseData(s, "|"); if (v.size() == 7) { String rel = (String) v.elementAt(6); if (rel.compareTo("Child") != 0 && rel.compareTo("Other") != 0) { u.add(s); } else if (rel.compareTo("Child") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("CHD") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!hasSubtype_hset.contains(code)) { u.add(s); } } } else if (rel.compareTo("Other") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("RO") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!rel_hset.contains(code)) { u.add(s); } } } } else { // Debug.println("(" + j + ") ??? " + s); } } delay = System.currentTimeMillis() - ms_remove_RO_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "Initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); // DBG.debugDetails("Max Return", NCImBrowserProperties.maxToReturn); delay = System.currentTimeMillis() - ms_all; Debug.println("Run time (ms) for " + action_overall + " " + delay); DBG.debugDetails(delay, action_overall, "getNeighborhoodSynonyms"); return u; } public static String getCodingSchemeURIAndVersion(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { if (ltag == null) return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); } } } } } catch (Exception e) { e.printStackTrace(); } return null; } public static String htmlEntityEncode(String s) { StringBuilder buf = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') { buf.append(c); } else { buf.append("&#").append((int) c).append(";"); } } return buf.toString(); } // [#23318] Maintain a history of visited concepts public static String getVisitedConceptLink(Vector concept_vec) { StringBuffer strbuf = new StringBuffer(); String line = "<A href=\"#\" onmouseover=\"Tip('"; strbuf.append(line); strbuf.append("<ul>"); for (int i = 0; i < concept_vec.size(); i++) { int j = concept_vec.size() - i - 1; String concept_data = (String) concept_vec.elementAt(j); Vector w = DataUtils.parseData(concept_data, "|"); String scheme = Constants.CODING_SCHEME_NAME; String code = (String) w.elementAt(0); String name = (String) w.elementAt(1); name = htmlEntityEncode(name); strbuf.append("<li>"); line = "<a href=\\'/ncimbrowser/ConceptReport.jsp?dictionary=" + scheme + "&code=" + code + "\\'>" + name + "</a><br>"; strbuf.append(line); strbuf.append("</li>"); } strbuf.append("</ul>"); line = "',"; strbuf.append(line); line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\""; strbuf.append(line); line = " onmouseout=UnTip() "; strbuf.append(line); line = ">Visited Concepts</A>"; strbuf.append(line); return strbuf.toString(); } public static HashMap getPropertyValuesForCodes(String scheme, String version, Vector codes, String propertyName) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); for (int i = 0; i < codes.size(); i++) { String code = (String) codes.elementAt(i); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); } CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { LocalNameList propertyNames = new LocalNameList(); propertyNames.addEntry(propertyName); CodedNodeSet.PropertyType[] propertyTypes = null; long ms = System.currentTimeMillis(), delay = 0; SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; // needs to be set to true int maxToReturn = codes.size(); ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, propertyNames, propertyTypes, resolveObjects, maxToReturn); // _logger.debug("resolveToList done"); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() > 0) { for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); } else { // _logger.debug(c.getEntityDescription().getContent()); Property[] properties = c.getProperty(); String values = ""; for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; values = values + prop.getValue().getContent(); if (j < properties.length - 1) { values = values + "; "; } } hmap.put(rcr.getCode(), values); } } } return hmap; } catch (Exception e) { _logger.error("Method: SearchUtil.searchByProperties"); _logger.error("* ERROR: cns.resolve throws exceptions."); _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector getConceptSources(String scheme, String version, String code) { Entity c = getConceptByCode(scheme, version, null, code); if (c == null) return null; Presentation[] presentations = c.getPresentation(); HashSet hset = new HashSet(); Vector v = new Vector(); for (int i = 0; i < presentations.length; i++) { Presentation presentation = presentations[i]; // java.lang.String name = presentation.getPropertyName(); // java.lang.String prop_value = // presentation.getValue().getContent(); Source[] sources = presentation.getSource(); for (int j = 0; j < sources.length; j++) { Source source = (Source) sources[j]; java.lang.String sab = source.getContent(); if (!hset.contains(sab)) { hset.add(sab); v.add(sab); } } } hset.clear(); return v; } public static String getMetadataValue(String scheme, String propertyName){ Vector v; try { v = getMetadataValues(scheme, propertyName); } catch (Exception e) { _logger.error(e.getMessage()); return null; } if (v == null || v.size() == 0) return null; return (String) v.elementAt(0); } public static Vector getMetadataValues(String scheme, String propertyName) { Vector v = new Vector(); /* * if (formalName2MetadataHashMap == null) { * //formalName2MetadataHashMap = getFormalName2MetadataHashMap(); * MetadataUtils.setSAB2FormalNameHashMap(); } */ if (_formalName2MetadataHashMap == null) { _formalName2MetadataHashMap = MetadataUtils.getFormalName2MetadataHashMap(); } Vector metadataProperties = (Vector) _formalName2MetadataHashMap.get(scheme); if (metadataProperties != null) { for (int i = 0; i < metadataProperties.size(); i++) { String t = (String) metadataProperties.elementAt(i); Vector w = parseData(t, "|"); String t1 = (String) w.elementAt(0); String t2 = (String) w.elementAt(1); if (t1.compareTo(propertyName) == 0) v.add(t2); } } return v; } public static boolean checkIsLicensed(String sab) { if (sab == null) return false; String securd_vocabularies = NCImBrowserProperties.getSecuredVocabularies(); String target = "|" + sab + "|"; if (securd_vocabularies.indexOf(target) == -1) return false; return true; } // /////////////////////////////////////////////// // siblings // ////////////////////////////////////////////// public Vector getSiblings(String code) { // return getSiblings("NCI Metathesaurus", null, code); return getSiblingsExt(code); } public Vector getSiblings(String scheme, String version, String code) { LexBIGService lbSvc = null; LexBIGServiceConvenienceMethods lbscm = null; Vector sibling_vec = new Vector(); try { lbSvc = RemoteServerUtil.createLexBIGService(); lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { return sibling_vec; } HashSet hset = new HashSet(); String[] assocNames = new String[] { "PAR" }; // find parents Vector v = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames); for (int i = 0; i < v.size(); i++) { String t = (String) v.elementAt(i); Vector w = parseData(t); String rel = (String) w.elementAt(0); String rela = (String) w.elementAt(1); String parent_name = (String) w.elementAt(2); String parent_code = (String) w.elementAt(3); Vector u = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, parent_code, assocNames, false); for (int j = 0; j < u.size(); j++) { String t2 = (String) u.elementAt(j); Vector w2 = parseData(t2); String sib_rel = (String) w2.elementAt(0); String sib_rela = (String) w2.elementAt(1); String sib_name = (String) w2.elementAt(2); String sib_code = (String) w2.elementAt(3); String sib_sab = (String) w2.elementAt(4); if (!hset.contains(t2) && sib_code.compareTo(code) != 0) { sibling_vec.add("SIB" + "|" + sib_name + "|" + sib_code + "|" + sib_sab); } } } return sibling_vec; } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames) { return getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames, true); } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList(assocNames, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = -1;// NCImBrowserProperties.maxToReturn; boolean navigationForward = !direction; boolean navigationBackward = direction; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), navigationForward, navigationBackward, 1, 1, new LocalNameList(), null, null, maxToReturn); String qualifier_name = null; String qualifier_value = null; if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); if (!direction) targetof = ref.getSourceOf(); if (targetof != null) { Association[] associations = targetof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { String associationName = lbscm .getAssociationNameFromAssociationCode( scheme, csvt, assoc .getAssociationName()); if (associationName .compareToIgnoreCase("equivalentClass") != 0) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = "NA"; String asso_source = "NA"; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("source") == 0) { asso_source = qualifier_value; // replace // associationName // by // Rela // value break; } } } v.add(associationName + "|" + asso_label + "|" + ac.getReferencedEntry() .getEntityDescription() .getContent() + "|" + ac.getReferencedEntry() .getEntityCode() + "|" + asso_source); } } } } } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; } public static HashMap getPropertyValueHashMap(String code) { return getPropertyValueHashMap(Constants.CODING_SCHEME_NAME, null, code); } private static String getSourceQualifierValue(Property p) { if (p == null) return null; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareToIgnoreCase("source") == 0) { return qualifier_value; } } } return null; } private static String getPropertySource(Property p) { if (p == null) return null; Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; return src.getContent(); } return null; } public static HashMap getPropertyValueHashMap(String scheme, String version, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, null, null, resolveObjects, 1); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() == 0) return null; ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(0); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); return null; } return getPropertyValueHashMap(c); } catch (Exception e) { _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static HashMap getPropertyValueHashMap(Entity c) { if (c == null) { return null; } HashMap hmap = new HashMap(); Property[] properties = c.getProperty(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getPresentation(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getDefinition(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getComment(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } return hmap; } public List<RelationshipTabResults> getAssociatedConceptsEx(String CUI, String associationName, Direction direction) { List<String> assoc_list = new ArrayList(); assoc_list.add(associationName); LexBIGService lbs = RemoteServerUtil.createLexBIGService(); CodingScheme cs = null; List results = new ArrayList<RelationshipTabResults>(); try { cs = getCodingScheme("NCI Metathesaurus", null); MetaBrowserService mbs = null; try { mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); Map<String, List<RelationshipTabResults>> map = null; try { map = mbs.getRelationshipsDisplay(CUI, assoc_list, direction); } catch (Exception ex) { ex.printStackTrace(); return null; } for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); for (RelationshipTabResults result : relations) { results.add(result); } } return results; } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception ex) { } return null; } public Vector getSiblingsExt(String CUI) { Vector v = new Vector(); HashSet hset = new HashSet(); List results = getAssociatedConceptsEx(CUI, "PAR", Direction.TARGETOF); if (results == null) return null; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); for (int i = 0; i < results.size(); i++) { RelationshipTabResults result = (RelationshipTabResults) results.get(i); List children = getAssociatedConceptsEx(result.getCui(), "CHD", Direction.TARGETOF); for (int j = 0; j < children.size(); j++) { RelationshipTabResults sub_result = (RelationshipTabResults) children.get(j); String t = "SIB" + "|" + sub_result.getName() + "|" + sub_result.getCui() + "|" + sub_result.getSource(); if (!hset.contains(t) && sub_result.getCui().compareTo(CUI) != 0) { hset.add(t); // v.add(t); String key = sub_result.getSource() + "|" + sub_result.getName() + "|" + sub_result.getCui(); hmap.put(key, t); key_vec.add(key); } } } key_vec = SortUtils.quickSort(key_vec); for (int i = 0; i < key_vec.size(); i++) { String key = (String) key_vec.elementAt(i); String value = (String) hmap.get(key); v.add(value); } // return SortUtils.quickSort(v); return v; } public static String getAssociationReverseName(String assoName) { String assocLabel = assoName; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); assocLabel = lbscm .getAssociationReverseName(assoName, "NCI Metathesaurus", null); } catch (Exception ex) { ex.printStackTrace(); } return assocLabel; } }
true
true
public Vector getSuperconceptCodes(String scheme, String version, String code) { // throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm .createCodeNodeSet(new String[] { code }, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0).getEntityDescription() .getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { _logger .debug("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; String version = null; int knt = 0; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { version = css.getRepresentsVersion(); knt++; if (ltag == null) return version; RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); // KLO, 102409 if (tags == null) return version; if (tags != null && tags.length > 0) { for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return version; } } } } } } catch (Exception e) { // e.printStackTrace(); } if (ltag != null && ltag.compareToIgnoreCase("PRODUCTION") == 0 & knt == 1) { _logger.debug("\tUse " + version + " as default."); return version; } return null; } public static Vector<String> getVersionListData(String codingSchemeName) { Vector<String> v = new Vector(); try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if (csrl == null) _logger.warn("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i = 0; i < csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals( CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); if (formalname.compareTo(codingSchemeName) == 0) { String representsVersion = css.getRepresentsVersion(); v.add(representsVersion); } } } } catch (Exception ex) { } return v; } public static String getFileName(String pathname) { File file = new File(pathname); String filename = file.getName(); return filename; } protected static Association processForAnonomousNodes(Association assoc) { // clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for (int i = 0; i < assoc.getAssociatedConcepts() .getAssociatedConceptCount(); i++) { // Conditionals to deal with anonymous nodes and UMLS top nodes // "V-X" // The first three allow UMLS traversal to top node. // The last two are specific to owl anonymous nodes which can act // like false // top nodes. if (assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@@")) { // do nothing } else { temp.getAssociatedConcepts().addAssociatedConcept( assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } public static LocalNameList vector2LocalNameList(Vector<String> v) { if (v == null) return null; LocalNameList list = new LocalNameList(); for (int i = 0; i < v.size(); i++) { String vEntry = (String) v.elementAt(i); list.addEntry(vEntry); } return list; } protected static NameAndValueList createNameAndValueList(Vector names, Vector values) { if (names == null) return null; NameAndValueList nvList = new NameAndValueList(); for (int i = 0; i < names.size(); i++) { String name = (String) names.elementAt(i); String value = (String) values.elementAt(i); NameAndValue nv = new NameAndValue(); nv.setName(name); if (value != null) { nv.setContent(value); } nvList.addNameAndValue(nv); } return nvList; } protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { ex.printStackTrace(); } return cs; } public static Vector<SupportedProperty> getSupportedProperties( CodingScheme cs) { if (cs == null) return null; Vector<SupportedProperty> v = new Vector<SupportedProperty>(); SupportedProperty[] properties = cs.getMappings().getSupportedProperty(); for (int i = 0; i < properties.length; i++) { SupportedProperty sp = (SupportedProperty) properties[i]; v.add(sp); } return v; } public static Vector<String> getSupportedPropertyNames(CodingScheme cs) { Vector w = getSupportedProperties(cs); if (w == null) return null; Vector<String> v = new Vector<String>(); for (int i = 0; i < w.size(); i++) { SupportedProperty sp = (SupportedProperty) w.elementAt(i); v.add(sp.getLocalId()); } return v; } public static Vector<String> getSupportedPropertyNames(String codingScheme, String version) { CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { CodingScheme cs = getCodingScheme(codingScheme, versionOrTag); return getSupportedPropertyNames(cs); } catch (Exception ex) { } return null; } public static Vector getPropertyNamesByType(Entity concept, String property_type) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } if (properties == null || properties.length == 0) return v; HashSet hset = new HashSet(); for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; String nm = p.getPropertyName(); if (!hset.contains(nm)) { hset.add(nm); v.add(p.getPropertyName()); } } hset.clear(); return v; } public static Vector getPropertyValues(Entity concept, String property_type, String property_name) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } /* * else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0) { * properties = concept.getInstruction(); } */ else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } else { _logger .warn("WARNING: property_type not found -- " + property_type); } if (properties == null || properties.length == 0) return v; for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; if (property_name.compareTo(p.getPropertyName()) == 0) { String t = p.getValue().getContent(); Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; t = t + "|" + src.getContent(); } else { if (property_name.compareToIgnoreCase("definition") == 0) { _logger.warn("*** WARNING: " + property_name + " with no source data: " + p.getValue().getContent()); PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); // _logger.debug("\t*** qualifier_name: " + // qualifier_name); // _logger.debug("\t*** qualifier_value: " // + qualifier_value); if (qualifier_name.compareTo("source") == 0) { t = t + "|" + qualifier_value; // _logger.debug("*** SOURCE: " + // qualifier_value); break; } } } else { _logger .warn("*** SOURCE NOT FOUND IN qualifiers neither. "); } } } v.add(t); } } return v; } // ===================================================================================== public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); List list = new ArrayList(); try { CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); Relations[] relations = cs.getRelations(); for (int i = 0; i < relations.length; i++) { Relations relation = relations[i]; if (relation.getContainerName().compareToIgnoreCase("roles") == 0) { AssociationPredicate[] asso_array = relation.getAssociationPredicate(); for (int j = 0; j < asso_array.length; j++) { AssociationPredicate association = (AssociationPredicate) asso_array[j]; list.add(association.getAssociationName()); } } } } catch (Exception ex) { } return list; } public static void sortArray(ArrayList list) { String tmp; if (list.size() <= 1) return; for (int i = 0; i < list.size(); i++) { String s1 = (String) list.get(i); for (int j = i + 1; j < list.size(); j++) { String s2 = (String) list.get(j); if (s1.compareToIgnoreCase(s2) > 0) { tmp = s1; list.set(i, s2); list.set(j, tmp); } } } } public static void sortArray(String[] strArray) { String tmp; if (strArray.length <= 1) return; for (int i = 0; i < strArray.length; i++) { for (int j = i + 1; j < strArray.length; j++) { if (strArray[i].compareToIgnoreCase(strArray[j]) > 0) { tmp = strArray[i]; strArray[i] = strArray[j]; strArray[j] = tmp; } } } } public String[] getSortedKeys(HashMap map) { if (map == null) return null; Set keyset = map.keySet(); String[] names = new String[keyset.size()]; Iterator it = keyset.iterator(); int i = 0; while (it.hasNext()) { String s = (String) it.next(); names[i] = s; i++; } sortArray(names); return names; } public String getPreferredName(Entity c) { Presentation[] presentations = c.getPresentation(); for (int i = 0; i < presentations.length; i++) { Presentation p = presentations[i]; if (p.getPropertyName().compareTo("Preferred_Name") == 0) { return p.getValue().getContent(); } } return null; } public HashMap getRelationshipHashMap(String scheme, String version, String code) { return getRelationshipHashMap(scheme, version, code, null); } protected static String getDirectionalLabel( LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, boolean navigatedFwd) throws LBException { String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(assoc .getAssociationName(), scheme, csvt) : lbscm .getAssociationReverseName(assoc.getAssociationName(), scheme, csvt); if (StringUtils.isBlank(assocLabel)) assocLabel = (navigatedFwd ? "" : "[Inverse]") + assoc.getAssociationName(); return assocLabel; } public LexBIGServiceConvenienceMethods createLexBIGServiceConvenienceMethods( LexBIGService lbSvc) { LexBIGServiceConvenienceMethods lbscm = null; try { lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { ex.printStackTrace(); } return lbscm; } public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab) { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); // Perform the query ... ResolvedConceptReferenceList matches = null; List list = new ArrayList();// getSupportedRoleNames(lbSvc, scheme, // version); ArrayList roleList = new ArrayList(); ArrayList associationList = new ArrayList(); ArrayList superconceptList = new ArrayList(); ArrayList siblingList = new ArrayList(); ArrayList subconceptList = new ArrayList(); ArrayList btList = new ArrayList(); ArrayList ntList = new ArrayList(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); HashMap map = new HashMap(); try { // LexBIGServiceConvenienceMethods lbscm = // createLexBIGServiceConvenienceMethods(lbSvc); /* * LexBIGServiceConvenienceMethods lbscm = * (LexBIGServiceConvenienceMethods) lbSvc * .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); */ CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); if (sab != null) { cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); } int maxToReturn = NCImBrowserProperties._maxToReturn; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), true, false, 1, 1, _noopList, null, null, null, maxToReturn, false); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); Association[] associations = sourceof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = assoc.getAssociationName(); // String associationName = // lbscm.getAssociationNameFromAssociationCode(scheme, // csvt, assoc.getAssociationName()); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; EntityDescription ed = ac.getEntityDescription(); String name = "No Description"; if (ed != null) name = ed.getContent(); String pt = name; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { String s = associationName + "|" + pt + "|" + ac.getConceptCode(); if (!parent_asso_vec.contains(associationName) && !child_asso_vec .contains(associationName)) { if (sibling_asso_vec .contains(associationName)) { siblingList.add(s); } else if (bt_vec.contains(associationName)) { btList.add(s); } else if (nt_vec.contains(associationName)) { ntList.add(s); } else { associationList.add(s); } } } } } } } if (roleList.size() > 0) { SortUtils.quickSort(roleList); } if (associationList.size() > 0) { // KLO, 052909 associationList = removeRedundantRelationships(associationList, "RO"); SortUtils.quickSort(associationList); } if (siblingList.size() > 0) { SortUtils.quickSort(siblingList); } if (btList.size() > 0) { SortUtils.quickSort(btList); } if (ntList.size() > 0) { SortUtils.quickSort(ntList); } map.put(TYPE_ROLE, roleList); map.put(TYPE_ASSOCIATION, associationList); map.put(TYPE_SIBLINGCONCEPT, siblingList); map.put(TYPE_BROADERCONCEPT, btList); map.put(TYPE_NARROWERCONCEPT, ntList); Vector superconcept_vec = getSuperconcepts(scheme, version, code); for (int i = 0; i < superconcept_vec.size(); i++) { Entity c = (Entity) superconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); superconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(superconceptList); map.put(TYPE_SUPERCONCEPT, superconceptList); Vector subconcept_vec = getSubconcepts(scheme, version, code); for (int i = 0; i < subconcept_vec.size(); i++) { Entity c = (Entity) subconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); subconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(subconceptList); map.put(TYPE_SUBCONCEPT, subconceptList); } catch (Exception ex) { ex.printStackTrace(); } return map; } public Vector getSuperconcepts(String scheme, String version, String code) { return getAssociationSources(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public Vector getSubconcepts(String scheme, String version, String code) { return getAssociationTargets(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = false; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator( CodedNodeGraph cng, ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn) { CodedNodeSet cns = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator toNodeList "); cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); if (cns == null) { _logger.warn("cng.toNodeList returns null???"); return null; } SortOptionList sortCriteria = null; // Constructors.createSortOptionList(new String[]{"matchToQuery", // "code"}); LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; ResolvedConceptReferencesIterator iterator = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve "); iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes); System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve DONE "); } catch (Exception e) { e.printStackTrace(); } if (iterator == null) { _logger.warn("cns.resolve returns null???"); } return iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn) { return resolveIterator(iterator, maxToReturn, null); } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code) { Vector v = new Vector(); if (iterator == null) { _logger.debug("No match."); return v; } try { int iteration = 0; while (iterator.hasNext()) { iteration++; iterator = iterator.scroll(maxToReturn); ResolvedConceptReferenceList rcrl = iterator.getNext(); ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference(); for (int i = 0; i < rcra.length; i++) { ResolvedConceptReference rcr = rcra[i]; org.LexGrid.concepts.Entity ce = rcr.getReferencedEntry(); if (code == null) { v.add(ce); } else { if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } } } catch (Exception e) { e.printStackTrace(); } return v; } public static Vector<String> parseData(String line) { return parseData(line, "|"); } public static Vector<String> parseData(String line, String tab) { Vector data_vec = new Vector(); StringTokenizer st = new StringTokenizer(line, tab); while (st.hasMoreTokens()) { String value = st.nextToken(); if (value.compareTo("null") == 0) value = " "; data_vec.add(value); } return data_vec; } public static String getHyperlink(String url, String codingScheme, String code) { codingScheme = codingScheme.replace(" ", "%20"); String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code; return link; } public List getHierarchyRoots(String scheme, String version, String hierarchyID) throws LBException { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); return getHierarchyRoots(scheme, csvt, hierarchyID); } public List getHierarchyRoots(String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); List list = ResolvedConceptReferenceList2List(roots); SortUtils.quickSort(list); return list; } public List ResolvedConceptReferenceList2List( ResolvedConceptReferenceList rcrl) { ArrayList list = new ArrayList(); for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); list.add(rcr); } return list; } public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, sab); } public static Vector getSynonyms(String scheme, String version, String tag, String code) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept) { return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept, String sab) { if (concept == null) return null; Vector v = new Vector(); Presentation[] properties = concept.getPresentation(); int n = 0; for (int i = 0; i < properties.length; i++) { Presentation p = properties[i]; // name String term_name = p.getValue().getContent(); String term_type = "null"; String term_source = "null"; String term_source_code = "null"; // source-code PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source-code") == 0) { term_source_code = qualifier_value; break; } } } // term type term_type = p.getRepresentationalForm(); // source Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; term_source = src.getContent(); } String t = null; if (sab == null) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } else if (term_source != null && sab.compareTo(term_source) == 0) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } } SortUtils.quickSort(v); return v; } public String getNCICBContactURL() { if (_ncicbContactURL != null) { return _ncicbContactURL; } String default_url = "[email protected]"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncicbContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL); if (_ncicbContactURL == null) { _ncicbContactURL = default_url; } } catch (Exception ex) { } _logger.debug("getNCICBContactURL returns " + _ncicbContactURL); return _ncicbContactURL; } public String getTerminologySubsetDownloadURL() { NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _terminologySubsetDownloadURL = properties .getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } catch (Exception ex) { } return _terminologySubsetDownloadURL; } public String getNCIMBuildInfo() { if (_ncimBuildInfo != null) { return _ncimBuildInfo; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO); if (_ncimBuildInfo == null) { _ncimBuildInfo = default_info; } } catch (Exception ex) { } _logger.debug("getNCIMBuildInfo returns " + _ncimBuildInfo); return _ncimBuildInfo; } public String getApplicationVersion() { if (_ncimAppVersion != null) { return _ncimAppVersion; } String default_info = "1.0"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimAppVersion = properties.getProperty(NCImBrowserProperties.NCIM_APP_VERSION); if (_ncimAppVersion == null) { _ncimAppVersion = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncimAppVersion; } public String getNCITAnthillBuildTagBuilt() { if (_ncitAnthillBuildTagBuilt != null) { return _ncitAnthillBuildTagBuilt; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitAnthillBuildTagBuilt = properties .getProperty(NCImBrowserProperties.APP_BUILD_TAG); if (_ncitAnthillBuildTagBuilt == null) { _ncitAnthillBuildTagBuilt = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncitAnthillBuildTagBuilt; } public String getEVSServiceURL() { if (_evsServiceURL != null) { return _evsServiceURL; } String default_info = "Local LexEVS"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _evsServiceURL = properties.getProperty(NCImBrowserProperties.EVS_SERVICE_URL); if (_evsServiceURL == null) { _evsServiceURL = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _evsServiceURL; } public String getNCItURL() { if (_ncitURL != null) { return _ncitURL; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitURL = properties.getProperty(NCImBrowserProperties.NCIT_URL); if (_ncitURL == null) { _ncitURL = default_info; } } catch (Exception ex) { } return _ncitURL; } public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) { Vector<String> v = new Vector<String>(); v.add("String"); v.add("Code"); v.add("CUI"); return v; } public static Vector getSources(String scheme, String version, String tag, String code) { Vector sources = getSynonyms(scheme, version, tag, code); // GLIOBLASTOMA MULTIFORME|DI|DXP|U000721 HashSet hset = new HashSet(); Vector source_vec = new Vector(); for (int i = 0; i < sources.size(); i++) { String s = (String) sources.elementAt(i); Vector ret_vec = DataUtils.parseData(s, "|"); String name = (String) ret_vec.elementAt(0); String type = (String) ret_vec.elementAt(1); String src = (String) ret_vec.elementAt(2); String srccode = (String) ret_vec.elementAt(3); if (!hset.contains(src)) { hset.add(src); source_vec.add(src); } } SortUtils.quickSort(source_vec); return source_vec; } public static boolean containSource(Vector sources, String source) { if (sources == null || sources.size() == 0) return false; String s = null; for (int i = 0; i < sources.size(); i++) { s = (String) sources.elementAt(i); if (s.compareTo(source) == 0) return true; } return false; } public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); // NameAndValueList nameAndValueList = // ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } SortUtils.quickSort(v); return v; } protected boolean isValidForSAB(AssociatedConcept ac, String sab) { for (NameAndValue qualifier : ac.getAssociationQualifiers() .getNameAndValue()) if (SOURCE.equalsIgnoreCase(qualifier.getContent()) && sab.equalsIgnoreCase(qualifier.getName())) return true; return false; } public Vector sortSynonyms(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String key = term_name + delim + term_source + delim + term_source_code + delim + term_type; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getAssociatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, false, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } hmap.put(associationName, v); } } } } } cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), Constructors.createNameAndValueList("source", source)); } else { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), null); } matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), false, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } if (associationName.compareTo("CHD") == 0) { associationName = "PAR"; } hmap.put(associationName, v); } } } } } } catch (Exception ex) { } return hmap; } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getRelatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { Debug.println("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches != null) { java.lang.Boolean incomplete = matches.getIncomplete(); // _logger.debug("(*) Number of matches: " + // matches.getResolvedConceptReferenceCount()); // _logger.debug("(*) Incomplete? " + incomplete); hmap.put(INCOMPLETE, incomplete.toString()); } if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; String directionalLabel = associationName; boolean navigatedFwd = true; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); } catch (Exception e) { Debug .println("(*) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) { String directionalLabel = associationName; boolean navigatedFwd = false; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); // Debug.println("(**) directionalLabel: associationName " // + associationName + // " directionalLabel: " + // directionalLabel); } catch (Exception e) { Debug .println("(**) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { // associationName = // qualifier_value; // // replace associationName // by Rela value asso_label = qualifier_value; break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } } } } } catch (Exception ex) { } return hmap; } private String findRepresentativeTerm(Entity c, String sab) { Vector synonyms = getSynonyms(c, sab); if (synonyms == null || synonyms.size() == 0) { // return null; // t = term_name + "|" + term_type + "|" + term_source + "|" + // term_source_code; return c.getEntityDescription().getContent() + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + Constants.EXTERNAL_TERM_SOURCE + "|" + Constants.EXTERNAL_TERM_SOURCE_CODE; } return NCImBrowserProperties.getHighestTermGroupRank(synonyms); } String getAssociationDirectionalName(LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String associationName, boolean navigatedFwd) { String assocLabel = null; try { assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(associationName, scheme, csvt) : lbscm.getAssociationReverseName( associationName, scheme, csvt); } catch (Exception ex) { } return assocLabel; } // Method for populating By Source tab relationships table public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay = 0; String action = "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; ms_all = System.currentTimeMillis(); while (it.hasNext()) { ms_categorization = System.currentTimeMillis(); String rel_rela = (String) it.next(); // _logger.debug("rel_rela: " + rel_rela); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; /* * if (parent_asso_vec.contains(rel)) category = "Child"; else * if (child_asso_vec.contains(rel)) category = "Parent"; else * if (bt_vec.contains(rel)) category = "Narrower"; else if * (nt_vec.contains(rel)) category = "Broader"; */ else if (sibling_asso_vec.contains(rel)) category = "Sibling"; ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization); Object obj = hmap.get(rel_rela); if (obj != null) { Vector v = (Vector) obj; // For each related concept: for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); Entity c = ac.getReferencedEntry(); if (!hset.contains(c.getEntityCode())) { hset.add(c.getEntityCode()); // Find the highest ranked atom data ms_find_highest_rank_atom = System.currentTimeMillis(); String t = findRepresentativeTerm(c, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); t = t + "|" + c.getEntityCode() + "|" + rela + "|" + category; // _logger.debug(t); w.add(t); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && category.compareTo("RO") != 0) { if (rel_hset.contains(c.getEntityCode())) { rel_hset.add(c.getEntityCode()); } } if (category.compareTo("Child") == 0 && category.compareTo("CHD") != 0) { if (hasSubtype_hset.contains(c.getEntityCode())) { hasSubtype_hset.add(c.getEntityCode()); } } } } } } } Vector u = new Vector(); // Remove redundant RO relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("RO") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } // Remove redundant CHD relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("CHD") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } ms_all_delay = System.currentTimeMillis() - ms_all; action = "categorizing relationships into six categories"; Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay); DBG.debugDetails(ms_categorization_delay, action, "getNeighborhoodSynonyms"); action = "finding highest ranked atoms"; Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay; action = "removing redundant RO relationships"; Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay); DBG.debugDetails(ms_remove_RO_delay, action, "getNeighborhoodSynonyms"); // Initial sort (refer to sortSynonymData method for sorting by a // specific column) long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); DBG.debugDetails("Max Return", NCImBrowserProperties._maxToReturn); return u; } public static String getRelationshipCode(String id) { if (id.compareTo("Parent") == 0) return "1"; else if (id.compareTo("Child") == 0) return "2"; else if (id.compareTo("Broader") == 0) return "3"; else if (id.compareTo("Narrower") == 0) return "4"; else if (id.compareTo("Sibling") == 0) return "5"; else return "6"; } public static boolean containsAllUpperCaseChars(String s) { for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch < 65 || ch > 90) return false; } return true; } public static Vector sortSynonymData(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String rel_type = (String) synonym_data.elementAt(6); String rel_type_str = getRelationshipCode(rel_type); String key = term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel") == 0) { String rel_key = rel; if (containsAllUpperCaseChars(rel)) rel_key = "|"; key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel_type_str; } if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } // KLO, 052909 private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) { ArrayList a = new ArrayList(); HashSet target_set = new HashSet(); for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { String associationTargetCode = w.elementAt(2); target_set.add(associationTargetCode); } } for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { a.add(s); } else { String associationTargetCode = w.elementAt(2); if (!target_set.contains(associationTargetCode)) { a.add(s); } } } return a; } public static Vector sortRelationshipData(Vector relationships, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < relationships.size(); n++) { String s = (String) relationships.elementAt(n); Vector ret_vec = DataUtils.parseData(s, "|"); String relationship_name = (String) ret_vec.elementAt(0); String target_concept_name = (String) ret_vec.elementAt(1); String target_concept_code = (String) ret_vec.elementAt(2); String rel_sab = (String) ret_vec.elementAt(3); String key = target_concept_name + delim + relationship_name + delim + target_concept_code + delim + rel_sab; if (sortBy.compareTo("source") == 0) { key = rel_sab + delim + target_concept_name + delim + relationship_name + delim + target_concept_code; } else if (sortBy.compareTo("rela") == 0) { key = relationship_name + delim + target_concept_name + delim + target_concept_code + delim + rel_sab; } else if (sortBy.compareTo("code") == 0) { key = target_concept_code + delim + target_concept_name + delim + relationship_name + delim + rel_sab; } hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public void removeRedundantRecords(HashMap hmap) { Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); while (it.hasNext()) { String rel = (String) it.next(); Vector v = (Vector) hmap.get(rel); HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } hmap.put(rel, u); } } public Vector removeRedundantRecords(Vector v) { HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } return u; } /* * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code, Vector sort_option) { * * Debug.println("(*) DataUtils getAssociationTargetHashMap "); Vector * parent_asso_vec = new Vector(Arrays .asList(hierAssocToParentNodes_)); * Vector child_asso_vec = new Vector(Arrays * .asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new * Vector(Arrays .asList(assocToSiblingNodes_)); Vector bt_vec = new * Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new * Vector(Arrays.asList(assocToNTNodes_)); Vector category_vec = new * Vector(Arrays.asList(relationshipCategories_)); * * HashMap rel_hmap = new HashMap(); for (int k = 0; k < * category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); Vector vec = new Vector(); * rel_hmap.put(category, vec); } * * Vector w = new Vector(); HashSet hset = new HashSet(); * * long ms = System.currentTimeMillis(), delay = 0; String action = * "Retrieving all relationships from the server"; HashMap hmap = * getRelatedConceptsHashMap(scheme, version, code, null, 0); // * resolveCodedEntryDepth // = // 0; delay = System.currentTimeMillis() - * ms; Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); * * // Categorize relationships into six categories and find association // * source data ms = System.currentTimeMillis(); action = * "Categorizing relationships into six categories; finding source data for each relationship" * ; while (it.hasNext()) { String rel_rela = (String) it.next(); if * (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = * DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); * String rela = (String) u.elementAt(1); * * String category = "Other"; if (parent_asso_vec.contains(rel)) category = * "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else * if (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; else if * (sibling_asso_vec.contains(rel)) category = "Sibling"; Vector v = * (Vector) hmap.get(rel_rela); * * for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = * (AssociatedConcept) v.elementAt(i); EntityDescription ed = * ac.getEntityDescription(); String source = "unspecified"; * * for (NameAndValue qualifier : ac.getAssociationQualifiers() * .getNameAndValue()) { if (SOURCE.equalsIgnoreCase(qualifier.getName())) { * source = qualifier.getContent(); w = (Vector) rel_hmap.get(category); if * (w == null) { w = new Vector(); } String str = rela + "|" + * ac.getEntityDescription().getContent() + "|" + ac.getCode() + "|" + * source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } * } } } } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * // Remove redundant RO relationships ms = System.currentTimeMillis(); * action = "Removing redundant RO and CHD relationships"; * * HashSet other_hset = new HashSet(); Vector w2 = (Vector) * rel_hmap.get("Other"); for (int k = 0; k < w2.size(); k++) { String s = * (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); Vector * ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } Vector w3 = new Vector(); for (int k = 0; k < * w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = * DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); * String name = (String) ret_vec.elementAt(1); String target_code = * (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { * // RO String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); * * other_hset = new HashSet(); w2 = (Vector) rel_hmap.get("Child"); for (int * k = 0; k < w2.size(); k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } w3 = new Vector(); for (int k = 0; k < w2.size(); * k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else * { String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); * delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * ms = System.currentTimeMillis(); action = * "Sorting relationships by sort options (columns)"; * * // Sort relationships by sort options (columns) if (sort_option == null) * { for (int k = 0; k < category_vec.size(); k++) { String category = * (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); * SortUtils.quickSort(w); rel_hmap.put(category, w); } } else { for (int k * = 0; k < category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); String * sortOption = (String) sort_option.elementAt(k); // * SortUtils.quickSort(w); w = sortRelationshipData(w, sortOption); * rel_hmap.put(category, w); } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * removeRedundantRecords(rel_hmap); String incomplete = (String) * hmap.get(INCOMPLETE); if (incomplete != null) rel_hmap.put(INCOMPLETE, * incomplete); return rel_hmap; } * * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code) { return getAssociationTargetHashMap(scheme, version, code, * null); } */ public Vector hashSet2Vector(HashSet hset) { if (hset == null) return null; Vector v = new Vector(); Iterator it = hset.iterator(); while (it.hasNext()) { String t = (String) it.next(); v.add(t); } return v; } // For relationships tab public HashMap getAssociationTargetHashMap(String CUI, Vector sort_option) { Debug.println("(*) DataUtils getAssociationTargetHashMap "); long ms, delay = 0; String action = null; ms = System.currentTimeMillis(); action = "Initializing member variables"; List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector category_vec = new Vector(Arrays.asList(_relationshipCategories)); HashMap rel_hmap = new HashMap(); for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); HashSet hset = new HashSet(); rel_hmap.put(category, hset); } HashSet w = new HashSet(); Map<String, List<RelationshipTabResults>> map = null; Map<String, List<RelationshipTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); try { _logger.info("************** metabrowser-extension *****************"); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); if (mbs == null) { _logger.error("Error! metabrowser-extension is null!"); return null; } ms = System.currentTimeMillis(); action = "Retrieving " + SOURCE_OF; ms = System.currentTimeMillis(); _logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); _logger.info("CUI: " + CUI); _logger.info("Direction: " + Direction.SOURCEOF); map = mbs.getRelationshipsDisplay(CUI, null, Direction.SOURCEOF); _logger.info("Done !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Retrieving " + TARGET_OF; ms = System.currentTimeMillis(); map2 = mbs.getRelationshipsDisplay(CUI, par_chd_assoc_list, Direction.TARGETOF); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); } catch (Exception ex) { ex.printStackTrace(); return null; } // Categorize relationships into six categories and find association // source data ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } for (String rel : map2.keySet()) { List<RelationshipTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // Remove redundant RO relationships ms = System.currentTimeMillis(); action = "Removing redundant RO and CHD relationships"; HashSet other_hset = new HashSet(); HashSet w2 = (HashSet) rel_hmap.get("Other"); Iterator it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } HashSet w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Other"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { // RO String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); other_hset = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Sorting relationships by sort options (columns)"; HashMap new_rel_hmap = new HashMap(); // Sort relationships by sort options (columns) if (sort_option == null) { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); SortUtils.quickSort(rel_v); new_rel_hmap.put(category, rel_v); } } else { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); String sortOption = (String) sort_option.elementAt(k); rel_v = sortRelationshipData(rel_v, sortOption); new_rel_hmap.put(category, rel_v); } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // KLO, testing Vector sibling_vector = getSiblings(CUI); if (sort_option != null) { sibling_vector = sortRelationshipData(sibling_vector, (String) sort_option.elementAt(4)); } //new_rel_hmap.put("Sibling", getSiblings(CUI)); new_rel_hmap.put("Sibling", sibling_vector); removeRedundantRecords(new_rel_hmap); String incomplete = (String) new_rel_hmap.get(INCOMPLETE); if (incomplete != null) { new_rel_hmap.put(INCOMPLETE, incomplete); } return new_rel_hmap; } public HashMap createCUI2SynonymsHahMap( Map<String, List<BySourceTabResults>> map, Map<String, List<BySourceTabResults>> map2) { HashMap hmap = new HashMap(); for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } return hmap; } public static BySourceTabResults findHighestRankedAtom( Vector<BySourceTabResults> v, String source) { if (v == null) return null; if (v.size() == 0) return null; if (v.size() == 1) return (BySourceTabResults) v.elementAt(0); BySourceTabResults target = null; for (int i = 0; i < v.size(); i++) { BySourceTabResults r = (BySourceTabResults) v.elementAt(i); if (source != null) { if (r.getSource().compareTo(source) == 0) { if (target == null) { target = r; } else { // select the higher ranked one as target String idx_target = NCImBrowserProperties.getRank(target.getType(), target.getSource()); String idx_atom = NCImBrowserProperties.getRank(r.getType(), r .getSource()); if (idx_atom != null && idx_atom.compareTo(idx_target) > 0) { target = r; } } } } else { return r; } } return target; } public Vector getNeighborhoodSynonyms(String CUI, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); // par_chd_assoc_list.add("RN"); Vector ret_vec = new Vector(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; String action_overall = "By source delay (total time)"; ms_all = System.currentTimeMillis(); long ms = System.currentTimeMillis(), delay = 0; String action = null;// "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); // HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); Map<String, List<BySourceTabResults>> map = null; Map<String, List<BySourceTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; try { action = "Retrieve data from browser extension"; ms = System.currentTimeMillis(); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); // String actionTmp = "Getting " + SOURCE_OF; // long msTmp = System.currentTimeMillis(); map = mbs.getBySourceTabDisplay(CUI, sab, null, Direction.SOURCEOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); // actionTmp = "Getting " + TARGET_OF; // msTmp = System.currentTimeMillis(); // to be modified: BT and PAR only??? map2 = mbs.getBySourceTabDisplay(CUI, sab, par_chd_assoc_list, Direction.TARGETOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); } catch (Exception ex) { } action = "Sort synonyms by CUI"; ms = System.currentTimeMillis(); Vector u = new Vector(); HashMap cui2SynonymsMap = createCUI2SynonymsHahMap(map, map2); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); HashSet CUI_hashset = new HashSet(); ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; ms_find_highest_rank_atom_delay = 0; String t = null; for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { // check CUI_hashmap containsKey(rel$code)??? if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } t = t + "|" + code + "|" + * rela + "|" + category; * * w.add(t); */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } // *** do the same for map2 for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } // w.add(t); CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } long total_categorization_delay = System.currentTimeMillis() - ms; String action_atom = "Find highest rank atom delay"; Debug.println("Run time (ms) for " + action_atom + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action_atom, "getNeighborhoodSynonyms"); long absolute_categorization_delay = total_categorization_delay - ms_find_highest_rank_atom_delay; Debug.println("Run time (ms) for " + action + " " + absolute_categorization_delay); DBG.debugDetails(absolute_categorization_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = System.currentTimeMillis(); action = "Remove redundant relationships"; for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); int j = i + 1; Vector<String> v = parseData(s, "|"); if (v.size() == 7) { String rel = (String) v.elementAt(6); if (rel.compareTo("Child") != 0 && rel.compareTo("Other") != 0) { u.add(s); } else if (rel.compareTo("Child") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("CHD") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!hasSubtype_hset.contains(code)) { u.add(s); } } } else if (rel.compareTo("Other") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("RO") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!rel_hset.contains(code)) { u.add(s); } } } } else { // Debug.println("(" + j + ") ??? " + s); } } delay = System.currentTimeMillis() - ms_remove_RO_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "Initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); // DBG.debugDetails("Max Return", NCImBrowserProperties.maxToReturn); delay = System.currentTimeMillis() - ms_all; Debug.println("Run time (ms) for " + action_overall + " " + delay); DBG.debugDetails(delay, action_overall, "getNeighborhoodSynonyms"); return u; } public static String getCodingSchemeURIAndVersion(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { if (ltag == null) return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); } } } } } catch (Exception e) { e.printStackTrace(); } return null; } public static String htmlEntityEncode(String s) { StringBuilder buf = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') { buf.append(c); } else { buf.append("&#").append((int) c).append(";"); } } return buf.toString(); } // [#23318] Maintain a history of visited concepts public static String getVisitedConceptLink(Vector concept_vec) { StringBuffer strbuf = new StringBuffer(); String line = "<A href=\"#\" onmouseover=\"Tip('"; strbuf.append(line); strbuf.append("<ul>"); for (int i = 0; i < concept_vec.size(); i++) { int j = concept_vec.size() - i - 1; String concept_data = (String) concept_vec.elementAt(j); Vector w = DataUtils.parseData(concept_data, "|"); String scheme = Constants.CODING_SCHEME_NAME; String code = (String) w.elementAt(0); String name = (String) w.elementAt(1); name = htmlEntityEncode(name); strbuf.append("<li>"); line = "<a href=\\'/ncimbrowser/ConceptReport.jsp?dictionary=" + scheme + "&code=" + code + "\\'>" + name + "</a><br>"; strbuf.append(line); strbuf.append("</li>"); } strbuf.append("</ul>"); line = "',"; strbuf.append(line); line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\""; strbuf.append(line); line = " onmouseout=UnTip() "; strbuf.append(line); line = ">Visited Concepts</A>"; strbuf.append(line); return strbuf.toString(); } public static HashMap getPropertyValuesForCodes(String scheme, String version, Vector codes, String propertyName) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); for (int i = 0; i < codes.size(); i++) { String code = (String) codes.elementAt(i); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); } CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { LocalNameList propertyNames = new LocalNameList(); propertyNames.addEntry(propertyName); CodedNodeSet.PropertyType[] propertyTypes = null; long ms = System.currentTimeMillis(), delay = 0; SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; // needs to be set to true int maxToReturn = codes.size(); ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, propertyNames, propertyTypes, resolveObjects, maxToReturn); // _logger.debug("resolveToList done"); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() > 0) { for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); } else { // _logger.debug(c.getEntityDescription().getContent()); Property[] properties = c.getProperty(); String values = ""; for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; values = values + prop.getValue().getContent(); if (j < properties.length - 1) { values = values + "; "; } } hmap.put(rcr.getCode(), values); } } } return hmap; } catch (Exception e) { _logger.error("Method: SearchUtil.searchByProperties"); _logger.error("* ERROR: cns.resolve throws exceptions."); _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector getConceptSources(String scheme, String version, String code) { Entity c = getConceptByCode(scheme, version, null, code); if (c == null) return null; Presentation[] presentations = c.getPresentation(); HashSet hset = new HashSet(); Vector v = new Vector(); for (int i = 0; i < presentations.length; i++) { Presentation presentation = presentations[i]; // java.lang.String name = presentation.getPropertyName(); // java.lang.String prop_value = // presentation.getValue().getContent(); Source[] sources = presentation.getSource(); for (int j = 0; j < sources.length; j++) { Source source = (Source) sources[j]; java.lang.String sab = source.getContent(); if (!hset.contains(sab)) { hset.add(sab); v.add(sab); } } } hset.clear(); return v; } public static String getMetadataValue(String scheme, String propertyName){ Vector v; try { v = getMetadataValues(scheme, propertyName); } catch (Exception e) { _logger.error(e.getMessage()); return null; } if (v == null || v.size() == 0) return null; return (String) v.elementAt(0); } public static Vector getMetadataValues(String scheme, String propertyName) { Vector v = new Vector(); /* * if (formalName2MetadataHashMap == null) { * //formalName2MetadataHashMap = getFormalName2MetadataHashMap(); * MetadataUtils.setSAB2FormalNameHashMap(); } */ if (_formalName2MetadataHashMap == null) { _formalName2MetadataHashMap = MetadataUtils.getFormalName2MetadataHashMap(); } Vector metadataProperties = (Vector) _formalName2MetadataHashMap.get(scheme); if (metadataProperties != null) { for (int i = 0; i < metadataProperties.size(); i++) { String t = (String) metadataProperties.elementAt(i); Vector w = parseData(t, "|"); String t1 = (String) w.elementAt(0); String t2 = (String) w.elementAt(1); if (t1.compareTo(propertyName) == 0) v.add(t2); } } return v; } public static boolean checkIsLicensed(String sab) { if (sab == null) return false; String securd_vocabularies = NCImBrowserProperties.getSecuredVocabularies(); String target = "|" + sab + "|"; if (securd_vocabularies.indexOf(target) == -1) return false; return true; } // /////////////////////////////////////////////// // siblings // ////////////////////////////////////////////// public Vector getSiblings(String code) { // return getSiblings("NCI Metathesaurus", null, code); return getSiblingsExt(code); } public Vector getSiblings(String scheme, String version, String code) { LexBIGService lbSvc = null; LexBIGServiceConvenienceMethods lbscm = null; Vector sibling_vec = new Vector(); try { lbSvc = RemoteServerUtil.createLexBIGService(); lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { return sibling_vec; } HashSet hset = new HashSet(); String[] assocNames = new String[] { "PAR" }; // find parents Vector v = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames); for (int i = 0; i < v.size(); i++) { String t = (String) v.elementAt(i); Vector w = parseData(t); String rel = (String) w.elementAt(0); String rela = (String) w.elementAt(1); String parent_name = (String) w.elementAt(2); String parent_code = (String) w.elementAt(3); Vector u = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, parent_code, assocNames, false); for (int j = 0; j < u.size(); j++) { String t2 = (String) u.elementAt(j); Vector w2 = parseData(t2); String sib_rel = (String) w2.elementAt(0); String sib_rela = (String) w2.elementAt(1); String sib_name = (String) w2.elementAt(2); String sib_code = (String) w2.elementAt(3); String sib_sab = (String) w2.elementAt(4); if (!hset.contains(t2) && sib_code.compareTo(code) != 0) { sibling_vec.add("SIB" + "|" + sib_name + "|" + sib_code + "|" + sib_sab); } } } return sibling_vec; } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames) { return getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames, true); } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList(assocNames, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = -1;// NCImBrowserProperties.maxToReturn; boolean navigationForward = !direction; boolean navigationBackward = direction; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), navigationForward, navigationBackward, 1, 1, new LocalNameList(), null, null, maxToReturn); String qualifier_name = null; String qualifier_value = null; if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); if (!direction) targetof = ref.getSourceOf(); if (targetof != null) { Association[] associations = targetof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { String associationName = lbscm .getAssociationNameFromAssociationCode( scheme, csvt, assoc .getAssociationName()); if (associationName .compareToIgnoreCase("equivalentClass") != 0) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = "NA"; String asso_source = "NA"; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("source") == 0) { asso_source = qualifier_value; // replace // associationName // by // Rela // value break; } } } v.add(associationName + "|" + asso_label + "|" + ac.getReferencedEntry() .getEntityDescription() .getContent() + "|" + ac.getReferencedEntry() .getEntityCode() + "|" + asso_source); } } } } } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; } public static HashMap getPropertyValueHashMap(String code) { return getPropertyValueHashMap(Constants.CODING_SCHEME_NAME, null, code); } private static String getSourceQualifierValue(Property p) { if (p == null) return null; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareToIgnoreCase("source") == 0) { return qualifier_value; } } } return null; } private static String getPropertySource(Property p) { if (p == null) return null; Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; return src.getContent(); } return null; } public static HashMap getPropertyValueHashMap(String scheme, String version, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, null, null, resolveObjects, 1); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() == 0) return null; ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(0); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); return null; } return getPropertyValueHashMap(c); } catch (Exception e) { _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static HashMap getPropertyValueHashMap(Entity c) { if (c == null) { return null; } HashMap hmap = new HashMap(); Property[] properties = c.getProperty(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getPresentation(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getDefinition(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getComment(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } return hmap; } public List<RelationshipTabResults> getAssociatedConceptsEx(String CUI, String associationName, Direction direction) { List<String> assoc_list = new ArrayList(); assoc_list.add(associationName); LexBIGService lbs = RemoteServerUtil.createLexBIGService(); CodingScheme cs = null; List results = new ArrayList<RelationshipTabResults>(); try { cs = getCodingScheme("NCI Metathesaurus", null); MetaBrowserService mbs = null; try { mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); Map<String, List<RelationshipTabResults>> map = null; try { map = mbs.getRelationshipsDisplay(CUI, assoc_list, direction); } catch (Exception ex) { ex.printStackTrace(); return null; } for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); for (RelationshipTabResults result : relations) { results.add(result); } } return results; } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception ex) { } return null; } public Vector getSiblingsExt(String CUI) { Vector v = new Vector(); HashSet hset = new HashSet(); List results = getAssociatedConceptsEx(CUI, "PAR", Direction.TARGETOF); if (results == null) return null; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); for (int i = 0; i < results.size(); i++) { RelationshipTabResults result = (RelationshipTabResults) results.get(i); List children = getAssociatedConceptsEx(result.getCui(), "CHD", Direction.TARGETOF); for (int j = 0; j < children.size(); j++) { RelationshipTabResults sub_result = (RelationshipTabResults) children.get(j); String t = "SIB" + "|" + sub_result.getName() + "|" + sub_result.getCui() + "|" + sub_result.getSource(); if (!hset.contains(t) && sub_result.getCui().compareTo(CUI) != 0) { hset.add(t); // v.add(t); String key = sub_result.getSource() + "|" + sub_result.getName() + "|" + sub_result.getCui(); hmap.put(key, t); key_vec.add(key); } } } key_vec = SortUtils.quickSort(key_vec); for (int i = 0; i < key_vec.size(); i++) { String key = (String) key_vec.elementAt(i); String value = (String) hmap.get(key); v.add(value); } // return SortUtils.quickSort(v); return v; } public static String getAssociationReverseName(String assoName) { String assocLabel = assoName; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); assocLabel = lbscm .getAssociationReverseName(assoName, "NCI Metathesaurus", null); } catch (Exception ex) { ex.printStackTrace(); } return assocLabel; } }
public Vector getSuperconceptCodes(String scheme, String version, String code) { // throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm .createCodeNodeSet(new String[] { code }, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0).getEntityDescription() .getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { _logger .debug("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; String version = null; int knt = 0; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { version = css.getRepresentsVersion(); knt++; if (ltag == null) return version; RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); // KLO, 102409 if (tags == null) return version; if (tags != null && tags.length > 0) { for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return version; } } } } } } catch (Exception e) { // e.printStackTrace(); } if (ltag != null && ltag.compareToIgnoreCase("PRODUCTION") == 0 & knt == 1) { _logger.debug("\tUse " + version + " as default."); return version; } return null; } public static Vector<String> getVersionListData(String codingSchemeName) { Vector<String> v = new Vector(); try { // RemoteServerUtil rsu = new RemoteServerUtil(); // EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if (csrl == null) _logger.warn("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i = 0; i < csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals( CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); if (formalname.compareTo(codingSchemeName) == 0) { String representsVersion = css.getRepresentsVersion(); v.add(representsVersion); } } } } catch (Exception ex) { } return v; } public static String getFileName(String pathname) { File file = new File(pathname); String filename = file.getName(); return filename; } protected static Association processForAnonomousNodes(Association assoc) { // clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for (int i = 0; i < assoc.getAssociatedConcepts() .getAssociatedConceptCount(); i++) { // Conditionals to deal with anonymous nodes and UMLS top nodes // "V-X" // The first three allow UMLS traversal to top node. // The last two are specific to owl anonymous nodes which can act // like false // top nodes. if (assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@@")) { // do nothing } else { temp.getAssociatedConcepts().addAssociatedConcept( assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } public static LocalNameList vector2LocalNameList(Vector<String> v) { if (v == null) return null; LocalNameList list = new LocalNameList(); for (int i = 0; i < v.size(); i++) { String vEntry = (String) v.elementAt(i); list.addEntry(vEntry); } return list; } protected static NameAndValueList createNameAndValueList(Vector names, Vector values) { if (names == null) return null; NameAndValueList nvList = new NameAndValueList(); for (int i = 0; i < names.size(); i++) { String name = (String) names.elementAt(i); String value = (String) values.elementAt(i); NameAndValue nv = new NameAndValue(); nv.setName(name); if (value != null) { nv.setContent(value); } nvList.addNameAndValue(nv); } return nvList; } protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { ex.printStackTrace(); } return cs; } public static Vector<SupportedProperty> getSupportedProperties( CodingScheme cs) { if (cs == null) return null; Vector<SupportedProperty> v = new Vector<SupportedProperty>(); SupportedProperty[] properties = cs.getMappings().getSupportedProperty(); for (int i = 0; i < properties.length; i++) { SupportedProperty sp = (SupportedProperty) properties[i]; v.add(sp); } return v; } public static Vector<String> getSupportedPropertyNames(CodingScheme cs) { Vector w = getSupportedProperties(cs); if (w == null) return null; Vector<String> v = new Vector<String>(); for (int i = 0; i < w.size(); i++) { SupportedProperty sp = (SupportedProperty) w.elementAt(i); v.add(sp.getLocalId()); } return v; } public static Vector<String> getSupportedPropertyNames(String codingScheme, String version) { CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { CodingScheme cs = getCodingScheme(codingScheme, versionOrTag); return getSupportedPropertyNames(cs); } catch (Exception ex) { } return null; } public static Vector getPropertyNamesByType(Entity concept, String property_type) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } if (properties == null || properties.length == 0) return v; HashSet hset = new HashSet(); for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; String nm = p.getPropertyName(); if (!hset.contains(nm)) { hset.add(nm); v.add(p.getPropertyName()); } } hset.clear(); return v; } public static Vector getPropertyValues(Entity concept, String property_type, String property_name) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } /* * else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0) { * properties = concept.getInstruction(); } */ else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } else { _logger .warn("WARNING: property_type not found -- " + property_type); } if (properties == null || properties.length == 0) return v; for (int i = 0; i < properties.length; i++) { Property p = (Property) properties[i]; if (property_name.compareTo(p.getPropertyName()) == 0) { String t = p.getValue().getContent(); Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; t = t + "|" + src.getContent(); } else { if (property_name.compareToIgnoreCase("definition") == 0) { _logger.warn("*** WARNING: " + property_name + " with no source data: " + p.getValue().getContent()); PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); // _logger.debug("\t*** qualifier_name: " + // qualifier_name); // _logger.debug("\t*** qualifier_value: " // + qualifier_value); if (qualifier_name.compareTo("source") == 0) { t = t + "|" + qualifier_value; // _logger.debug("*** SOURCE: " + // qualifier_value); break; } } } else { _logger .warn("*** SOURCE NOT FOUND IN qualifiers neither. "); } } } v.add(t); } } return v; } // ===================================================================================== public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); List list = new ArrayList(); try { CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); Relations[] relations = cs.getRelations(); for (int i = 0; i < relations.length; i++) { Relations relation = relations[i]; if (relation.getContainerName().compareToIgnoreCase("roles") == 0) { AssociationPredicate[] asso_array = relation.getAssociationPredicate(); for (int j = 0; j < asso_array.length; j++) { AssociationPredicate association = (AssociationPredicate) asso_array[j]; list.add(association.getAssociationName()); } } } } catch (Exception ex) { } return list; } public static void sortArray(ArrayList list) { String tmp; if (list.size() <= 1) return; for (int i = 0; i < list.size(); i++) { String s1 = (String) list.get(i); for (int j = i + 1; j < list.size(); j++) { String s2 = (String) list.get(j); if (s1.compareToIgnoreCase(s2) > 0) { tmp = s1; list.set(i, s2); list.set(j, tmp); } } } } public static void sortArray(String[] strArray) { String tmp; if (strArray.length <= 1) return; for (int i = 0; i < strArray.length; i++) { for (int j = i + 1; j < strArray.length; j++) { if (strArray[i].compareToIgnoreCase(strArray[j]) > 0) { tmp = strArray[i]; strArray[i] = strArray[j]; strArray[j] = tmp; } } } } public String[] getSortedKeys(HashMap map) { if (map == null) return null; Set keyset = map.keySet(); String[] names = new String[keyset.size()]; Iterator it = keyset.iterator(); int i = 0; while (it.hasNext()) { String s = (String) it.next(); names[i] = s; i++; } sortArray(names); return names; } public String getPreferredName(Entity c) { Presentation[] presentations = c.getPresentation(); for (int i = 0; i < presentations.length; i++) { Presentation p = presentations[i]; if (p.getPropertyName().compareTo("Preferred_Name") == 0) { return p.getValue().getContent(); } } return null; } public HashMap getRelationshipHashMap(String scheme, String version, String code) { return getRelationshipHashMap(scheme, version, code, null); } protected static String getDirectionalLabel( LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, boolean navigatedFwd) throws LBException { String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(assoc .getAssociationName(), scheme, csvt) : lbscm .getAssociationReverseName(assoc.getAssociationName(), scheme, csvt); if (StringUtils.isBlank(assocLabel)) assocLabel = (navigatedFwd ? "" : "[Inverse]") + assoc.getAssociationName(); return assocLabel; } public LexBIGServiceConvenienceMethods createLexBIGServiceConvenienceMethods( LexBIGService lbSvc) { LexBIGServiceConvenienceMethods lbscm = null; try { lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { ex.printStackTrace(); } return lbscm; } public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab) { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); // Perform the query ... ResolvedConceptReferenceList matches = null; List list = new ArrayList();// getSupportedRoleNames(lbSvc, scheme, // version); ArrayList roleList = new ArrayList(); ArrayList associationList = new ArrayList(); ArrayList superconceptList = new ArrayList(); ArrayList siblingList = new ArrayList(); ArrayList subconceptList = new ArrayList(); ArrayList btList = new ArrayList(); ArrayList ntList = new ArrayList(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); HashMap map = new HashMap(); try { // LexBIGServiceConvenienceMethods lbscm = // createLexBIGServiceConvenienceMethods(lbSvc); /* * LexBIGServiceConvenienceMethods lbscm = * (LexBIGServiceConvenienceMethods) lbSvc * .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); */ CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); if (sab != null) { cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); } int maxToReturn = NCImBrowserProperties._maxToReturn; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), true, false, 1, 1, _noopList, null, null, null, maxToReturn, false); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); Association[] associations = sourceof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = assoc.getAssociationName(); // String associationName = // lbscm.getAssociationNameFromAssociationCode(scheme, // csvt, assoc.getAssociationName()); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; EntityDescription ed = ac.getEntityDescription(); String name = "No Description"; if (ed != null) name = ed.getContent(); String pt = name; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { String s = associationName + "|" + pt + "|" + ac.getConceptCode(); if (!parent_asso_vec.contains(associationName) && !child_asso_vec .contains(associationName)) { if (sibling_asso_vec .contains(associationName)) { siblingList.add(s); } else if (bt_vec.contains(associationName)) { btList.add(s); } else if (nt_vec.contains(associationName)) { ntList.add(s); } else { associationList.add(s); } } } } } } } if (roleList.size() > 0) { SortUtils.quickSort(roleList); } if (associationList.size() > 0) { // KLO, 052909 associationList = removeRedundantRelationships(associationList, "RO"); SortUtils.quickSort(associationList); } if (siblingList.size() > 0) { SortUtils.quickSort(siblingList); } if (btList.size() > 0) { SortUtils.quickSort(btList); } if (ntList.size() > 0) { SortUtils.quickSort(ntList); } map.put(TYPE_ROLE, roleList); map.put(TYPE_ASSOCIATION, associationList); map.put(TYPE_SIBLINGCONCEPT, siblingList); map.put(TYPE_BROADERCONCEPT, btList); map.put(TYPE_NARROWERCONCEPT, ntList); Vector superconcept_vec = getSuperconcepts(scheme, version, code); for (int i = 0; i < superconcept_vec.size(); i++) { Entity c = (Entity) superconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); superconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(superconceptList); map.put(TYPE_SUPERCONCEPT, superconceptList); Vector subconcept_vec = getSubconcepts(scheme, version, code); for (int i = 0; i < subconcept_vec.size(); i++) { Entity c = (Entity) subconcept_vec.elementAt(i); // String pt = getPreferredName(c); String pt = c.getEntityDescription().getContent(); subconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(subconceptList); map.put(TYPE_SUBCONCEPT, subconceptList); } catch (Exception ex) { ex.printStackTrace(); } return map; } public Vector getSuperconcepts(String scheme, String version, String code) { return getAssociationSources(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public Vector getSubconcepts(String scheme, String version, String code) { return getAssociationTargets(scheme, version, code, _hierAssocToChildNodes); } public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { // EVSApplicationService lbSvc = new // RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = false; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator( CodedNodeGraph cng, ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn) { CodedNodeSet cns = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator toNodeList "); cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); if (cns == null) { _logger.warn("cng.toNodeList returns null???"); return null; } SortOptionList sortCriteria = null; // Constructors.createSortOptionList(new String[]{"matchToQuery", // "code"}); LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; ResolvedConceptReferencesIterator iterator = null; try { System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve "); iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes); System.out.println("codedNodeGraph2CodedNodeSetIterator cns.resolve DONE "); } catch (Exception e) { e.printStackTrace(); } if (iterator == null) { _logger.warn("cns.resolve returns null???"); } return iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn) { return resolveIterator(iterator, maxToReturn, null); } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code) { Vector v = new Vector(); if (iterator == null) { _logger.debug("No match."); return v; } try { int iteration = 0; while (iterator.hasNext()) { iteration++; iterator = iterator.scroll(maxToReturn); ResolvedConceptReferenceList rcrl = iterator.getNext(); ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference(); for (int i = 0; i < rcra.length; i++) { ResolvedConceptReference rcr = rcra[i]; org.LexGrid.concepts.Entity ce = rcr.getReferencedEntry(); if (code == null) { v.add(ce); } else { if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } } } catch (Exception e) { e.printStackTrace(); } return v; } public static Vector<String> parseData(String line) { return parseData(line, "|"); } public static Vector<String> parseData(String line, String tab) { Vector data_vec = new Vector(); StringTokenizer st = new StringTokenizer(line, tab); while (st.hasMoreTokens()) { String value = st.nextToken(); if (value.compareTo("null") == 0) value = " "; data_vec.add(value); } return data_vec; } public static String getHyperlink(String url, String codingScheme, String code) { codingScheme = codingScheme.replace(" ", "%20"); String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code; return link; } public List getHierarchyRoots(String scheme, String version, String hierarchyID) throws LBException { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); return getHierarchyRoots(scheme, csvt, hierarchyID); } public List getHierarchyRoots(String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); List list = ResolvedConceptReferenceList2List(roots); SortUtils.quickSort(list); return list; } public List ResolvedConceptReferenceList2List( ResolvedConceptReferenceList rcrl) { ArrayList list = new ArrayList(); for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); list.add(rcr); } return list; } public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, sab); } public static Vector getSynonyms(String scheme, String version, String tag, String code) { Entity concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept) { return getSynonyms(concept, null); } public static Vector getSynonyms(Entity concept, String sab) { if (concept == null) return null; Vector v = new Vector(); Presentation[] properties = concept.getPresentation(); int n = 0; for (int i = 0; i < properties.length; i++) { Presentation p = properties[i]; // name String term_name = p.getValue().getContent(); String term_type = "null"; String term_source = "null"; String term_source_code = "null"; // source-code PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source-code") == 0) { term_source_code = qualifier_value; break; } } } // term type term_type = p.getRepresentationalForm(); // source Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; term_source = src.getContent(); } String t = null; if (sab == null) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } else if (term_source != null && sab.compareTo(term_source) == 0) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } } SortUtils.quickSort(v); return v; } public String getNCICBContactURL() { if (_ncicbContactURL != null) { return _ncicbContactURL; } String default_url = "[email protected]"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncicbContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL); if (_ncicbContactURL == null) { _ncicbContactURL = default_url; } } catch (Exception ex) { } _logger.debug("getNCICBContactURL returns " + _ncicbContactURL); return _ncicbContactURL; } public String getTerminologySubsetDownloadURL() { NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _terminologySubsetDownloadURL = properties .getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } catch (Exception ex) { } return _terminologySubsetDownloadURL; } public String getNCIMBuildInfo() { if (_ncimBuildInfo != null) { return _ncimBuildInfo; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO); if (_ncimBuildInfo == null) { _ncimBuildInfo = default_info; } } catch (Exception ex) { } _logger.debug("getNCIMBuildInfo returns " + _ncimBuildInfo); return _ncimBuildInfo; } public String getApplicationVersion() { if (_ncimAppVersion != null) { return _ncimAppVersion; } String default_info = "1.0"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncimAppVersion = properties.getProperty(NCImBrowserProperties.NCIM_APP_VERSION); if (_ncimAppVersion == null) { _ncimAppVersion = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncimAppVersion; } public String getNCITAppBuildTag() { if (_ncitAnthillBuildTagBuilt != null) { return _ncitAnthillBuildTagBuilt; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitAnthillBuildTagBuilt = properties .getProperty(NCImBrowserProperties.APP_BUILD_TAG); if (_ncitAnthillBuildTagBuilt == null) { _ncitAnthillBuildTagBuilt = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _ncitAnthillBuildTagBuilt; } public String getEVSServiceURL() { if (_evsServiceURL != null) { return _evsServiceURL; } String default_info = "Local LexEVS"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _evsServiceURL = properties.getProperty(NCImBrowserProperties.EVS_SERVICE_URL); if (_evsServiceURL == null) { _evsServiceURL = default_info; } } catch (Exception ex) { ex.printStackTrace(); } return _evsServiceURL; } public String getNCItURL() { if (_ncitURL != null) { return _ncitURL; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); _ncitURL = properties.getProperty(NCImBrowserProperties.NCIT_URL); if (_ncitURL == null) { _ncitURL = default_info; } } catch (Exception ex) { } return _ncitURL; } public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) { Vector<String> v = new Vector<String>(); v.add("String"); v.add("Code"); v.add("CUI"); return v; } public static Vector getSources(String scheme, String version, String tag, String code) { Vector sources = getSynonyms(scheme, version, tag, code); // GLIOBLASTOMA MULTIFORME|DI|DXP|U000721 HashSet hset = new HashSet(); Vector source_vec = new Vector(); for (int i = 0; i < sources.size(); i++) { String s = (String) sources.elementAt(i); Vector ret_vec = DataUtils.parseData(s, "|"); String name = (String) ret_vec.elementAt(0); String type = (String) ret_vec.elementAt(1); String src = (String) ret_vec.elementAt(2); String srccode = (String) ret_vec.elementAt(3); if (!hset.contains(src)) { hset.add(src); source_vec.add(src); } } SortUtils.quickSort(source_vec); return source_vec; } public static boolean containSource(Vector sources, String source) { if (sources == null || sources.size() == 0) return false; String s = null; for (int i = 0; i < sources.size(); i++) { s = (String) sources.elementAt(i); if (s.compareTo(source) == 0) return true; } return false; } public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); // NameAndValueList nameAndValueList = // ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(null, Constructors .createNameAndValueList(sab, SOURCE)); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } SortUtils.quickSort(v); return v; } protected boolean isValidForSAB(AssociatedConcept ac, String sab) { for (NameAndValue qualifier : ac.getAssociationQualifiers() .getNameAndValue()) if (SOURCE.equalsIgnoreCase(qualifier.getContent()) && sab.equalsIgnoreCase(qualifier.getName())) return true; return false; } public Vector sortSynonyms(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String key = term_name + delim + term_source + delim + term_source_code + delim + term_type; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getAssociatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, false, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } hmap.put(associationName, v); } } } } } cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), Constructors.createNameAndValueList("source", source)); } else { cng = cng .restrictToAssociations( Constructors .createNameAndValueList(MetaTreeUtils._hierAssocToChildNodes), null); } matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), false, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } if (associationName.compareTo("CHD") == 0) { associationName = "PAR"; } hmap.put(associationName, v); } } } } } } catch (Exception ex) { } return hmap; } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getRelatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { Debug.println("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations(Constructors .createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches != null) { java.lang.Boolean incomplete = matches.getIncomplete(); // _logger.debug("(*) Number of matches: " + // matches.getResolvedConceptReferenceCount()); // _logger.debug("(*) Incomplete? " + incomplete); hmap.put(INCOMPLETE, incomplete.toString()); } if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; String directionalLabel = associationName; boolean navigatedFwd = true; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); } catch (Exception e) { Debug .println("(*) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm .getAssociationNameFromAssociationCode( codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) { String directionalLabel = associationName; boolean navigatedFwd = false; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); // Debug.println("(**) directionalLabel: associationName " // + associationName + // " directionalLabel: " + // directionalLabel); } catch (Exception e) { Debug .println("(**) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { // associationName = // qualifier_value; // // replace associationName // by Rela value asso_label = qualifier_value; break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } } } } } catch (Exception ex) { } return hmap; } private String findRepresentativeTerm(Entity c, String sab) { Vector synonyms = getSynonyms(c, sab); if (synonyms == null || synonyms.size() == 0) { // return null; // t = term_name + "|" + term_type + "|" + term_source + "|" + // term_source_code; return c.getEntityDescription().getContent() + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + Constants.EXTERNAL_TERM_SOURCE + "|" + Constants.EXTERNAL_TERM_SOURCE_CODE; } return NCImBrowserProperties.getHighestTermGroupRank(synonyms); } String getAssociationDirectionalName(LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String associationName, boolean navigatedFwd) { String assocLabel = null; try { assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(associationName, scheme, csvt) : lbscm.getAssociationReverseName( associationName, scheme, csvt); } catch (Exception ex) { } return assocLabel; } // Method for populating By Source tab relationships table public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay = 0; String action = "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; ms_all = System.currentTimeMillis(); while (it.hasNext()) { ms_categorization = System.currentTimeMillis(); String rel_rela = (String) it.next(); // _logger.debug("rel_rela: " + rel_rela); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; /* * if (parent_asso_vec.contains(rel)) category = "Child"; else * if (child_asso_vec.contains(rel)) category = "Parent"; else * if (bt_vec.contains(rel)) category = "Narrower"; else if * (nt_vec.contains(rel)) category = "Broader"; */ else if (sibling_asso_vec.contains(rel)) category = "Sibling"; ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization); Object obj = hmap.get(rel_rela); if (obj != null) { Vector v = (Vector) obj; // For each related concept: for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); Entity c = ac.getReferencedEntry(); if (!hset.contains(c.getEntityCode())) { hset.add(c.getEntityCode()); // Find the highest ranked atom data ms_find_highest_rank_atom = System.currentTimeMillis(); String t = findRepresentativeTerm(c, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); t = t + "|" + c.getEntityCode() + "|" + rela + "|" + category; // _logger.debug(t); w.add(t); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && category.compareTo("RO") != 0) { if (rel_hset.contains(c.getEntityCode())) { rel_hset.add(c.getEntityCode()); } } if (category.compareTo("Child") == 0 && category.compareTo("CHD") != 0) { if (hasSubtype_hset.contains(c.getEntityCode())) { hasSubtype_hset.add(c.getEntityCode()); } } } } } } } Vector u = new Vector(); // Remove redundant RO relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("RO") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } // Remove redundant CHD relationships for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >= 5) { String associationName = v.elementAt(5); if (associationName.compareTo("CHD") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } ms_all_delay = System.currentTimeMillis() - ms_all; action = "categorizing relationships into six categories"; Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay); DBG.debugDetails(ms_categorization_delay, action, "getNeighborhoodSynonyms"); action = "finding highest ranked atoms"; Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay; action = "removing redundant RO relationships"; Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay); DBG.debugDetails(ms_remove_RO_delay, action, "getNeighborhoodSynonyms"); // Initial sort (refer to sortSynonymData method for sorting by a // specific column) long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); DBG.debugDetails("Max Return", NCImBrowserProperties._maxToReturn); return u; } public static String getRelationshipCode(String id) { if (id.compareTo("Parent") == 0) return "1"; else if (id.compareTo("Child") == 0) return "2"; else if (id.compareTo("Broader") == 0) return "3"; else if (id.compareTo("Narrower") == 0) return "4"; else if (id.compareTo("Sibling") == 0) return "5"; else return "6"; } public static boolean containsAllUpperCaseChars(String s) { for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch < 65 || ch > 90) return false; } return true; } public static Vector sortSynonymData(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String rel_type = (String) synonym_data.elementAt(6); String rel_type_str = getRelationshipCode(rel_type); String key = term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel") == 0) { String rel_key = rel; if (containsAllUpperCaseChars(rel)) rel_key = "|"; key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui + delim + rel_type_str; } if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } // KLO, 052909 private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) { ArrayList a = new ArrayList(); HashSet target_set = new HashSet(); for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { String associationTargetCode = w.elementAt(2); target_set.add(associationTargetCode); } } for (int i = 0; i < associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { a.add(s); } else { String associationTargetCode = w.elementAt(2); if (!target_set.contains(associationTargetCode)) { a.add(s); } } } return a; } public static Vector sortRelationshipData(Vector relationships, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n = 0; n < relationships.size(); n++) { String s = (String) relationships.elementAt(n); Vector ret_vec = DataUtils.parseData(s, "|"); String relationship_name = (String) ret_vec.elementAt(0); String target_concept_name = (String) ret_vec.elementAt(1); String target_concept_code = (String) ret_vec.elementAt(2); String rel_sab = (String) ret_vec.elementAt(3); String key = target_concept_name + delim + relationship_name + delim + target_concept_code + delim + rel_sab; if (sortBy.compareTo("source") == 0) { key = rel_sab + delim + target_concept_name + delim + relationship_name + delim + target_concept_code; } else if (sortBy.compareTo("rela") == 0) { key = relationship_name + delim + target_concept_name + delim + target_concept_code + delim + rel_sab; } else if (sortBy.compareTo("code") == 0) { key = target_concept_code + delim + target_concept_name + delim + relationship_name + delim + rel_sab; } hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i = 0; i < key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public void removeRedundantRecords(HashMap hmap) { Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); while (it.hasNext()) { String rel = (String) it.next(); Vector v = (Vector) hmap.get(rel); HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } hmap.put(rel, u); } } public Vector removeRedundantRecords(Vector v) { HashSet hset = new HashSet(); Vector u = new Vector(); for (int k = 0; k < v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } return u; } /* * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code, Vector sort_option) { * * Debug.println("(*) DataUtils getAssociationTargetHashMap "); Vector * parent_asso_vec = new Vector(Arrays .asList(hierAssocToParentNodes_)); * Vector child_asso_vec = new Vector(Arrays * .asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new * Vector(Arrays .asList(assocToSiblingNodes_)); Vector bt_vec = new * Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new * Vector(Arrays.asList(assocToNTNodes_)); Vector category_vec = new * Vector(Arrays.asList(relationshipCategories_)); * * HashMap rel_hmap = new HashMap(); for (int k = 0; k < * category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); Vector vec = new Vector(); * rel_hmap.put(category, vec); } * * Vector w = new Vector(); HashSet hset = new HashSet(); * * long ms = System.currentTimeMillis(), delay = 0; String action = * "Retrieving all relationships from the server"; HashMap hmap = * getRelatedConceptsHashMap(scheme, version, code, null, 0); // * resolveCodedEntryDepth // = // 0; delay = System.currentTimeMillis() - * ms; Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); * * // Categorize relationships into six categories and find association // * source data ms = System.currentTimeMillis(); action = * "Categorizing relationships into six categories; finding source data for each relationship" * ; while (it.hasNext()) { String rel_rela = (String) it.next(); if * (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = * DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); * String rela = (String) u.elementAt(1); * * String category = "Other"; if (parent_asso_vec.contains(rel)) category = * "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else * if (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; else if * (sibling_asso_vec.contains(rel)) category = "Sibling"; Vector v = * (Vector) hmap.get(rel_rela); * * for (int i = 0; i < v.size(); i++) { AssociatedConcept ac = * (AssociatedConcept) v.elementAt(i); EntityDescription ed = * ac.getEntityDescription(); String source = "unspecified"; * * for (NameAndValue qualifier : ac.getAssociationQualifiers() * .getNameAndValue()) { if (SOURCE.equalsIgnoreCase(qualifier.getName())) { * source = qualifier.getContent(); w = (Vector) rel_hmap.get(category); if * (w == null) { w = new Vector(); } String str = rela + "|" + * ac.getEntityDescription().getContent() + "|" + ac.getCode() + "|" + * source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } * } } } } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * // Remove redundant RO relationships ms = System.currentTimeMillis(); * action = "Removing redundant RO and CHD relationships"; * * HashSet other_hset = new HashSet(); Vector w2 = (Vector) * rel_hmap.get("Other"); for (int k = 0; k < w2.size(); k++) { String s = * (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); Vector * ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } Vector w3 = new Vector(); for (int k = 0; k < * w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = * DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); * String name = (String) ret_vec.elementAt(1); String target_code = * (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { * // RO String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); * * other_hset = new HashSet(); w2 = (Vector) rel_hmap.get("Child"); for (int * k = 0; k < w2.size(); k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if * (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { * other_hset.add(t); } } w3 = new Vector(); for (int k = 0; k < w2.size(); * k++) { String s = (String) w2.elementAt(k); * * // _logger.debug("(*) getAssociationTargetHashMap s " + s); * * Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) * ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String * target_code = (String) ret_vec.elementAt(2); String src = (String) * ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else * { String t = name + "|" + target_code + "|" + src; if * (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); * delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * ms = System.currentTimeMillis(); action = * "Sorting relationships by sort options (columns)"; * * // Sort relationships by sort options (columns) if (sort_option == null) * { for (int k = 0; k < category_vec.size(); k++) { String category = * (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); * SortUtils.quickSort(w); rel_hmap.put(category, w); } } else { for (int k * = 0; k < category_vec.size(); k++) { String category = (String) * category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); String * sortOption = (String) sort_option.elementAt(k); // * SortUtils.quickSort(w); w = sortRelationshipData(w, sortOption); * rel_hmap.put(category, w); } } delay = System.currentTimeMillis() - ms; * Debug.println("Run time (ms) for " + action + " " + delay); * DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); * * removeRedundantRecords(rel_hmap); String incomplete = (String) * hmap.get(INCOMPLETE); if (incomplete != null) rel_hmap.put(INCOMPLETE, * incomplete); return rel_hmap; } * * public HashMap getAssociationTargetHashMap(String scheme, String version, * String code) { return getAssociationTargetHashMap(scheme, version, code, * null); } */ public Vector hashSet2Vector(HashSet hset) { if (hset == null) return null; Vector v = new Vector(); Iterator it = hset.iterator(); while (it.hasNext()) { String t = (String) it.next(); v.add(t); } return v; } // For relationships tab public HashMap getAssociationTargetHashMap(String CUI, Vector sort_option) { Debug.println("(*) DataUtils getAssociationTargetHashMap "); long ms, delay = 0; String action = null; ms = System.currentTimeMillis(); action = "Initializing member variables"; List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector category_vec = new Vector(Arrays.asList(_relationshipCategories)); HashMap rel_hmap = new HashMap(); for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); HashSet hset = new HashSet(); rel_hmap.put(category, hset); } HashSet w = new HashSet(); Map<String, List<RelationshipTabResults>> map = null; Map<String, List<RelationshipTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); try { _logger.info("************** metabrowser-extension *****************"); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); if (mbs == null) { _logger.error("Error! metabrowser-extension is null!"); return null; } ms = System.currentTimeMillis(); action = "Retrieving " + SOURCE_OF; ms = System.currentTimeMillis(); _logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); _logger.info("CUI: " + CUI); _logger.info("Direction: " + Direction.SOURCEOF); map = mbs.getRelationshipsDisplay(CUI, null, Direction.SOURCEOF); _logger.info("Done !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! getRelationshipsDisplay !!!!"); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Retrieving " + TARGET_OF; ms = System.currentTimeMillis(); map2 = mbs.getRelationshipsDisplay(CUI, par_chd_assoc_list, Direction.TARGETOF); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); } catch (Exception ex) { ex.printStackTrace(); return null; } // Categorize relationships into six categories and find association // source data ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } for (String rel : map2.keySet()) { List<RelationshipTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (RelationshipTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (HashSet) rel_hmap.get(category); if (w == null) { w = new HashSet(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // Remove redundant RO relationships ms = System.currentTimeMillis(); action = "Removing redundant RO and CHD relationships"; HashSet other_hset = new HashSet(); HashSet w2 = (HashSet) rel_hmap.get("Other"); Iterator it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } HashSet w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Other"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { // RO String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); other_hset = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } w3 = new HashSet(); w2 = (HashSet) rel_hmap.get("Child"); it = w2.iterator(); while (it.hasNext()) { String s = (String) it.next(); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Sorting relationships by sort options (columns)"; HashMap new_rel_hmap = new HashMap(); // Sort relationships by sort options (columns) if (sort_option == null) { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); SortUtils.quickSort(rel_v); new_rel_hmap.put(category, rel_v); } } else { for (int k = 0; k < category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (HashSet) rel_hmap.get(category); Vector rel_v = hashSet2Vector(w); String sortOption = (String) sort_option.elementAt(k); rel_v = sortRelationshipData(rel_v, sortOption); new_rel_hmap.put(category, rel_v); } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // KLO, testing Vector sibling_vector = getSiblings(CUI); if (sort_option != null) { sibling_vector = sortRelationshipData(sibling_vector, (String) sort_option.elementAt(4)); } //new_rel_hmap.put("Sibling", getSiblings(CUI)); new_rel_hmap.put("Sibling", sibling_vector); removeRedundantRecords(new_rel_hmap); String incomplete = (String) new_rel_hmap.get(INCOMPLETE); if (incomplete != null) { new_rel_hmap.put(INCOMPLETE, incomplete); } return new_rel_hmap; } public HashMap createCUI2SynonymsHahMap( Map<String, List<BySourceTabResults>> map, Map<String, List<BySourceTabResults>> map2) { HashMap hmap = new HashMap(); for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { for (BySourceTabResults result : relations) { String rela = result.getRela(); String cui = result.getCui(); String source = result.getSource(); String name = result.getTerm(); Vector v = null; if (hmap.containsKey(cui)) { v = (Vector) hmap.get(cui); } else { v = new Vector(); } // check if v.contains result v.add(result); hmap.put(cui, v); } } } return hmap; } public static BySourceTabResults findHighestRankedAtom( Vector<BySourceTabResults> v, String source) { if (v == null) return null; if (v.size() == 0) return null; if (v.size() == 1) return (BySourceTabResults) v.elementAt(0); BySourceTabResults target = null; for (int i = 0; i < v.size(); i++) { BySourceTabResults r = (BySourceTabResults) v.elementAt(i); if (source != null) { if (r.getSource().compareTo(source) == 0) { if (target == null) { target = r; } else { // select the higher ranked one as target String idx_target = NCImBrowserProperties.getRank(target.getType(), target.getSource()); String idx_atom = NCImBrowserProperties.getRank(r.getType(), r .getSource()); if (idx_atom != null && idx_atom.compareTo(idx_target) > 0) { target = r; } } } } else { return r; } } return target; } public Vector getNeighborhoodSynonyms(String CUI, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); // par_chd_assoc_list.add("RN"); Vector ret_vec = new Vector(); Vector parent_asso_vec = new Vector(Arrays.asList(_hierAssocToParentNodes)); Vector child_asso_vec = new Vector(Arrays.asList(_hierAssocToChildNodes)); Vector sibling_asso_vec = new Vector(Arrays.asList(_assocToSiblingNodes)); Vector bt_vec = new Vector(Arrays.asList(_assocToBTNodes)); Vector nt_vec = new Vector(Arrays.asList(_assocToNTNodes)); Vector w = new Vector(); HashSet hset = new HashSet(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; String action_overall = "By source delay (total time)"; ms_all = System.currentTimeMillis(); long ms = System.currentTimeMillis(), delay = 0; String action = null;// "Retrieving distance-one relationships from the server"; // HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, // sab); // HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); Map<String, List<BySourceTabResults>> map = null; Map<String, List<BySourceTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; try { action = "Retrieve data from browser extension"; ms = System.currentTimeMillis(); mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); // String actionTmp = "Getting " + SOURCE_OF; // long msTmp = System.currentTimeMillis(); map = mbs.getBySourceTabDisplay(CUI, sab, null, Direction.SOURCEOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); // actionTmp = "Getting " + TARGET_OF; // msTmp = System.currentTimeMillis(); // to be modified: BT and PAR only??? map2 = mbs.getBySourceTabDisplay(CUI, sab, par_chd_assoc_list, Direction.TARGETOF); // Debug.println("Run time (ms) " + actionTmp + " " + // (System.currentTimeMillis() - msTmp)); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); } catch (Exception ex) { } action = "Sort synonyms by CUI"; ms = System.currentTimeMillis(); Vector u = new Vector(); HashMap cui2SynonymsMap = createCUI2SynonymsHahMap(map, map2); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); HashSet CUI_hashset = new HashSet(); ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; ms_find_highest_rank_atom_delay = 0; String t = null; for (String rel : map.keySet()) { List<BySourceTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { // check CUI_hashmap containsKey(rel$code)??? if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } t = t + "|" + code + "|" + * rela + "|" + category; * * w.add(t); */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } // *** do the same for map2 for (String rel : map2.keySet()) { List<BySourceTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; /* * if (parent_asso_vec.contains(rel)) category = "Parent"; else * if (child_asso_vec.contains(rel)) category = "Child"; else if * (bt_vec.contains(rel)) category = "Broader"; else if * (nt_vec.contains(rel)) category = "Narrower"; */ if (parent_asso_vec.contains(rel)) category = "Child"; else if (child_asso_vec.contains(rel)) category = "Parent"; else if (bt_vec.contains(rel)) category = "Narrower"; else if (nt_vec.contains(rel)) category = "Broader"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for (BySourceTabResults result : relations) { String code = result.getCui(); if (code.compareTo(CUI) != 0 && code.indexOf("@") == -1) { if (!CUI_hashset.contains(rel + "$" + code)) { String rela = result.getRela(); if (rela == null || rela.compareTo("null") == 0) { rela = " "; } Vector v = (Vector) cui2SynonymsMap.get(code); ms_find_highest_rank_atom = System.currentTimeMillis(); BySourceTabResults top_atom = findHighestRankedAtom(v, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); /* * if (top_atom == null) { Concept c = * getConceptByCode("NCI Metathesaurus", null, null, * code); t = c.getEntityDescription().getContent() * + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + * Constants.EXTERNAL_TERM_SOURCE + "|" + * Constants.EXTERNAL_TERM_SOURCE_CODE; } else { t = * top_atom.getTerm() + "|" + top_atom.getType() + * "|" + top_atom.getSource() + "|" + * top_atom.getCode(); } */ if (top_atom == null) { for (int k = 0; k < v.size(); k++) { top_atom = (BySourceTabResults) v.elementAt(k); t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + top_atom.getRela() + "|" + category; w.add(t); } } else { t = top_atom.getTerm() + "|" + top_atom.getType() + "|" + top_atom.getSource() + "|" + top_atom.getCode(); t = t + "|" + code + "|" + rela + "|" + category; w.add(t); } // w.add(t); CUI_hashset.add(rel + "$" + code); // Temporarily save non-RO other relationships if (category.compareTo("Other") == 0 && rela.compareTo("RO") != 0) { if (!rel_hset.contains(code)) { rel_hset.add(code); } } if (category.compareTo("Child") == 0 && rela.compareTo("CHD") != 0) { if (!hasSubtype_hset.contains(code)) { hasSubtype_hset.add(code); } } } } } } } long total_categorization_delay = System.currentTimeMillis() - ms; String action_atom = "Find highest rank atom delay"; Debug.println("Run time (ms) for " + action_atom + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action_atom, "getNeighborhoodSynonyms"); long absolute_categorization_delay = total_categorization_delay - ms_find_highest_rank_atom_delay; Debug.println("Run time (ms) for " + action + " " + absolute_categorization_delay); DBG.debugDetails(absolute_categorization_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = System.currentTimeMillis(); action = "Remove redundant relationships"; for (int i = 0; i < w.size(); i++) { String s = (String) w.elementAt(i); int j = i + 1; Vector<String> v = parseData(s, "|"); if (v.size() == 7) { String rel = (String) v.elementAt(6); if (rel.compareTo("Child") != 0 && rel.compareTo("Other") != 0) { u.add(s); } else if (rel.compareTo("Child") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("CHD") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!hasSubtype_hset.contains(code)) { u.add(s); } } } else if (rel.compareTo("Other") == 0) { String rela = (String) v.elementAt(5); if (rela.compareTo("RO") != 0) { u.add(s); } else { String code = (String) v.elementAt(4); if (!rel_hset.contains(code)) { u.add(s); } } } } else { // Debug.println("(" + j + ") ??? " + s); } } delay = System.currentTimeMillis() - ms_remove_RO_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "Initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); // DBG.debugDetails("Max Return", NCImBrowserProperties.maxToReturn); delay = System.currentTimeMillis() - ms_all; Debug.println("Run time (ms) for " + action_overall + " " + delay); DBG.debugDetails(delay, action_overall, "getNeighborhoodSynonyms"); return u; } public static String getCodingSchemeURIAndVersion(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i = 0; i < csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { if (ltag == null) return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); for (int j = 0; j < tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getCodingSchemeURI() + "|" + css.getRepresentsVersion(); } } } } } catch (Exception e) { e.printStackTrace(); } return null; } public static String htmlEntityEncode(String s) { StringBuilder buf = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') { buf.append(c); } else { buf.append("&#").append((int) c).append(";"); } } return buf.toString(); } // [#23318] Maintain a history of visited concepts public static String getVisitedConceptLink(Vector concept_vec) { StringBuffer strbuf = new StringBuffer(); String line = "<A href=\"#\" onmouseover=\"Tip('"; strbuf.append(line); strbuf.append("<ul>"); for (int i = 0; i < concept_vec.size(); i++) { int j = concept_vec.size() - i - 1; String concept_data = (String) concept_vec.elementAt(j); Vector w = DataUtils.parseData(concept_data, "|"); String scheme = Constants.CODING_SCHEME_NAME; String code = (String) w.elementAt(0); String name = (String) w.elementAt(1); name = htmlEntityEncode(name); strbuf.append("<li>"); line = "<a href=\\'/ncimbrowser/ConceptReport.jsp?dictionary=" + scheme + "&code=" + code + "\\'>" + name + "</a><br>"; strbuf.append(line); strbuf.append("</li>"); } strbuf.append("</ul>"); line = "',"; strbuf.append(line); line = "WIDTH, 300, TITLE, 'Visited Concepts', SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)\""; strbuf.append(line); line = " onmouseout=UnTip() "; strbuf.append(line); line = ">Visited Concepts</A>"; strbuf.append(line); return strbuf.toString(); } public static HashMap getPropertyValuesForCodes(String scheme, String version, Vector codes, String propertyName) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); for (int i = 0; i < codes.size(); i++) { String code = (String) codes.elementAt(i); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); } CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { LocalNameList propertyNames = new LocalNameList(); propertyNames.addEntry(propertyName); CodedNodeSet.PropertyType[] propertyTypes = null; long ms = System.currentTimeMillis(), delay = 0; SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; // needs to be set to true int maxToReturn = codes.size(); ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, propertyNames, propertyTypes, resolveObjects, maxToReturn); // _logger.debug("resolveToList done"); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() > 0) { for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); } else { // _logger.debug(c.getEntityDescription().getContent()); Property[] properties = c.getProperty(); String values = ""; for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; values = values + prop.getValue().getContent(); if (j < properties.length - 1) { values = values + "; "; } } hmap.put(rcr.getCode(), values); } } } return hmap; } catch (Exception e) { _logger.error("Method: SearchUtil.searchByProperties"); _logger.error("* ERROR: cns.resolve throws exceptions."); _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector getConceptSources(String scheme, String version, String code) { Entity c = getConceptByCode(scheme, version, null, code); if (c == null) return null; Presentation[] presentations = c.getPresentation(); HashSet hset = new HashSet(); Vector v = new Vector(); for (int i = 0; i < presentations.length; i++) { Presentation presentation = presentations[i]; // java.lang.String name = presentation.getPropertyName(); // java.lang.String prop_value = // presentation.getValue().getContent(); Source[] sources = presentation.getSource(); for (int j = 0; j < sources.length; j++) { Source source = (Source) sources[j]; java.lang.String sab = source.getContent(); if (!hset.contains(sab)) { hset.add(sab); v.add(sab); } } } hset.clear(); return v; } public static String getMetadataValue(String scheme, String propertyName){ Vector v; try { v = getMetadataValues(scheme, propertyName); } catch (Exception e) { _logger.error(e.getMessage()); return null; } if (v == null || v.size() == 0) return null; return (String) v.elementAt(0); } public static Vector getMetadataValues(String scheme, String propertyName) { Vector v = new Vector(); /* * if (formalName2MetadataHashMap == null) { * //formalName2MetadataHashMap = getFormalName2MetadataHashMap(); * MetadataUtils.setSAB2FormalNameHashMap(); } */ if (_formalName2MetadataHashMap == null) { _formalName2MetadataHashMap = MetadataUtils.getFormalName2MetadataHashMap(); } Vector metadataProperties = (Vector) _formalName2MetadataHashMap.get(scheme); if (metadataProperties != null) { for (int i = 0; i < metadataProperties.size(); i++) { String t = (String) metadataProperties.elementAt(i); Vector w = parseData(t, "|"); String t1 = (String) w.elementAt(0); String t2 = (String) w.elementAt(1); if (t1.compareTo(propertyName) == 0) v.add(t2); } } return v; } public static boolean checkIsLicensed(String sab) { if (sab == null) return false; String securd_vocabularies = NCImBrowserProperties.getSecuredVocabularies(); String target = "|" + sab + "|"; if (securd_vocabularies.indexOf(target) == -1) return false; return true; } // /////////////////////////////////////////////// // siblings // ////////////////////////////////////////////// public Vector getSiblings(String code) { // return getSiblings("NCI Metathesaurus", null, code); return getSiblingsExt(code); } public Vector getSiblings(String scheme, String version, String code) { LexBIGService lbSvc = null; LexBIGServiceConvenienceMethods lbscm = null; Vector sibling_vec = new Vector(); try { lbSvc = RemoteServerUtil.createLexBIGService(); lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { return sibling_vec; } HashSet hset = new HashSet(); String[] assocNames = new String[] { "PAR" }; // find parents Vector v = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames); for (int i = 0; i < v.size(); i++) { String t = (String) v.elementAt(i); Vector w = parseData(t); String rel = (String) w.elementAt(0); String rela = (String) w.elementAt(1); String parent_name = (String) w.elementAt(2); String parent_code = (String) w.elementAt(3); Vector u = getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, parent_code, assocNames, false); for (int j = 0; j < u.size(); j++) { String t2 = (String) u.elementAt(j); Vector w2 = parseData(t2); String sib_rel = (String) w2.elementAt(0); String sib_rela = (String) w2.elementAt(1); String sib_name = (String) w2.elementAt(2); String sib_code = (String) w2.elementAt(3); String sib_sab = (String) w2.elementAt(4); if (!hset.contains(t2) && sib_code.compareTo(code) != 0) { sibling_vec.add("SIB" + "|" + sib_name + "|" + sib_code + "|" + sib_sab); } } } return sibling_vec; } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames) { return getAssociatedConceptsByAssociations(lbSvc, lbscm, scheme, version, code, assocNames, true); } public Vector getAssociatedConceptsByAssociations(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList(assocNames, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = -1;// NCImBrowserProperties.maxToReturn; boolean navigationForward = !direction; boolean navigationBackward = direction; matches = cng.resolveAsList(ConvenienceMethods.createConceptReference( code, scheme), navigationForward, navigationBackward, 1, 1, new LocalNameList(), null, null, maxToReturn); String qualifier_name = null; String qualifier_value = null; if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches.enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); if (!direction) targetof = ref.getSourceOf(); if (targetof != null) { Association[] associations = targetof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { String associationName = lbscm .getAssociationNameFromAssociationCode( scheme, csvt, assoc .getAssociationName()); if (associationName .compareToIgnoreCase("equivalentClass") != 0) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = "NA"; String asso_source = "NA"; if (associationName .compareToIgnoreCase("equivalentClass") != 0) { for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace // associationName // by // Rela // value break; } } for (NameAndValue qual : ac .getAssociationQualifiers() .getNameAndValue()) { qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name .compareToIgnoreCase("source") == 0) { asso_source = qualifier_value; // replace // associationName // by // Rela // value break; } } } v.add(associationName + "|" + asso_label + "|" + ac.getReferencedEntry() .getEntityDescription() .getContent() + "|" + ac.getReferencedEntry() .getEntityCode() + "|" + asso_source); } } } } } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; } public static HashMap getPropertyValueHashMap(String code) { return getPropertyValueHashMap(Constants.CODING_SCHEME_NAME, null, code); } private static String getSourceQualifierValue(Property p) { if (p == null) return null; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareToIgnoreCase("source") == 0) { return qualifier_value; } } } return null; } private static String getPropertySource(Property p) { if (p == null) return null; Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; return src.getContent(); } return null; } public static HashMap getPropertyValueHashMap(String scheme, String version, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc = null"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); ConceptReferenceList crefs = new ConceptReferenceList(); ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(scheme); cr.setConceptCode(code); crefs.addConceptReference(cr); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(scheme, versionOrTag); cns = cns.restrictToCodes(crefs); } catch (Exception e1) { e1.printStackTrace(); } try { SortOptionList sortOptions = null; LocalNameList filterOptions = null; boolean resolveObjects = true; ResolvedConceptReferenceList rcrl = cns.resolveToList(sortOptions, filterOptions, null, null, resolveObjects, 1); HashMap hmap = new HashMap(); if (rcrl == null) { _logger.warn("Concept not found."); return null; } if (rcrl.getResolvedConceptReferenceCount() == 0) return null; ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(0); Entity c = rcr.getReferencedEntry(); if (c == null) { _logger.warn("Concept is null."); return null; } return getPropertyValueHashMap(c); } catch (Exception e) { _logger.error("* " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); } return null; } public static HashMap getPropertyValueHashMap(Entity c) { if (c == null) { return null; } HashMap hmap = new HashMap(); Property[] properties = c.getProperty(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getPresentation(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getDefinition(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } properties = c.getComment(); for (int j = 0; j < properties.length; j++) { Property prop = properties[j]; String prop_name = prop.getPropertyName(); String prop_value = prop.getValue().getContent(); String source = getPropertySource(prop); if (source == null) source = "None"; prop_value = prop_value + "|" + source; Vector u = new Vector(); if (hmap.containsKey(prop_name)) { u = (Vector) hmap.get(prop_name); } else { u = new Vector(); } if (!u.contains(prop_value)) { u.add(prop_value); hmap.put(prop_name, u); } } return hmap; } public List<RelationshipTabResults> getAssociatedConceptsEx(String CUI, String associationName, Direction direction) { List<String> assoc_list = new ArrayList(); assoc_list.add(associationName); LexBIGService lbs = RemoteServerUtil.createLexBIGService(); CodingScheme cs = null; List results = new ArrayList<RelationshipTabResults>(); try { cs = getCodingScheme("NCI Metathesaurus", null); MetaBrowserService mbs = null; try { mbs = (MetaBrowserService) lbs .getGenericExtension("metabrowser-extension"); Map<String, List<RelationshipTabResults>> map = null; try { map = mbs.getRelationshipsDisplay(CUI, assoc_list, direction); } catch (Exception ex) { ex.printStackTrace(); return null; } for (String rel : map.keySet()) { List<RelationshipTabResults> relations = map.get(rel); for (RelationshipTabResults result : relations) { results.add(result); } } return results; } catch (Exception ex) { ex.printStackTrace(); return null; } } catch (Exception ex) { } return null; } public Vector getSiblingsExt(String CUI) { Vector v = new Vector(); HashSet hset = new HashSet(); List results = getAssociatedConceptsEx(CUI, "PAR", Direction.TARGETOF); if (results == null) return null; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); for (int i = 0; i < results.size(); i++) { RelationshipTabResults result = (RelationshipTabResults) results.get(i); List children = getAssociatedConceptsEx(result.getCui(), "CHD", Direction.TARGETOF); for (int j = 0; j < children.size(); j++) { RelationshipTabResults sub_result = (RelationshipTabResults) children.get(j); String t = "SIB" + "|" + sub_result.getName() + "|" + sub_result.getCui() + "|" + sub_result.getSource(); if (!hset.contains(t) && sub_result.getCui().compareTo(CUI) != 0) { hset.add(t); // v.add(t); String key = sub_result.getSource() + "|" + sub_result.getName() + "|" + sub_result.getCui(); hmap.put(key, t); key_vec.add(key); } } } key_vec = SortUtils.quickSort(key_vec); for (int i = 0; i < key_vec.size(); i++) { String key = (String) key_vec.elementAt(i); String value = (String) hmap.get(key); v.add(value); } // return SortUtils.quickSort(v); return v; } public static String getAssociationReverseName(String assoName) { String assocLabel = assoName; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); assocLabel = lbscm .getAssociationReverseName(assoName, "NCI Metathesaurus", null); } catch (Exception ex) { ex.printStackTrace(); } return assocLabel; } }
diff --git a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/mopp/AbstractPrinterGenerator.java b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/mopp/AbstractPrinterGenerator.java index b747f3687..a0872f787 100644 --- a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/mopp/AbstractPrinterGenerator.java +++ b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/mopp/AbstractPrinterGenerator.java @@ -1,162 +1,162 @@ package org.emftext.sdk.codegen.generators.mopp; import static org.emftext.sdk.codegen.generators.IClassNameConstants.E_OBJECT; import static org.emftext.sdk.codegen.generators.IClassNameConstants.ILLEGAL_ARGUMENT_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MAP; import static org.emftext.sdk.codegen.generators.IClassNameConstants.PRINTER_WRITER; import static org.emftext.sdk.codegen.generators.IClassNameConstants.STRING; import java.util.LinkedList; import java.util.List; import java.util.Queue; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; import org.emftext.sdk.codegen.EArtifact; import org.emftext.sdk.codegen.GenerationContext; import org.emftext.sdk.codegen.GeneratorUtil; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.generators.JavaBaseGenerator; import org.emftext.sdk.codegen.util.ConcreteSyntaxUtil; import org.emftext.sdk.concretesyntax.GenClassCache; import org.emftext.sdk.concretesyntax.Rule; import org.emftext.sdk.util.StringUtil; public abstract class AbstractPrinterGenerator extends JavaBaseGenerator { private final GeneratorUtil generatorUtil = new GeneratorUtil(); private ConcreteSyntaxUtil csUtil = new ConcreteSyntaxUtil(); private GenClassCache genClassCache; private String referenceResolverSwitchClassName; public AbstractPrinterGenerator() { super(); } public AbstractPrinterGenerator(GenerationContext context, EArtifact artifact) { super(context, artifact); genClassCache = context.getConcreteSyntax().getGenClassCache(); this.referenceResolverSwitchClassName = context.getQualifiedClassName(EArtifact.REFERENCE_RESOLVER_SWITCH); } protected String getMetaClassName(Rule rule) { if (hasMapType(rule.getMetaclass()) ) { return rule.getMetaclass().getQualifiedClassName(); } return genClassCache.getQualifiedInterfaceName(rule.getMetaclass()); } protected String getMethodName(Rule rule) { String className = getMetaClassName(rule); // first escape underscore with their unicode value className = className.replace("_", "_005f"); // then replace package separator with underscore className = className.replace(".", "_"); return "print_" + className; } protected void addAddWarningToResourceMethod(StringComposite sc) { sc.add("protected void addWarningToResource(final " + STRING + " errorMessage, " + E_OBJECT + " cause) {"); sc.add(getClassNameHelper().getI_TEXT_RESOURCE() + " resource = getResource();"); sc.add("if (resource == null) {"); sc.add("// the resource can be null if the printer is used stand alone"); sc.add("return;"); sc.add("}"); sc.add("resource.addProblem(new " + getContext().getQualifiedClassName(EArtifact.PROBLEM) + "(errorMessage, " + getClassNameHelper().getE_PROBLEM_TYPE() + ".ERROR), cause);"); sc.add("}"); sc.addLineBreak(); } protected void addDoPrintMethod(StringComposite sc, List<Rule> rules) { sc.add("protected void doPrint(" + E_OBJECT + " element, " + PRINTER_WRITER + " out, " + STRING + " globaltab) {"); sc.add("if (element == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write.\");"); sc.add("}"); sc.add("if (out == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write on.\");"); sc.add("}"); sc.addLineBreak(); Queue<Rule> ruleQueue = new LinkedList<Rule>(rules); while (!ruleQueue.isEmpty()) { Rule rule = ruleQueue.remove(); // check whether all subclass calls have been printed if (csUtil.hasSubClassesWithCS(rule.getMetaclass(), ruleQueue)) { ruleQueue.add(rule); } else { sc.add("if (element instanceof " + getMetaClassName(rule) + ") {"); sc.add(getMethodName(rule) + "((" + getMetaClassName(rule) + ") element, globaltab, out);"); sc.add("return;"); sc.add("}"); } } sc.addLineBreak(); - sc.add("addWarningToResource(\"The cs printer can not handle \" + element.eClass().getName() + \" elements\", element);"); + sc.add("addWarningToResource(\"The printer can not handle \" + element.eClass().getName() + \" elements\", element);"); sc.add("}"); sc.addLineBreak(); } protected void addGetOptionsMethod(StringComposite sc) { sc.add("public " + MAP + "<?,?> getOptions() {"); sc.add("return options;"); sc.add("}"); sc.addLineBreak(); } protected void addSetOptionsMethod(StringComposite sc) { sc.add("public void setOptions(" + MAP + "<?,?> options) {"); sc.add("this.options = options;"); sc.add("}"); sc.addLineBreak(); } protected void addGetReferenceResolverSwitchMethod(StringComposite sc) { sc.add("protected " + referenceResolverSwitchClassName + " getReferenceResolverSwitch() {"); sc.add("return (" + referenceResolverSwitchClassName + ") new " + getClassNameHelper().getMETA_INFORMATION() + "().getReferenceResolverSwitch();"); sc.add("}"); sc.addLineBreak(); } protected void addGetResourceMethod(StringComposite sc) { sc.add("public " + getClassNameHelper().getI_TEXT_RESOURCE() + " getResource() {"); sc.add("return resource;"); sc.add("}"); sc.addLineBreak(); } // TODO mseifert: I think this code is also somewhere else protected String getAccessMethod(GenClass genClass, GenFeature genFeature) { if (hasMapType(genClass)) { return "get" + StringUtil.capitalize(genFeature.getName()) + "()"; } else { String method = "eGet(element.eClass().getEStructuralFeature(" + generatorUtil.getFeatureConstant(genClass, genFeature) + "))"; return method; } } // TODO mseifert: this should go somewhere else protected boolean hasMapType(GenClass genClass) { return java.util.Map.Entry.class.getName().equals(genClass.getEcoreClass().getInstanceClassName()); } protected String getTabString(int count) { return getRepeatingString(count, '\t'); } protected String getWhiteSpaceString(int count) { return getRepeatingString(count, ' '); } private String getRepeatingString(int count, char character) { StringBuffer spaces = new StringBuffer(); for (int i = 0; i < count; i++) { spaces.append(character); } return spaces.toString(); } }
true
true
protected void addDoPrintMethod(StringComposite sc, List<Rule> rules) { sc.add("protected void doPrint(" + E_OBJECT + " element, " + PRINTER_WRITER + " out, " + STRING + " globaltab) {"); sc.add("if (element == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write.\");"); sc.add("}"); sc.add("if (out == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write on.\");"); sc.add("}"); sc.addLineBreak(); Queue<Rule> ruleQueue = new LinkedList<Rule>(rules); while (!ruleQueue.isEmpty()) { Rule rule = ruleQueue.remove(); // check whether all subclass calls have been printed if (csUtil.hasSubClassesWithCS(rule.getMetaclass(), ruleQueue)) { ruleQueue.add(rule); } else { sc.add("if (element instanceof " + getMetaClassName(rule) + ") {"); sc.add(getMethodName(rule) + "((" + getMetaClassName(rule) + ") element, globaltab, out);"); sc.add("return;"); sc.add("}"); } } sc.addLineBreak(); sc.add("addWarningToResource(\"The cs printer can not handle \" + element.eClass().getName() + \" elements\", element);"); sc.add("}"); sc.addLineBreak(); }
protected void addDoPrintMethod(StringComposite sc, List<Rule> rules) { sc.add("protected void doPrint(" + E_OBJECT + " element, " + PRINTER_WRITER + " out, " + STRING + " globaltab) {"); sc.add("if (element == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write.\");"); sc.add("}"); sc.add("if (out == null) {"); sc.add("throw new " + ILLEGAL_ARGUMENT_EXCEPTION + "(\"Nothing to write on.\");"); sc.add("}"); sc.addLineBreak(); Queue<Rule> ruleQueue = new LinkedList<Rule>(rules); while (!ruleQueue.isEmpty()) { Rule rule = ruleQueue.remove(); // check whether all subclass calls have been printed if (csUtil.hasSubClassesWithCS(rule.getMetaclass(), ruleQueue)) { ruleQueue.add(rule); } else { sc.add("if (element instanceof " + getMetaClassName(rule) + ") {"); sc.add(getMethodName(rule) + "((" + getMetaClassName(rule) + ") element, globaltab, out);"); sc.add("return;"); sc.add("}"); } } sc.addLineBreak(); sc.add("addWarningToResource(\"The printer can not handle \" + element.eClass().getName() + \" elements\", element);"); sc.add("}"); sc.addLineBreak(); }
diff --git a/plugins/org.eclipse.m2m.atl.profiler.ui/src/org/eclipse/m2m/atl/profiler/ui/profilingdatatable/ProfilingDataTableView.java b/plugins/org.eclipse.m2m.atl.profiler.ui/src/org/eclipse/m2m/atl/profiler/ui/profilingdatatable/ProfilingDataTableView.java index 36c95a20..192561e1 100644 --- a/plugins/org.eclipse.m2m.atl.profiler.ui/src/org/eclipse/m2m/atl/profiler/ui/profilingdatatable/ProfilingDataTableView.java +++ b/plugins/org.eclipse.m2m.atl.profiler.ui/src/org/eclipse/m2m/atl/profiler/ui/profilingdatatable/ProfilingDataTableView.java @@ -1,543 +1,543 @@ /******************************************************************************* * Copyright (c) 2008,2009 Communication & Systems. * * 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: * Arnaud Giuliani - initial API and implementation * Obeo - icons modifications, observer deletion *******************************************************************************/ package org.eclipse.m2m.atl.profiler.ui.profilingdatatable; import java.util.Collections; import java.util.Observable; import java.util.Observer; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.m2m.atl.profiler.core.ATLModelHandler; import org.eclipse.m2m.atl.profiler.core.ATLProfiler; import org.eclipse.m2m.atl.profiler.core.ProfilerModelHandler; import org.eclipse.m2m.atl.profiler.core.util.ProfilerModelExporter; import org.eclipse.m2m.atl.profiler.exportmodel.ExportRoot; import org.eclipse.m2m.atl.profiler.model.ProfilingOperation; import org.eclipse.m2m.atl.profiler.model.provider.ModelItemProviderAdapterFactory; import org.eclipse.m2m.atl.profiler.ui.Messages; import org.eclipse.m2m.atl.profiler.ui.activators.ExecutionViewerActivator; import org.eclipse.m2m.atl.profiler.ui.executionviewer.view.ExecutionView; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.DrillDownAdapter; import org.eclipse.ui.part.ViewPart; /** * The data table view. * * @author <a href="mailto:[email protected]">Arnaud Giuliani</a> * @author <a href="mailto:[email protected]">Thierry Fortin</a> */ public class ProfilingDataTableView extends ViewPart implements Observer, ISelectionListener { /** Instructions column name. */ public static final String INSTRUCTIONS_COLNAME = Messages .getString("ProfilingDataTableView_EXECUTED_INSTRUCTIONS"); //$NON-NLS-1$ /** Execution time column name. */ public static final String TIME_EXECUTION_COLNAME = Messages .getString("ProfilingDataTableView_TIME_EXECUTION"); //$NON-NLS-1$ /** Calls column name. */ public static final String CALLS_COLNAME = Messages.getString("ProfilingDataTableView_CALLS"); //$NON-NLS-1$ /** Operation name column name. */ public static final String OPERATION_NAME_COLNAME = Messages .getString("ProfilingDataTableView_OPERATION_NAME"); //$NON-NLS-1$ /** In memory column name. */ public static final String INMEMORY_COLNAME = Messages.getString("ProfilingDataTableView_MEMORY_COL"); //$NON-NLS-1$ /** Max memory column name. */ public static final String MAXMEMORY_COLNAME = Messages .getString("ProfilingDataTableView_MAX_MEMORY_COL"); //$NON-NLS-1$ /** Out memory column name. */ public static final String OUTMEMORY_COLNAME = Messages .getString("ProfilingDataTableView_END_MEMORY_COL"); //$NON-NLS-1$ /** The view id. */ public static final String ID = "org.eclipse.m2m.atl.profiler.ui.profilingdatatable"; //$NON-NLS-1$ private static final String SHOW_PERCENTS = Messages .getString("ProfilingDataTableView_PERCENT_STATISTICS"); //$NON-NLS-1$ private static final String EXPORT_DATA = Messages.getString("ProfilingDataTableView_XMI_EXPORT"); //$NON-NLS-1$ private static final String SHOW_PERCENTS_GIF = "percentsStatistics.gif"; //$NON-NLS-1$ private static final String SAVE_GIF = "save.gif"; //$NON-NLS-1$ private static final String HIDE_NATIVE_OPERATIONS_GIF = "hideNativeOperations.gif"; //$NON-NLS-1$ private static final String SHOW_PERCENTAGES = Messages .getString("ProfilingDataTableView_HIDE_NATIVE_OPERATIONS"); //$NON-NLS-1$ private static int instructionsColId; private static int timeExecutionColId; private static int callsColId; private static int operationNameColId; private static int inMemoryColId; private static int maxMemoryColId; private static int outMemoryColId; private static boolean showPercents; private static long totalInstructions; private static double totalTime; // Actions private Action showPercentsAction; private Action hideNativeOperationsAction; // Filters private NativeOperationFilter hideNativeOperationsfilter; private TreeViewer treeViewer; private DrillDownAdapter drillDownAdapter; private Action doubleClickAction; private Action xmiExportAction; private DirectoryDialog exportDirectorydialog; /** * The constructor. */ public ProfilingDataTableView() { ATLProfiler.getInstance().addObserver(this); ProfilingDataTableView.showPercents = false; } /** * {@inheritDoc} * * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ public void dispose() { super.dispose(); ATLProfiler.getInstance().deleteObserver(this); } /** * {@inheritDoc} * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { treeViewer = new TreeViewer(parent, SWT.FULL_SELECTION); drillDownAdapter = new DrillDownAdapter(treeViewer); treeViewer.setContentProvider(new ProfilingDataTableContentProvider( new ModelItemProviderAdapterFactory())); treeViewer .setLabelProvider(new ProfilingDataTableLabelProvider(new ModelItemProviderAdapterFactory())); exportDirectorydialog = new DirectoryDialog(parent.getShell()); makeColumns(); makeListeners(); makefilters(); makeActions(); setDefaultActions(); contributeToActionBars(); hookDoubleClickAction(); getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this); getSite().setSelectionProvider(treeViewer); } private void makeListeners() { // TreeTable listeners Tree tree = treeViewer.getTree(); addColumnSelectionListener(operationNameColId, tree, new NameComparator(), new NameComparator(false)); addColumnSelectionListener(timeExecutionColId, tree, new TimeComparator(), new TimeComparator(false)); addColumnSelectionListener(instructionsColId, tree, new TotalInstructionComparator(), new TotalInstructionComparator(false)); addColumnSelectionListener(callsColId, tree, new CallsComparator(), new CallsComparator(false)); addColumnSelectionListener(inMemoryColId, tree, new MemoryComparator( MemoryComparator.ColumnType.InMem), new MemoryComparator(MemoryComparator.ColumnType.InMem, false)); addColumnSelectionListener(maxMemoryColId, tree, new MemoryComparator( MemoryComparator.ColumnType.MaxMem), new MemoryComparator(MemoryComparator.ColumnType.MaxMem, false)); addColumnSelectionListener(outMemoryColId, tree, new MemoryComparator( MemoryComparator.ColumnType.OutMem), new MemoryComparator(MemoryComparator.ColumnType.OutMem, false)); } private void addColumnSelectionListener(final int colId, final Tree tree, final ViewerComparator wc, final ViewerComparator descWc) { tree.getColumn(colId).addSelectionListener(new SelectionAdapter() { private int direction; @Override public void widgetSelected(SelectionEvent e) { if (direction == SWT.None) { setupColumnSorting(colId, SWT.UP, tree, wc); } else if (direction == SWT.UP) { setupColumnSorting(colId, SWT.DOWN, tree, descWc); } else { setupColumnSorting(colId, SWT.None, tree, null); } treeViewer.refresh(); } private void setupColumnSorting(final int colId, final int dir, final Tree tree, final ViewerComparator wc) { treeViewer.collapseAll(); treeViewer.setComparator(wc); tree.setSortColumn(tree.getColumn(colId)); direction = dir; tree.setSortDirection(direction); } }); } private void makeColumns() { int i = 0; Tree tree = treeViewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); operationNameColId = i; TreeColumn opNameCol = new TreeColumn(tree, SWT.LEFT); opNameCol.setText(OPERATION_NAME_COLNAME); opNameCol.setWidth(150); i++; callsColId = i; TreeColumn callsCol = new TreeColumn(tree, SWT.CENTER); callsCol.setText(CALLS_COLNAME); callsCol.setWidth(75); i++; timeExecutionColId = i; TreeColumn timeExecCol = new TreeColumn(tree, SWT.CENTER); timeExecCol.setText(TIME_EXECUTION_COLNAME); timeExecCol.setWidth(120); i++; instructionsColId = i; TreeColumn instrCountCol = new TreeColumn(tree, SWT.CENTER); instrCountCol.setText(INSTRUCTIONS_COLNAME); instrCountCol.setWidth(140); i++; inMemoryColId = i; TreeColumn inMemCol = new TreeColumn(tree, SWT.CENTER); inMemCol.setText(INMEMORY_COLNAME); inMemCol.setWidth(120); i++; maxMemoryColId = i; TreeColumn maxMemCol = new TreeColumn(tree, SWT.CENTER); maxMemCol.setText(MAXMEMORY_COLNAME); maxMemCol.setWidth(105); i++; outMemoryColId = i; TreeColumn outMemCol = new TreeColumn(tree, SWT.CENTER); outMemCol.setText(OUTMEMORY_COLNAME); outMemCol.setWidth(85); } private void makefilters() { hideNativeOperationsfilter = new NativeOperationFilter(); } private void makeActions() { hideNativeOperationsAction = new Action(SHOW_PERCENTAGES, Action.AS_CHECK_BOX) { @Override public void run() { updateFilters(hideNativeOperationsAction); } }; hideNativeOperationsAction.setImageDescriptor(ExecutionViewerActivator .getImageDescriptor(HIDE_NATIVE_OPERATIONS_GIF)); showPercentsAction = new Action(SHOW_PERCENTS, Action.AS_CHECK_BOX) { @Override public void run() { if (showPercents) { - showPercents = true; + showPercents = false; // get total time & total instructions totalTime = ProfilerModelHandler.getInstance().getModelTotalTime(); totalInstructions = ProfilerModelHandler.getInstance().getModelTotalInstructions(); } else { - showPercents = false; + showPercents = true; } treeViewer.refresh(); } }; showPercentsAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SHOW_PERCENTS_GIF)); xmiExportAction = new Action(EXPORT_DATA) { @Override public void run() { String path = exportDirectorydialog.open(); if (path != null) { path += "/profiler_export.xmi"; //$NON-NLS-1$ URI uri = URI.createFileURI(path); Resource rsc = new ResourceSetImpl().createResource(uri); rsc.getContents().clear(); ExportRoot exportModel = null; try { exportModel = ProfilerModelExporter.exportCurrentProfilingModel(); } catch (Exception e1) { e1.printStackTrace(); } if (exportModel != null) { rsc.getContents().add(exportModel); try { rsc.save(Collections.EMPTY_MAP); } catch (Exception e) { e.printStackTrace(); } showMessage( Messages.getString("ProfilingDataTableView_EXPORT_SUCCESSFULL") + path, Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } else { showError( Messages.getString("ProfilingDataTableView_UNABLE_TO_EXPORT"), Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } } } }; xmiExportAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SAVE_GIF)); doubleClickAction = new Action() { @Override public void run() { ISelection selection = treeViewer.getSelection(); if (treeViewer.getComparator() != null) { treeViewer.collapseAll(); treeViewer.setComparator(null); treeViewer.getTree().setSortDirection(0); TreeSelection current = (TreeSelection)selection; treeViewer.setSelection(current); } } }; } private void hookDoubleClickAction() { treeViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { doubleClickAction.run(); } }); } private void setDefaultActions() { hideNativeOperationsAction.setChecked(true); treeViewer.addFilter(hideNativeOperationsfilter); } private void updateFilters(Action updateFiltersAction) { if (updateFiltersAction.isChecked()) { treeViewer.addFilter(hideNativeOperationsfilter); } else { treeViewer.removeFilter(hideNativeOperationsfilter); } } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } private void fillLocalPullDown(IMenuManager manager) { manager.add(hideNativeOperationsAction); manager.add(showPercentsAction); manager.add(xmiExportAction); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(hideNativeOperationsAction); manager.add(showPercentsAction); manager.add(xmiExportAction); manager.add(new Separator()); drillDownAdapter.addNavigationActions(manager); } /** * {@inheritDoc} * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { treeViewer.getControl().setFocus(); } /** * Sets the view input. * * @param arg * the input */ public void setInput(final Object arg) { Display display = PlatformUI.getWorkbench().getDisplay(); display.syncExec(new Runnable() { public void run() { treeViewer.setInput(arg); treeViewer.refresh(); } }); } /** * {@inheritDoc} * * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ public void update(Observable o, Object arg) { setInput(arg); } /** * {@inheritDoc} * * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (part instanceof ExecutionView && !ExecutionView.isShowCallTree()) { TreeSelection current = (TreeSelection)selection; if (current.getFirstElement() instanceof ProfilingOperation) { TreePath tp = current.getPaths()[0]; if (tp.getLastSegment() instanceof ProfilingOperation) { ProfilingOperation pOp = (ProfilingOperation)tp.getLastSegment(); String atlName = ATLModelHandler.getInstance().getATLName(pOp.getContent()); Object[] segments = new Object[2]; segments[0] = ProfilerModelHandler.getInstance().getOperationRegistry().get(atlName); segments[1] = pOp; if (!((pOp.getContent().equals("__resolve__") || pOp.getContent().equals("__match_") || pOp //$NON-NLS-1$ //$NON-NLS-2$ .getContent().equals("__exec__")) && hideNativeOperationsAction.isChecked())) { //$NON-NLS-1$ TreePath newTp = new TreePath(segments); TreeSelection newselection = new TreeSelection(newTp); treeViewer.setSelection(newselection); } } } } else if (part instanceof ExecutionView && ExecutionView.isShowCallTree()) { TreeSelection current = (TreeSelection)selection; if (current.getFirstElement() instanceof ProfilingOperation) { TreePath tp = current.getPaths()[0]; if (tp.getLastSegment() instanceof ProfilingOperation) { ProfilingOperation pOp = (ProfilingOperation)tp.getLastSegment(); String atlName = ATLModelHandler.getInstance().getATLName(pOp.getContent()); Object[] segments = new Object[1]; segments[0] = ProfilerModelHandler.getInstance().getOperationRegistry().get(atlName); TreePath newTp = new TreePath(segments); TreeSelection newselection = new TreeSelection(newTp); treeViewer.setSelection(newselection); } } } } private void showMessage(String message, String title) { MessageDialog.openInformation(treeViewer.getControl().getShell(), title, message); } private void showError(String message, String title) { MessageDialog.openError(treeViewer.getControl().getShell(), title, message); } public static int getTotalInstructionsId() { return instructionsColId; } public static int getTotalTimeExecutionId() { return timeExecutionColId; } public static int getCallsId() { return callsColId; } public static int getOperationNameId() { return operationNameColId; } public static int getInMemoryColId() { return inMemoryColId; } public static boolean isShowPercentAction() { return showPercents; } public static void setShowPercentAction(boolean s) { showPercents = s; } public static long getTotalInstructions() { return totalInstructions; } public static double getTotalTime() { return totalTime; } public static int getMaxMemoryColID() { return maxMemoryColId; } public static int getOutMemoryColId() { return outMemoryColId; } }
false
true
private void makeActions() { hideNativeOperationsAction = new Action(SHOW_PERCENTAGES, Action.AS_CHECK_BOX) { @Override public void run() { updateFilters(hideNativeOperationsAction); } }; hideNativeOperationsAction.setImageDescriptor(ExecutionViewerActivator .getImageDescriptor(HIDE_NATIVE_OPERATIONS_GIF)); showPercentsAction = new Action(SHOW_PERCENTS, Action.AS_CHECK_BOX) { @Override public void run() { if (showPercents) { showPercents = true; // get total time & total instructions totalTime = ProfilerModelHandler.getInstance().getModelTotalTime(); totalInstructions = ProfilerModelHandler.getInstance().getModelTotalInstructions(); } else { showPercents = false; } treeViewer.refresh(); } }; showPercentsAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SHOW_PERCENTS_GIF)); xmiExportAction = new Action(EXPORT_DATA) { @Override public void run() { String path = exportDirectorydialog.open(); if (path != null) { path += "/profiler_export.xmi"; //$NON-NLS-1$ URI uri = URI.createFileURI(path); Resource rsc = new ResourceSetImpl().createResource(uri); rsc.getContents().clear(); ExportRoot exportModel = null; try { exportModel = ProfilerModelExporter.exportCurrentProfilingModel(); } catch (Exception e1) { e1.printStackTrace(); } if (exportModel != null) { rsc.getContents().add(exportModel); try { rsc.save(Collections.EMPTY_MAP); } catch (Exception e) { e.printStackTrace(); } showMessage( Messages.getString("ProfilingDataTableView_EXPORT_SUCCESSFULL") + path, Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } else { showError( Messages.getString("ProfilingDataTableView_UNABLE_TO_EXPORT"), Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } } } }; xmiExportAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SAVE_GIF)); doubleClickAction = new Action() { @Override public void run() { ISelection selection = treeViewer.getSelection(); if (treeViewer.getComparator() != null) { treeViewer.collapseAll(); treeViewer.setComparator(null); treeViewer.getTree().setSortDirection(0); TreeSelection current = (TreeSelection)selection; treeViewer.setSelection(current); } } }; }
private void makeActions() { hideNativeOperationsAction = new Action(SHOW_PERCENTAGES, Action.AS_CHECK_BOX) { @Override public void run() { updateFilters(hideNativeOperationsAction); } }; hideNativeOperationsAction.setImageDescriptor(ExecutionViewerActivator .getImageDescriptor(HIDE_NATIVE_OPERATIONS_GIF)); showPercentsAction = new Action(SHOW_PERCENTS, Action.AS_CHECK_BOX) { @Override public void run() { if (showPercents) { showPercents = false; // get total time & total instructions totalTime = ProfilerModelHandler.getInstance().getModelTotalTime(); totalInstructions = ProfilerModelHandler.getInstance().getModelTotalInstructions(); } else { showPercents = true; } treeViewer.refresh(); } }; showPercentsAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SHOW_PERCENTS_GIF)); xmiExportAction = new Action(EXPORT_DATA) { @Override public void run() { String path = exportDirectorydialog.open(); if (path != null) { path += "/profiler_export.xmi"; //$NON-NLS-1$ URI uri = URI.createFileURI(path); Resource rsc = new ResourceSetImpl().createResource(uri); rsc.getContents().clear(); ExportRoot exportModel = null; try { exportModel = ProfilerModelExporter.exportCurrentProfilingModel(); } catch (Exception e1) { e1.printStackTrace(); } if (exportModel != null) { rsc.getContents().add(exportModel); try { rsc.save(Collections.EMPTY_MAP); } catch (Exception e) { e.printStackTrace(); } showMessage( Messages.getString("ProfilingDataTableView_EXPORT_SUCCESSFULL") + path, Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } else { showError( Messages.getString("ProfilingDataTableView_UNABLE_TO_EXPORT"), Messages.getString("ProfilingDataTableView_EXPORT")); //$NON-NLS-1$ //$NON-NLS-2$ } } } }; xmiExportAction.setImageDescriptor(ExecutionViewerActivator.getImageDescriptor(SAVE_GIF)); doubleClickAction = new Action() { @Override public void run() { ISelection selection = treeViewer.getSelection(); if (treeViewer.getComparator() != null) { treeViewer.collapseAll(); treeViewer.setComparator(null); treeViewer.getTree().setSortDirection(0); TreeSelection current = (TreeSelection)selection; treeViewer.setSelection(current); } } }; }
diff --git a/src/imdb/parser/ParseHandler.java b/src/imdb/parser/ParseHandler.java index cdcb655..2f598cc 100644 --- a/src/imdb/parser/ParseHandler.java +++ b/src/imdb/parser/ParseHandler.java @@ -1,204 +1,204 @@ package imdb.parser; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseHandler { private Document doc; public Title getTitle(String id) throws IllegalArgumentException, IOException { /*if(!id.toLowerCase().startsWith("tt")) id = "tt" + id;*/ if(!Pattern.compile("^tt\\d+$", Pattern.CASE_INSENSITIVE).matcher(id).matches()) { throw new IllegalArgumentException(String.format("Bad ID \"%s\" supplied.", id)); } this.doc = createDoc(id); Title t; TitleParser tp = new TitleParser(doc); if(this.isTVShow()) { TVShowParser tvsp = new TVShowParser(doc); t = new TVShow(id); tp.parse(t); tvsp.parse((TVShow)t); } else if(this.isEpisode()) { EpisodeParser ep = new EpisodeParser(doc); t = new Episode(id); tp.parse(t); ep.parse((Episode)t); } else if(this.isMovie()) { MovieParser mp = new MovieParser(doc); t = new Movie(id); tp.parse(t); mp.parse((Movie)t); } else { throw new IllegalArgumentException(String.format("Bad ID \"%s\" supplied.", id)); } return t; } public String getIdByName(String name) throws IOException { URL url = new URL(String.format("http://www.imdb.com/find?q=%s&s=tt", URLEncoder.encode(name, "UTF-8"))); Document doc = createDoc(url); Elements els = doc.select(".findResult .result_text a"); if(els.size() > 0) { String titleHref = els.get(0).attr("href"); Matcher m = Pattern.compile("tt\\d+", Pattern.CASE_INSENSITIVE).matcher(titleHref); if(m.find()) { return m.group(); } } return null; } //Returns an array containing IMDb IDs for all episodes of the specified season protected static String[] parseSeasonPage(String showId, int season) throws IOException { String[] ret; Document doc = createDoc(showId, season); Elements descs = doc.getElementsByAttributeValue("itemprop", "description"); ret = new String[descs.size()]; for (int i = 0; i < descs.size(); i++) { String href = descs.get(i).previousElementSibling().child(0).attr("href"); Matcher m = Pattern.compile("tt\\d+", Pattern.CASE_INSENSITIVE).matcher(href); m.find(); ret[i] = m.group(); } return ret; } private boolean isEpisode() { boolean ret; Elements es = doc.getElementsByAttributeValue("property", "og:type"); if(es.size() > 0) { ret = es.get(0).attr("content").toLowerCase().equals("video.episode"); } else { ret = doc.getElementsByClass("tv_header").size() > 0; } return ret; } private boolean isMovie() { boolean ret; Elements es = doc.getElementsByAttributeValue("property", "og:type"); if(es.size() > 0) { ret = es.get(0).attr("content").toLowerCase().equals("video.movie"); } else { ret = !this.isTVShow() && !this.isEpisode() && doc.getElementsByClass("star-box-giga-star").size() > 0; } return ret; } private boolean isTVShow() { boolean ret; Elements es = doc.getElementsByAttributeValue("property", "og:type"); if(es.size() > 0) { ret = es.get(0).attr("content").toLowerCase().equals("video.tv_show"); } else { final String TV_SERIES = "TV Series"; String infoBarText = doc.getElementsByClass("infobar").text().trim(); ret = infoBarText.startsWith(TV_SERIES); } return ret; } public String[] getSuggestions(String query) throws Exception { ArrayList<String> suggestions = new ArrayList<String>(); - query = query.trim().replace(" ", "_"); + //IMDb seems to have a length restriction of 6 on search suggestion querys, not including spaces - //IMDb seems to have a length restriction on search suggestions querys ( http://sg.media-imdb.com/suggests/t/the_ame.json -> 200, http://sg.media-imdb.com/suggests/t/the_amer.json -> 403 ) - final int MAX_QUERY_LENGTH = 7; - if(query.length() > MAX_QUERY_LENGTH) { - query = query.substring(0, MAX_QUERY_LENGTH); + final int MAX_QUERY_LENGTH = 6; + while((query = query.trim()).replace(" ", "").length() > MAX_QUERY_LENGTH) { + query = query.substring(0, query.length() - 1); } + query = query.replace(' ', '_'); - URL url = new URL(String.format("http://sg.media-imdb.com/suggests/%s/%s.json", query.charAt(0), URLEncoder.encode(query, "UTF-8"))); + URL url = new URL(String.format("http://sg.media-imdb.com/suggests/%s/%s.json", Character.toLowerCase(query.charAt(0)), URLEncoder.encode(query.toLowerCase(), "UTF-8"))); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"); if(con.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { builder.append(line); } String json = builder.toString(); reader.close(); Matcher m = Pattern.compile("\\{.*}").matcher(json); if(m.find()) { json = m.group(); JSONObject jo = new JSONObject(json); JSONArray ja = jo.getJSONArray("d"); suggestions.ensureCapacity(ja.length()); for (int i = 0; i < ja.length(); i++) { // ID ja.getJSONObject(i).getString("id") String name = ja.getJSONObject(i).getString("l"); suggestions.add(name); } } } return suggestions.toArray(new String[suggestions.size()]); } private static Document createDoc(String id) throws IOException { return createDoc(new URL(String.format("http://imdb.com/title/%s", id))); } private static Document createDoc(String id, int season) throws IOException { return createDoc(new URL(String.format("http://imdb.com/title/%s/episodes?season=%s", id, season))); } private static Document createDoc(URL url) throws IOException { try { return Jsoup.connect(url.toString()) .timeout(5000) .ignoreHttpErrors(true) .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19") .get(); } catch (IOException e) { throw new IOException("Could not connect. Try again later"); } } }
false
true
public String[] getSuggestions(String query) throws Exception { ArrayList<String> suggestions = new ArrayList<String>(); query = query.trim().replace(" ", "_"); //IMDb seems to have a length restriction on search suggestions querys ( http://sg.media-imdb.com/suggests/t/the_ame.json -> 200, http://sg.media-imdb.com/suggests/t/the_amer.json -> 403 ) final int MAX_QUERY_LENGTH = 7; if(query.length() > MAX_QUERY_LENGTH) { query = query.substring(0, MAX_QUERY_LENGTH); } URL url = new URL(String.format("http://sg.media-imdb.com/suggests/%s/%s.json", query.charAt(0), URLEncoder.encode(query, "UTF-8"))); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"); if(con.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { builder.append(line); } String json = builder.toString(); reader.close(); Matcher m = Pattern.compile("\\{.*}").matcher(json); if(m.find()) { json = m.group(); JSONObject jo = new JSONObject(json); JSONArray ja = jo.getJSONArray("d"); suggestions.ensureCapacity(ja.length()); for (int i = 0; i < ja.length(); i++) { // ID ja.getJSONObject(i).getString("id") String name = ja.getJSONObject(i).getString("l"); suggestions.add(name); } } } return suggestions.toArray(new String[suggestions.size()]); }
public String[] getSuggestions(String query) throws Exception { ArrayList<String> suggestions = new ArrayList<String>(); //IMDb seems to have a length restriction of 6 on search suggestion querys, not including spaces final int MAX_QUERY_LENGTH = 6; while((query = query.trim()).replace(" ", "").length() > MAX_QUERY_LENGTH) { query = query.substring(0, query.length() - 1); } query = query.replace(' ', '_'); URL url = new URL(String.format("http://sg.media-imdb.com/suggests/%s/%s.json", Character.toLowerCase(query.charAt(0)), URLEncoder.encode(query.toLowerCase(), "UTF-8"))); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"); if(con.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while((line = reader.readLine()) != null) { builder.append(line); } String json = builder.toString(); reader.close(); Matcher m = Pattern.compile("\\{.*}").matcher(json); if(m.find()) { json = m.group(); JSONObject jo = new JSONObject(json); JSONArray ja = jo.getJSONArray("d"); suggestions.ensureCapacity(ja.length()); for (int i = 0; i < ja.length(); i++) { // ID ja.getJSONObject(i).getString("id") String name = ja.getJSONObject(i).getString("l"); suggestions.add(name); } } } return suggestions.toArray(new String[suggestions.size()]); }
diff --git a/core/src/edu/trunk/wisc/ssec/mcidas/CalibratorGvar.java b/core/src/edu/trunk/wisc/ssec/mcidas/CalibratorGvar.java index f1cff3c67..f6fd73633 100644 --- a/core/src/edu/trunk/wisc/ssec/mcidas/CalibratorGvar.java +++ b/core/src/edu/trunk/wisc/ssec/mcidas/CalibratorGvar.java @@ -1,404 +1,402 @@ // // CalibratorGvar.java // /* This source file is part of the edu.wisc.ssec.mcidas package and is Copyright (C) 1998 - 2008 by Tom Whittaker, Tommy Jasmin, Tom Rink, Don Murray, James Kelly, Bill Hibbard, Dave Glowacki, Curtis Rueden and others. 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package edu.wisc.ssec.mcidas; import java.io.DataInputStream; import java.io.IOException; /** * CalibratorGvar creates a Calibrator object designed specifically * to deal with GVAR data. Not fully implemented at present - some * calibrations remain to be done. * * @version 1.5 16 Nov 1998 * @author Tommy Jasmin, SSEC */ public abstract class CalibratorGvar implements Calibrator { protected static final int NUM_BANDS_IMAGER = 5; protected static final int NUM_BANDS_SOUNDER = 18; protected static final int NUM_VIS_DETECTORS = 8; protected static final int NUM_IR_DETECTORS = 2; protected static final int NUM_IR_BANDS = 4; protected static final int LOOKUP_TABLE_SZ_IMGR = 1024; protected static final int LOOKUP_TABLE_SZ_SNDR = 32768; // var to store current cal type protected static int curCalType = 0; protected static int index = 0; protected float [] visBiasCoef = new float [NUM_VIS_DETECTORS]; protected float [] visGain1Coef = new float [NUM_VIS_DETECTORS]; protected float [] visGain2Coef = new float [NUM_VIS_DETECTORS]; protected float visRadToAlb = 0.0f; protected float [][] irBiasCoef = new float [NUM_IR_DETECTORS][NUM_IR_BANDS]; protected float [][] irGainCoef = new float [NUM_IR_DETECTORS][NUM_IR_BANDS]; protected float [] sBiasCoef = new float [NUM_BANDS_SOUNDER]; protected float [] sGainCoef = new float [NUM_BANDS_SOUNDER]; protected float [][] lookupTable; // used in calibrator method private static float gain = 0.0f; private static float bias = 0.0f; private static int scale = 1; private static int bandNum = 0; private static int sid = 0; /** * * constructor * * @param dis data input stream * @param ad AncillaryData object * @param calBlock calibration parameters array * */ public CalibratorGvar ( DataInputStream dis, AncillaryData ad, int [] calBlock ) throws IOException { this(ad.getSensorId(), calBlock); } public CalibratorGvar(final int sensorId, int[] calBlock) { int calIndex = 0; sid = sensorId; // now, correct for satellites starting with G12 (sid = 78) int irOffset = 2; if (sid > 77) irOffset = 0; //System.out.println("xxx sid = "+sid); if ((sid % 2) == 0) { // initialize lookup table lookupTable = new float [NUM_BANDS_IMAGER] [LOOKUP_TABLE_SZ_IMGR]; for (int i = 0; i < NUM_BANDS_IMAGER; i++) { for (int j = 0; j < LOOKUP_TABLE_SZ_IMGR; j++) { lookupTable [i][j] = Float.NaN; } } // read in an imager format cal block for (int i = 0; i < NUM_VIS_DETECTORS; i++) { visBiasCoef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_VIS_DETECTORS; i++) { visGain1Coef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_VIS_DETECTORS; i++) { visGain2Coef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } visRadToAlb = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; for (int i = 0; i < NUM_IR_BANDS; i++) { irBiasCoef[0][(i + irOffset) % NUM_IR_BANDS] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_IR_BANDS; i++) { irBiasCoef[1][(i + irOffset) % NUM_IR_BANDS] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_IR_BANDS; i++) { irGainCoef[0][(i + irOffset) % NUM_IR_BANDS] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_IR_BANDS; i++) { irGainCoef[1][(i + irOffset) % NUM_IR_BANDS] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } } else { // initialize lookup table lookupTable = new float [NUM_BANDS_SOUNDER + 1] [LOOKUP_TABLE_SZ_SNDR]; for (int i = 0; i < NUM_BANDS_SOUNDER + 1; i++) { for (int j = 0; j < LOOKUP_TABLE_SZ_SNDR; j++) { lookupTable [i][j] = Float.NaN; } } // read in a sounder format cal block for (int i = 0; i < NUM_VIS_DETECTORS / 2; i++) { visBiasCoef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_VIS_DETECTORS / 2; i++) { visGain1Coef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_VIS_DETECTORS / 2; i++) { visGain2Coef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } visRadToAlb = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; for (int i = 0; i < NUM_BANDS_SOUNDER; i++) { sBiasCoef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } for (int i = 0; i < NUM_BANDS_SOUNDER; i++) { sGainCoef[i] = (float) ConversionUtility.GouldToNative(calBlock[calIndex]); calIndex++; } } } /** * * set calibration type of current (input) data * * @param calType one of the types defined in Calibrator interface * */ public int setCalType(int calType) { if ((calType < Calibrator.CAL_MIN) || (calType > Calibrator.CAL_MAX)) { return -1; } curCalType = calType; return 0; } /** * * calibrate from radiance to temperature * * @param inVal input data value * @param band channel/band number * @param sId sensor id number * */ public abstract float radToTemp(float inVal, int band, int sId); /** * * calibrate data buffer to specified units. * * @param inputData input data buffer * @param band channel/band number * @param calTypeOut units to convert input buffer to * */ public float[] calibrate ( float[] inputData, int band, int calTypeOut ) { // create the output data buffer float[] outputData = new float[inputData.length]; // just call the other calibrate routine for each data point for (int i = 0; i < inputData.length; i++) { outputData[i] = calibrate(inputData[i], band, calTypeOut); } // return the calibrated buffer return outputData; } /** * * calibrate single value to specified units. * * @param inputPixel input data value * @param band channel/band number * @param calTypeOut units to convert input buffer to * */ public float calibrate ( float inputPixel, int band, int calTypeOut ) { float outputData = 0.0f; //System.out.println("#### input pixel="+inputPixel); //System.out.println("#### cal band = "+band); //System.out.println("#### len lookup = "+lookupTable.length+" "+lookupTable[3].length); // load gain and bias constants based on band requested if (band != bandNum) { bandNum = band; if ((sid % 2) == 0) { if (band == 1) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = irGainCoef[0][band - 2]; bias = irBiasCoef[0][band - 2]; //System.out.println("#### band="+band+" gain="+gain+" bias"+bias); } scale = 32; - gain = 5.2f; - bias = 68.f; } else { if (band == 19) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = sGainCoef[band - 1]; bias = sBiasCoef[band - 1]; } scale = 2; } } // check lookup table first, if there is an entry, use it if (curCalType == CAL_BRIT) { // one byte values are signed, so take absolute value for index index = (int) inputPixel + 128; } else { // otherwise scale down the 1K possible 15 bit values to an index index = (int) inputPixel / scale; } //System.out.println("xxx band = "+band+" index = "+index+" scale="+scale+ " inputPixel"+inputPixel); if (!(Float.isNaN(lookupTable[band - 1][index]))) { return (lookupTable[band - 1][index]); } // validate, then calibrate for each combination starting with cur type switch (curCalType) { case CAL_RAW: outputData = inputPixel; // if they want raw, just break right away if (calTypeOut == CAL_RAW) { break; } // convert to radiance if ((sid % 2) == 0) { outputData = inputPixel / scale; } outputData = (outputData - bias) / gain; // if they want radiance we are done if (calTypeOut == CAL_RAD) { break; } // otherwise, convert to temperature outputData = radToTemp(outputData, band, sid); // if they want temperature, break here if (calTypeOut == CAL_TEMP) { break; } // compute brightness from temperature if (outputData >= 242.0f) { outputData = Math.max(660 - (int) (outputData * 2), 0); } else { outputData = Math.min(418 - (int) outputData, 255); } // if they want brightness, break here if (calTypeOut == CAL_BRIT) { break; } break; case CAL_RAD: outputData = inputPixel; break; case CAL_ALB: outputData = inputPixel; break; case CAL_TEMP: outputData = inputPixel; break; case CAL_BRIT: outputData = inputPixel; break; } lookupTable[band - 1][index] = outputData; return outputData; } }
true
true
public float calibrate ( float inputPixel, int band, int calTypeOut ) { float outputData = 0.0f; //System.out.println("#### input pixel="+inputPixel); //System.out.println("#### cal band = "+band); //System.out.println("#### len lookup = "+lookupTable.length+" "+lookupTable[3].length); // load gain and bias constants based on band requested if (band != bandNum) { bandNum = band; if ((sid % 2) == 0) { if (band == 1) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = irGainCoef[0][band - 2]; bias = irBiasCoef[0][band - 2]; //System.out.println("#### band="+band+" gain="+gain+" bias"+bias); } scale = 32; gain = 5.2f; bias = 68.f; } else { if (band == 19) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = sGainCoef[band - 1]; bias = sBiasCoef[band - 1]; } scale = 2; } } // check lookup table first, if there is an entry, use it if (curCalType == CAL_BRIT) { // one byte values are signed, so take absolute value for index index = (int) inputPixel + 128; } else { // otherwise scale down the 1K possible 15 bit values to an index index = (int) inputPixel / scale; } //System.out.println("xxx band = "+band+" index = "+index+" scale="+scale+ " inputPixel"+inputPixel); if (!(Float.isNaN(lookupTable[band - 1][index]))) { return (lookupTable[band - 1][index]); } // validate, then calibrate for each combination starting with cur type switch (curCalType) { case CAL_RAW: outputData = inputPixel; // if they want raw, just break right away if (calTypeOut == CAL_RAW) { break; } // convert to radiance if ((sid % 2) == 0) { outputData = inputPixel / scale; } outputData = (outputData - bias) / gain; // if they want radiance we are done if (calTypeOut == CAL_RAD) { break; } // otherwise, convert to temperature outputData = radToTemp(outputData, band, sid); // if they want temperature, break here if (calTypeOut == CAL_TEMP) { break; } // compute brightness from temperature if (outputData >= 242.0f) { outputData = Math.max(660 - (int) (outputData * 2), 0); } else { outputData = Math.min(418 - (int) outputData, 255); } // if they want brightness, break here if (calTypeOut == CAL_BRIT) { break; } break; case CAL_RAD: outputData = inputPixel; break; case CAL_ALB: outputData = inputPixel; break; case CAL_TEMP: outputData = inputPixel; break; case CAL_BRIT: outputData = inputPixel; break; } lookupTable[band - 1][index] = outputData; return outputData; }
public float calibrate ( float inputPixel, int band, int calTypeOut ) { float outputData = 0.0f; //System.out.println("#### input pixel="+inputPixel); //System.out.println("#### cal band = "+band); //System.out.println("#### len lookup = "+lookupTable.length+" "+lookupTable[3].length); // load gain and bias constants based on band requested if (band != bandNum) { bandNum = band; if ((sid % 2) == 0) { if (band == 1) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = irGainCoef[0][band - 2]; bias = irBiasCoef[0][band - 2]; //System.out.println("#### band="+band+" gain="+gain+" bias"+bias); } scale = 32; } else { if (band == 19) { gain = visGain1Coef[0]; bias = visBiasCoef[0]; } else { gain = sGainCoef[band - 1]; bias = sBiasCoef[band - 1]; } scale = 2; } } // check lookup table first, if there is an entry, use it if (curCalType == CAL_BRIT) { // one byte values are signed, so take absolute value for index index = (int) inputPixel + 128; } else { // otherwise scale down the 1K possible 15 bit values to an index index = (int) inputPixel / scale; } //System.out.println("xxx band = "+band+" index = "+index+" scale="+scale+ " inputPixel"+inputPixel); if (!(Float.isNaN(lookupTable[band - 1][index]))) { return (lookupTable[band - 1][index]); } // validate, then calibrate for each combination starting with cur type switch (curCalType) { case CAL_RAW: outputData = inputPixel; // if they want raw, just break right away if (calTypeOut == CAL_RAW) { break; } // convert to radiance if ((sid % 2) == 0) { outputData = inputPixel / scale; } outputData = (outputData - bias) / gain; // if they want radiance we are done if (calTypeOut == CAL_RAD) { break; } // otherwise, convert to temperature outputData = radToTemp(outputData, band, sid); // if they want temperature, break here if (calTypeOut == CAL_TEMP) { break; } // compute brightness from temperature if (outputData >= 242.0f) { outputData = Math.max(660 - (int) (outputData * 2), 0); } else { outputData = Math.min(418 - (int) outputData, 255); } // if they want brightness, break here if (calTypeOut == CAL_BRIT) { break; } break; case CAL_RAD: outputData = inputPixel; break; case CAL_ALB: outputData = inputPixel; break; case CAL_TEMP: outputData = inputPixel; break; case CAL_BRIT: outputData = inputPixel; break; } lookupTable[band - 1][index] = outputData; return outputData; }
diff --git a/GameIO.java b/GameIO.java index 4ffd788..241a31b 100644 --- a/GameIO.java +++ b/GameIO.java @@ -1,173 +1,171 @@ import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.concurrent.BlockingQueue; import java.util.regex.Pattern; import java.util.regex.Matcher; public class GameIO { Client client; public GameIO(Client client) { this.client = client; this.client.write("launch;"); } public void execute() { final Client.Events src = this.client.addListener(); Thread listener = new Thread(new Runnable() { public void run() { while (true) { if (Thread.interrupted()) { return; } try { parseOutput(src.take()); } catch (Exception e) { throw new RuntimeException(e); } } } }); listener.start(); try { byte buf[] = new byte[1024]; int read_cnt; while ((read_cnt = System.in.read(buf)) > 0) { if (!listener.isAlive()) { return; - } else { - System.out.println(listener.getState()); } StringTokenizer commands = new StringTokenizer(new String(buf, 0, read_cnt), ";", true); while (commands.countTokens() > 1) { String command = commands.nextToken(); command += commands.nextToken(); System.out.println("Cmd: " + command); if (command.equals("p;")) { try { this.print(); } catch (Exception e) { e.printStackTrace(System.out); } } else { client.write(command); } } } } catch (Exception e) { throw new RuntimeException(e); } finally { listener.interrupt(); } } // now state. int pid; int round; int cell_size; int map_height; int map_width; List<String> map; int time; boolean dead; Point me; Point bomb; static Pattern head; static Pattern map_symbols; static Pattern sapka_info_pat; static Pattern changes_part; private synchronized void parseOutput(String output) { Matcher matcher = head.matcher(output); if (!matcher.find()) { System.out.println("Output: " + output); return; } if (matcher.group(2) != null) { this.pid = Integer.parseInt(matcher.group(3)); } else if (matcher.group(4) != null) { this.round = Integer.parseInt(matcher.group(5)); this.cell_size = Integer.parseInt(matcher.group(6)); this.map = new ArrayList<String>(); Matcher map_matcher = map_symbols.matcher(matcher.group(7)); this.map_height = 0; this.map_width = 0; while (map_matcher.find()) { this.map_height++; String line = map_matcher.group(1); if (this.map_width == 0) { this.map_width = line.length(); } this.map.add(line); } } else if (matcher.group(8) != null) { this.time = Integer.parseInt(matcher.group(9)); Matcher sapka_matcher = sapka_info_pat.matcher(matcher.group(10)); while (sapka_matcher.find()) { if (Integer.parseInt(sapka_matcher.group(1)) != this.pid) { continue; } if (sapka_matcher.group(2).equals("dead")) { this.dead = true; break; } int x = Integer.parseInt(sapka_matcher.group(3)); int y = Integer.parseInt(sapka_matcher.group(4)); this.me = new Point(x, y); } } } private synchronized void print() { try { for (String line: this.map) { System.out.println(line); } if (this.me != null) { System.out.println("Me: " + this.me.x + ", " + this.me.y); } } catch (Exception e) { throw new RuntimeException(e); } } static { head = Pattern.compile( "^(" // 1 + "(PID([0-9]*)&[^;]*)" // 2,3 + "|(START([0-9]*)&([0-9]+)\r\n([^;]+))" // 4,5,6,7 + "|(T([0-9]*)&([^;&]*)&([^;&]*)(&[^;])?)" // 8,9,10,11,12 + ");"); /* + "(REND (-?[0-9]*))" // 10,11 + "(GEND (-?[0-9]*))" // 12,13 */ map_symbols = Pattern.compile("^([\\.Xw]+)$", Pattern.MULTILINE); sapka_info_pat = Pattern.compile("P([0-9]+) " + "(dead|([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)( i)?)(,|$)"); } }
true
true
public void execute() { final Client.Events src = this.client.addListener(); Thread listener = new Thread(new Runnable() { public void run() { while (true) { if (Thread.interrupted()) { return; } try { parseOutput(src.take()); } catch (Exception e) { throw new RuntimeException(e); } } } }); listener.start(); try { byte buf[] = new byte[1024]; int read_cnt; while ((read_cnt = System.in.read(buf)) > 0) { if (!listener.isAlive()) { return; } else { System.out.println(listener.getState()); } StringTokenizer commands = new StringTokenizer(new String(buf, 0, read_cnt), ";", true); while (commands.countTokens() > 1) { String command = commands.nextToken(); command += commands.nextToken(); System.out.println("Cmd: " + command); if (command.equals("p;")) { try { this.print(); } catch (Exception e) { e.printStackTrace(System.out); } } else { client.write(command); } } } } catch (Exception e) { throw new RuntimeException(e); } finally { listener.interrupt(); } }
public void execute() { final Client.Events src = this.client.addListener(); Thread listener = new Thread(new Runnable() { public void run() { while (true) { if (Thread.interrupted()) { return; } try { parseOutput(src.take()); } catch (Exception e) { throw new RuntimeException(e); } } } }); listener.start(); try { byte buf[] = new byte[1024]; int read_cnt; while ((read_cnt = System.in.read(buf)) > 0) { if (!listener.isAlive()) { return; } StringTokenizer commands = new StringTokenizer(new String(buf, 0, read_cnt), ";", true); while (commands.countTokens() > 1) { String command = commands.nextToken(); command += commands.nextToken(); System.out.println("Cmd: " + command); if (command.equals("p;")) { try { this.print(); } catch (Exception e) { e.printStackTrace(System.out); } } else { client.write(command); } } } } catch (Exception e) { throw new RuntimeException(e); } finally { listener.interrupt(); } }
diff --git a/src/main/java/com/rimerosolutions/buildtools/ant/wrapper/BootstrapMainStarter.java b/src/main/java/com/rimerosolutions/buildtools/ant/wrapper/BootstrapMainStarter.java index 9c346a0..e6ab2a5 100644 --- a/src/main/java/com/rimerosolutions/buildtools/ant/wrapper/BootstrapMainStarter.java +++ b/src/main/java/com/rimerosolutions/buildtools/ant/wrapper/BootstrapMainStarter.java @@ -1,69 +1,69 @@ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rimerosolutions.buildtools.ant.wrapper; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * @author Hans Dockter */ public class BootstrapMainStarter { public void start(String[] args, File antHome) throws Exception { File[] antJars = findBootstrapJars(antHome); URL[] jarUrls = new URL[antJars.length]; for (int i = 0; i < antJars.length; i++) { jarUrls[i] = antJars[i].toURI().toURL(); } URLClassLoader contextClassLoader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader().getParent()); Thread.currentThread().setContextClassLoader(contextClassLoader); Class<?> mainClass = contextClassLoader.loadClass("org.apache.tools.ant.Main"); mainClass.getMethod("main", String[].class).invoke(null, new Object[] { args }); } private File[] findBootstrapJars(File antHome) { List<File> bootstrapJars = new ArrayList<File>(); for (File file : new File(antHome, "lib").listFiles()) { - if (file.getName().endsWith("launcher.jar")) { + if (file.getName().endsWith(".jar")) { bootstrapJars.add(file); } } String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { File toolsJar = new File(javaHome, "lib/tools.jar"); File toolsJarOsx = new File(javaHome, "lib/classes.jar"); if (toolsJar.exists()) { bootstrapJars.add(toolsJar); } if (toolsJarOsx.exists()) { bootstrapJars.add(toolsJarOsx); } } return bootstrapJars.toArray(new File[bootstrapJars.size()]); } }
true
true
private File[] findBootstrapJars(File antHome) { List<File> bootstrapJars = new ArrayList<File>(); for (File file : new File(antHome, "lib").listFiles()) { if (file.getName().endsWith("launcher.jar")) { bootstrapJars.add(file); } } String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { File toolsJar = new File(javaHome, "lib/tools.jar"); File toolsJarOsx = new File(javaHome, "lib/classes.jar"); if (toolsJar.exists()) { bootstrapJars.add(toolsJar); } if (toolsJarOsx.exists()) { bootstrapJars.add(toolsJarOsx); } } return bootstrapJars.toArray(new File[bootstrapJars.size()]); }
private File[] findBootstrapJars(File antHome) { List<File> bootstrapJars = new ArrayList<File>(); for (File file : new File(antHome, "lib").listFiles()) { if (file.getName().endsWith(".jar")) { bootstrapJars.add(file); } } String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { File toolsJar = new File(javaHome, "lib/tools.jar"); File toolsJarOsx = new File(javaHome, "lib/classes.jar"); if (toolsJar.exists()) { bootstrapJars.add(toolsJar); } if (toolsJarOsx.exists()) { bootstrapJars.add(toolsJarOsx); } } return bootstrapJars.toArray(new File[bootstrapJars.size()]); }
diff --git a/src/dfEditor/CustomNode.java b/src/dfEditor/CustomNode.java index 4f07819..b01db2e 100644 --- a/src/dfEditor/CustomNode.java +++ b/src/dfEditor/CustomNode.java @@ -1,79 +1,79 @@ package dfEditor; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.Color; public class CustomNode extends DefaultMutableTreeNode { private Color colour = Color.BLUE; private int childDirUniqueID; private int childLeafUniqueID; private boolean isLeaf; private Object _object; public CustomNode(Object userObject, boolean allowsChildren) { super(userObject, allowsChildren); isLeaf = !allowsChildren; childDirUniqueID = 0; childLeafUniqueID = 0; } @Override public boolean isLeaf() { return isLeaf; } public String suggestNameForChildLeaf() { return new String(""+childLeafUniqueID++); } public String suggestNameForChildDir() { return new String(""+childDirUniqueID++); } public Color getColour() { return colour; } public void setColour(Color c) { //System.out.println("setting colour of " + this + " to " + c); colour = c; } public void setCustomObject(final Object aObj) { _object = aObj; } public final Object getCustomObject() { return _object; } public String getFullPathName() { String path = new String(""); Object[] objects = this.getUserObjectPath(); for (int i=0; i<objects.length; ++i) { path += objects[i]; - if (i < objects.length-1 && i > 0 || !this.isLeaf()) + if (i < objects.length-1 || !this.isLeaf()) path += "/"; } return path; } }
true
true
public String getFullPathName() { String path = new String(""); Object[] objects = this.getUserObjectPath(); for (int i=0; i<objects.length; ++i) { path += objects[i]; if (i < objects.length-1 && i > 0 || !this.isLeaf()) path += "/"; } return path; }
public String getFullPathName() { String path = new String(""); Object[] objects = this.getUserObjectPath(); for (int i=0; i<objects.length; ++i) { path += objects[i]; if (i < objects.length-1 || !this.isLeaf()) path += "/"; } return path; }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/InitializableVariableBuilder.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/InitializableVariableBuilder.java index 9553d449..b6b011dd 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/InitializableVariableBuilder.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/databuilder/InitializableVariableBuilder.java @@ -1,72 +1,74 @@ package jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder; import java.util.Stack; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.expression.ExpressionElement; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.expression.ExpressionElementManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.StateChangeEvent; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.VariableDefinitionStateManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.StateChangeEvent.StateChangeEventType; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.statemanager.VariableDefinitionStateManager.VARIABLE_STATE; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.AstVisitEvent; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExpressionInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.UnitInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedExpressionInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedUnitInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedVariableInfo; public abstract class InitializableVariableBuilder<TVar extends UnresolvedVariableInfo, TUnit extends UnresolvedUnitInfo<? extends UnitInfo>> extends VariableBuilder<TVar, TUnit> { public InitializableVariableBuilder(BuildDataManager buildDataManager, final ExpressionElementManager expressionManager, VariableDefinitionStateManager variableStateManager, ModifiersBuilder modifiersBuilder, TypeBuilder typeBuilder, NameBuilder nameBuilder) { super(buildDataManager, variableStateManager, modifiersBuilder, typeBuilder, nameBuilder); if (null == expressionManager) { throw new IllegalArgumentException("expressionManager is null"); } this.expressionManager = expressionManager; } @Override public void stateChangend(final StateChangeEvent<AstVisitEvent> event) { super.stateChangend(event); final StateChangeEventType eventType = event.getType(); if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_DEF)) { // �ϐ��̏������������邩�ǂ����킩��Ȃ��̂łƂ肠����null������� this.builtInitializerStack.push(null); } else if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_INITIALIZER)) { // �������������݂����̂Ő錾���ɓ������Ƃ��ɃX�^�b�N�ɐς�null������ assert this.builtInitializerStack.peek() == null : "Illegal state: incorrect stack state"; this.builtInitializerStack.pop(); } else if (eventType.equals(VARIABLE_STATE.EXIT_VARIABLE_INITIALIZER)) { ExpressionElement lastExpression = expressionManager.getLastPoppedExpressionElement(); assert (lastExpression.getUsage() instanceof UnresolvedExpressionInfo) : "Illegal state: variable initilizer was not a expression"; if(null != lastExpression) { this.builtInitializerStack .push((UnresolvedExpressionInfo<? extends ExpressionInfo>) lastExpression .getUsage()); + } else { + this.builtInitializerStack.push(null); } } } /** * �\�z���������������i�[���Ă����X�^�b�N */ protected final Stack<UnresolvedExpressionInfo<? extends ExpressionInfo>> builtInitializerStack = new Stack<UnresolvedExpressionInfo<? extends ExpressionInfo>>(); protected final ExpressionElementManager expressionManager; }
true
true
public void stateChangend(final StateChangeEvent<AstVisitEvent> event) { super.stateChangend(event); final StateChangeEventType eventType = event.getType(); if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_DEF)) { // �ϐ��̏������������邩�ǂ����킩��Ȃ��̂łƂ肠����null������� this.builtInitializerStack.push(null); } else if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_INITIALIZER)) { // �������������݂����̂Ő錾���ɓ������Ƃ��ɃX�^�b�N�ɐς�null������ assert this.builtInitializerStack.peek() == null : "Illegal state: incorrect stack state"; this.builtInitializerStack.pop(); } else if (eventType.equals(VARIABLE_STATE.EXIT_VARIABLE_INITIALIZER)) { ExpressionElement lastExpression = expressionManager.getLastPoppedExpressionElement(); assert (lastExpression.getUsage() instanceof UnresolvedExpressionInfo) : "Illegal state: variable initilizer was not a expression"; if(null != lastExpression) { this.builtInitializerStack .push((UnresolvedExpressionInfo<? extends ExpressionInfo>) lastExpression .getUsage()); } } }
public void stateChangend(final StateChangeEvent<AstVisitEvent> event) { super.stateChangend(event); final StateChangeEventType eventType = event.getType(); if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_DEF)) { // �ϐ��̏������������邩�ǂ����킩��Ȃ��̂łƂ肠����null������� this.builtInitializerStack.push(null); } else if (eventType.equals(VARIABLE_STATE.ENTER_VARIABLE_INITIALIZER)) { // �������������݂����̂Ő錾���ɓ������Ƃ��ɃX�^�b�N�ɐς�null������ assert this.builtInitializerStack.peek() == null : "Illegal state: incorrect stack state"; this.builtInitializerStack.pop(); } else if (eventType.equals(VARIABLE_STATE.EXIT_VARIABLE_INITIALIZER)) { ExpressionElement lastExpression = expressionManager.getLastPoppedExpressionElement(); assert (lastExpression.getUsage() instanceof UnresolvedExpressionInfo) : "Illegal state: variable initilizer was not a expression"; if(null != lastExpression) { this.builtInitializerStack .push((UnresolvedExpressionInfo<? extends ExpressionInfo>) lastExpression .getUsage()); } else { this.builtInitializerStack.push(null); } } }
diff --git a/sling/core/src/main/java/org/apache/sling/core/impl/parameters/EncodedRequestParameter.java b/sling/core/src/main/java/org/apache/sling/core/impl/parameters/EncodedRequestParameter.java index 14d9812076..28ac62f08c 100644 --- a/sling/core/src/main/java/org/apache/sling/core/impl/parameters/EncodedRequestParameter.java +++ b/sling/core/src/main/java/org/apache/sling/core/impl/parameters/EncodedRequestParameter.java @@ -1,121 +1,121 @@ /* * 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.sling.core.impl.parameters; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; /** * The <code>EncodedRequestParameter</code> TODO */ public class EncodedRequestParameter extends AbstractEncodedParameter { private byte[] content; EncodedRequestParameter(String encoding) { super(encoding); this.content = Util.NO_CONTENT; } void setContent(byte[] content) { this.content = content; super.setEncoding(this.getEncoding()); } /** * @see org.apache.sling.api.request.RequestParameter#get() */ public byte[] get() { return this.content; } /** * @see org.apache.sling.api.request.RequestParameter#getContentType() */ public String getContentType() { // none known for www-form-encoded parameters return null; } /** * @see org.apache.sling.api.request.RequestParameter#getInputStream() */ public InputStream getInputStream() { return new ByteArrayInputStream(this.get()); } /** * @see org.apache.sling.api.request.RequestParameter#getFileName() */ public String getFileName() { // no original file name return null; } /** * @see org.apache.sling.api.request.RequestParameter#getSize() */ public long getSize() { return this.get().length; } /** * @see org.apache.sling.api.request.RequestParameter#getString() */ public String getString() { return this.getEncodedString(); } /** * @see org.apache.sling.api.request.RequestParameter#getString(java.lang.String) */ public String getString(String encoding) throws UnsupportedEncodingException { return new String(this.get(), encoding); } /** * @see org.apache.sling.api.request.RequestParameter#isFormField() */ public boolean isFormField() { // www-form-encoded are always form fields return true; } public String toString() { return this.getString(); } protected String decode(byte[] data, String encoding) { if (encoding != null) { try { String value = new String(data, Util.ENCODING_DIRECT); - return URLDecoder.decode(value, encoding); + return value; // URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException uue) { // not expected, use default encoding anyway ... } catch (IllegalArgumentException iae) { // due to illegal encoding in value, ignore for now } } // if still here, use platform default encoding return new String(data); } }
true
true
protected String decode(byte[] data, String encoding) { if (encoding != null) { try { String value = new String(data, Util.ENCODING_DIRECT); return URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException uue) { // not expected, use default encoding anyway ... } catch (IllegalArgumentException iae) { // due to illegal encoding in value, ignore for now } } // if still here, use platform default encoding return new String(data); }
protected String decode(byte[] data, String encoding) { if (encoding != null) { try { String value = new String(data, Util.ENCODING_DIRECT); return value; // URLDecoder.decode(value, encoding); } catch (UnsupportedEncodingException uue) { // not expected, use default encoding anyway ... } catch (IllegalArgumentException iae) { // due to illegal encoding in value, ignore for now } } // if still here, use platform default encoding return new String(data); }
diff --git a/ActiveObjects/src/net/java/ao/EntityManager.java b/ActiveObjects/src/net/java/ao/EntityManager.java index 17d9117..55e452b 100644 --- a/ActiveObjects/src/net/java/ao/EntityManager.java +++ b/ActiveObjects/src/net/java/ao/EntityManager.java @@ -1,1026 +1,1032 @@ /* * Copyright 2007 Daniel Spiewak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.ao; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; 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.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import net.java.ao.cache.Cache; import net.java.ao.cache.CacheLayer; import net.java.ao.cache.RAMCache; import net.java.ao.cache.RAMRelationsCache; import net.java.ao.cache.RelationsCache; import net.java.ao.schema.AutoIncrement; import net.java.ao.schema.CamelCaseFieldNameConverter; import net.java.ao.schema.CamelCaseTableNameConverter; import net.java.ao.schema.FieldNameConverter; import net.java.ao.schema.SchemaGenerator; import net.java.ao.schema.TableNameConverter; import net.java.ao.types.TypeManager; /** * <p>The root control class for the entire ActiveObjects API. <code>EntityManager</code> * is the source of all {@link RawEntity} objects, as well as the dispatch layer between the entities, * the pluggable table name converters, and the database abstraction layers. This is the * entry point for any use of the API.</p> * * <p><code>EntityManager</code> is designed to be used in an instance fashion with each * instance corresponding to a single database. Thus, rather than a singleton instance or a * static factory method, <code>EntityManager</code> does have a proper constructor. Any * static instance management is left up to the developer using the API.</p> * * <p>As a side note, ActiveObjects can optionally log all SQL queries prior to their * execution. This query logging is done with the Java Logging API using the {@link Logger} * instance for the <code>net.java.ao</code> package. This logging is disabled by default * by the <code>EntityManager</code> static initializer. Thus, if it is desirable to log the * SQL statements, the <code>Logger</code> level must be set to {@link Level.FINE} * <i>after</i> the <code>EntityManager</code> class is first used. This usually means * setting the log level after the constructer has been called.</p> * * @author Daniel Spiewak */ public class EntityManager { static { Logger.getLogger("net.java.ao").setLevel(Level.OFF); } private final DatabaseProvider provider; private final boolean weaklyCache; private Map<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>> proxies; private final ReadWriteLock proxyLock = new ReentrantReadWriteLock(); private Map<CacheKey<?>, Reference<RawEntity<?>>> entityCache; private final ReadWriteLock entityCacheLock = new ReentrantReadWriteLock(); private Cache cache; private final ReadWriteLock cacheLock = new ReentrantReadWriteLock(); private TableNameConverter tableNameConverter; private final ReadWriteLock tableNameConverterLock = new ReentrantReadWriteLock(); private FieldNameConverter fieldNameConverter; private final ReadWriteLock fieldNameConverterLock = new ReentrantReadWriteLock(); private PolymorphicTypeMapper typeMapper; private final ReadWriteLock typeMapperLock = new ReentrantReadWriteLock(); private Map<Class<? extends ValueGenerator<?>>, ValueGenerator<?>> valGenCache; private final ReadWriteLock valGenCacheLock = new ReentrantReadWriteLock(); private final RelationsCache relationsCache = new RAMRelationsCache(); /** * Creates a new instance of <code>EntityManager</code> using the specified * {@link DatabaseProvider}. This constructor intializes the entity cache, as well * as creates the default {@link TableNameConverter} (the default is * {@link CamelCaseTableNameConverter}, which is non-pluralized) and the default * {@link FieldNameConverter} ({@link CamelCaseFieldNameConverter}). The provider * instance is immutable once set using this constructor. By default (using this * constructor), all entities are strongly cached, meaning references are held to * the instances, preventing garbage collection. * * @param provider The {@link DatabaseProvider} to use in all database operations. * @see #EntityManager(DatabaseProvider, boolean) */ public EntityManager(DatabaseProvider provider) { this(provider, false); } /** * Creates a new instance of <code>EntityManager</code> using the specified * {@link DatabaseProvider}. This constructor initializes the entity and proxy * caches based on the given boolean value. If <code>true</code>, the entities * will be weakly cached, not maintaining a reference allowing for garbage * collection. If <code>false</code>, then strong caching will be used, preventing * garbage collection and ensuring the cache is logically complete. If you are * concerned about memory, specify <code>true</code>. Otherwise, for * maximum performance use <code>false</code> (highly recomended). * * @param provider The {@link DatabaseProvider} to use in all database operations. * @param weaklyCache Whether or not to use {@link WeakReference} in the entity * cache. If <code>false</code>, then {@link SoftReference} will be used. */ public EntityManager(DatabaseProvider provider, boolean weaklyCache) { this.provider = provider; this.weaklyCache = weaklyCache; if (weaklyCache) { proxies = new WeakHashMap<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>(); } else { proxies = new SoftHashMap<RawEntity<?>, EntityProxy<? extends RawEntity<?>, ?>>(); } entityCache = new HashMap<CacheKey<?>, Reference<RawEntity<?>>>(); cache = new RAMCache(); valGenCache = new HashMap<Class<? extends ValueGenerator<?>>, ValueGenerator<?>>(); tableNameConverter = new CamelCaseTableNameConverter(); fieldNameConverter = new CamelCaseFieldNameConverter(); typeMapper = new DefaultPolymorphicTypeMapper(new HashMap<Class<? extends RawEntity<?>>, String>()); } /** * <p>Creates a new instance of <code>EntityManager</code> by auto-magically * finding a {@link DatabaseProvider} instance for the specified JDBC URI, username * and password. The auto-magically determined instance is pooled by default * (if a supported connection pooling library is available on the classpath).</p> * * <p>The actual auto-magical parsing code isn't contained within this method, * but in {@link DatabaseProvider#getInstance(String, String, String)}. This way, * it is possible to use the parsing logic to get a <code>DatabaseProvider</code> * instance separate from <code>EntityManager</code> if necessary.</p> * * @param uri The JDBC URI to use for the database connection. * @param username The username to use in authenticating the database connection. * @param password The password to use in authenticating the database connection. * @see #EntityManager(DatabaseProvider) * @see net.java.ao.DatabaseProvider#getInstance(String, String, String) */ public EntityManager(String uri, String username, String password) { this(DatabaseProvider.getInstance(uri, username, password)); } /** * Convenience method to create the schema for the specified entities * using the current settings (table/field name converter and database provider). * * @see net.java.ao.schema.SchemaGenerator#migrate(DatabaseProvider, TableNameConverter, FieldNameConverter, Class...) */ public void migrate(Class<? extends RawEntity<?>>... entities) throws SQLException { tableNameConverterLock.readLock().lock(); fieldNameConverterLock.readLock().lock(); try { SchemaGenerator.migrate(provider, tableNameConverter, fieldNameConverter, entities); } finally { fieldNameConverterLock.readLock().unlock(); tableNameConverterLock.readLock().unlock(); } } /** * Flushes all value caches contained within entities controlled by this <code>EntityManager</code> * instance. This does not actually remove the entities from the instance cache maintained * within this class. Rather, it simply dumps all of the field values cached within the entities * themselves (with the exception of the primary key value). This should be used in the case * of a complex process outside AO control which may have changed values in the database. If * it is at all possible to determine precisely which rows have been changed, the {@link #flush(RawEntity...)} * method should be used instead. */ public void flushAll() { proxyLock.readLock().lock(); try { for (EntityProxy<? extends RawEntity<?>, ?> proxy : proxies.values()) { proxy.flushCache(); } } finally { proxyLock.readLock().unlock(); } relationsCache.flush(); } /** * Flushes the value caches of the specified entities along with all of the relevant * relations cache entries. This should be called after a process outside of AO control * may have modified the values in the specified rows. This does not actually remove * the entity instances themselves from the instance cache. Rather, it just flushes all * of their internally cached values (with the exception of the primary key). */ public void flush(RawEntity<?>... entities) { proxyLock.readLock().lock(); try { List<Class<? extends RawEntity<?>>> types = new ArrayList<Class<? extends RawEntity<?>>>(entities.length); for (RawEntity<?> entity : entities) { types.add(entity.getEntityType()); proxies.get(entity).flushCache(); } relationsCache.remove(types.toArray(new Class[types.size()])); } finally { proxyLock.readLock().unlock(); } } /** * <p>Returns an array of entities of the specified type corresponding to the * varargs primary keys. If an in-memory reference already exists to a corresponding * entity (of the specified type and key), it is returned rather than creating * a new instance.</p> * * <p>No checks are performed to ensure that the key actually exists in the * database for the specified object. Thus, this method is solely a Java * memory state modifying method. There is no database access involved. * The upshot of this is that the method is very very fast. The flip side of * course is that one could conceivably maintain entities which reference * non-existant database rows.</p> * * @param type The type of the entities to retrieve. * @param keys The primary keys corresponding to the entities to retrieve. All * keys must be typed according to the generic type parameter of the entity's * {@link RawEntity} inheritence (if inheriting from {@link Entity}, this is <code>Integer</code> * or <code>int</code>). Thus, the <code>keys</code> array is type-checked at compile * time. * @return An array of entities of the given type corresponding with the specified primary keys. */ public <T extends RawEntity<K>, K> T[] get(Class<T> type, K... keys) { T[] back = (T[]) Array.newInstance(type, keys.length); int index = 0; for (K key : keys) { entityCacheLock.writeLock().lock(); try { // upcast to workaround bug in javac Reference<?> reference = entityCache.get(new CacheKey<K>(key, type)); Reference<T> ref = (Reference<T>) reference; T entity = (ref == null ? null : ref.get()); if (entity != null) { back[index++] = entity; } else { back[index++] = getAndInstantiate(type, key); } } finally { entityCacheLock.writeLock().unlock(); } } return back; } /** * Creates a new instance of the entity of the specified type corresponding to the * given primary key. This is used by {@link #get(Class, Object...)} to create the entity * if the instance is not found already in the cache. This method should not be * repurposed to perform any caching, since ActiveObjects already assumes that * the caching has been performed. * * @param type The type of the entity to create. * @param key The primary key corresponding to the entity instance required. * @return An entity instance of the specified type and primary key. */ protected <T extends RawEntity<K>, K> T getAndInstantiate(Class<T> type, K key) { EntityProxy<T, K> proxy = new EntityProxy<T, K>(this, type, key); T entity = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, proxy); proxyLock.writeLock().lock(); try { proxies.put(entity, proxy); } finally { proxyLock.writeLock().unlock(); } entityCache.put(new CacheKey<K>(key, type), createRef(entity)); return entity; } /** * Cleverly overloaded method to return a single entity of the specified type * rather than an array in the case where only one ID is passed. This method * meerly delegates the call to the overloaded <code>get</code> method * and functions as syntactical sugar. * * @param type The type of the entity instance to retrieve. * @param key The primary key corresponding to the entity to be retrieved. * @return An entity instance of the given type corresponding to the specified primary key. * @see #get(Class, Object...) */ public <T extends RawEntity<K>, K> T get(Class<T> type, K key) { return get(type, (K[]) new Object[] {key})[0]; } /** * <p>Creates a new entity of the specified type with the optionally specified * initial parameters. This method actually inserts a row into the table represented * by the entity type and returns the entity instance which corresponds to that * row.</p> * * <p>The {@link DBParam} object parameters are designed to allow the creation * of entities which have non-null fields which have no defalut or auto-generated * value. Insertion of a row without such field values would of course fail, * thus the need for db params. The db params can also be used to set * the values for any field in the row, leading to more compact code under * certain circumstances.</p> * * <p>Unless within a transaction, this method will commit to the database * immediately and exactly once per call. Thus, care should be taken in * the creation of large numbers of entities. There doesn't seem to be a more * efficient way to create large numbers of entities, however one should still * be aware of the performance implications.</p> * * <p>This method delegates the action INSERT action to * {@link DatabaseProvider#insertReturningKey(Connection, Class, String, boolean, String, DBParam...)}. * This is necessary because not all databases support the JDBC <code>RETURN_GENERATED_KEYS</code> * constant (e.g. PostgreSQL and HSQLDB). Thus, the database provider itself is * responsible for handling INSERTion and retrieval of the correct primary key * value.</p> * * @param type The type of the entity to INSERT. * @param params An optional varargs array of initial values for the fields in the row. These * values will be passed to the database within the INSERT statement. * @return The new entity instance corresponding to the INSERTed row. * @see net.java.ao.DBParam * @see net.java.ao.DatabaseProvider#insertReturningKey(Connection, Class, String, boolean, String, DBParam...) */ public <T extends RawEntity<K>, K> T create(Class<T> type, DBParam... params) throws SQLException { T back = null; String table = null; tableNameConverterLock.readLock().lock(); try { table = tableNameConverter.getName(type); } finally { tableNameConverterLock.readLock().unlock(); } Set<DBParam> listParams = new HashSet<DBParam>(); listParams.addAll(Arrays.asList(params)); fieldNameConverterLock.readLock().lock(); try { for (Method method : MethodFinder.getInstance().findAnnotation(Generator.class, type)) { Generator genAnno = method.getAnnotation(Generator.class); String field = fieldNameConverter.getName(method); ValueGenerator<?> generator; valGenCacheLock.writeLock().lock(); try { if (valGenCache.containsKey(genAnno.value())) { generator = valGenCache.get(genAnno.value()); } else { generator = genAnno.value().newInstance(); valGenCache.put(genAnno.value(), generator); } } catch (InstantiationException e) { continue; } catch (IllegalAccessException e) { continue; } finally { valGenCacheLock.writeLock().unlock(); } listParams.add(new DBParam(field, generator.generateValue(this))); } } finally { fieldNameConverterLock.readLock().unlock(); } Connection conn = getProvider().getConnection(); try { relationsCache.remove(type); Method pkMethod = Common.getPrimaryKeyMethod(type); back = get(type, provider.insertReturningKey(conn, Common.getPrimaryKeyClassType(type), Common.getPrimaryKeyField(type, getFieldNameConverter()), pkMethod.getAnnotation(AutoIncrement.class) != null, table, listParams.toArray(new DBParam[listParams.size()]))); } finally { conn.close(); } back.init(); return back; } /** * Creates and INSERTs a new entity of the specified type with the given map of * parameters. This method merely delegates to the {@link #create(Class, DBParam...)} * method. The idea behind having a separate convenience method taking a map is in * circumstances with large numbers of parameters or for people familiar with the * anonymous inner class constructor syntax who might be more comfortable with * creating a map than with passing a number of objects. * * @param type The type of the entity to INSERT. * @param params A map of parameters to pass to the INSERT. * @return The new entity instance corresponding to the INSERTed row. * @see #create(Class, DBParam...) */ public <T extends RawEntity<K>, K> T create(Class<T> type, Map<String, Object> params) throws SQLException { DBParam[] arrParams = new DBParam[params.size()]; int i = 0; for (String key : params.keySet()) { arrParams[i++] = new DBParam(key, params.get(key)); } return create(type, arrParams); } /** * <p>Deletes the specified entities from the database. DELETE statements are * called on the rows in the corresponding tables and the entities are removed * from the instance cache. The entity instances themselves are not invalidated, * but it doesn't even make sense to continue using the instance without a row * with which it is paired.</p> * * <p>This method does attempt to group the DELETE statements on a per-type * basis. Thus, if you pass 5 instances of <code>EntityA</code> and two * instances of <code>EntityB</code>, the following SQL prepared statements * will be invoked:</p> * * <pre>DELETE FROM entityA WHERE id IN (?,?,?,?,?); * DELETE FROM entityB WHERE id IN (?,?);</pre> * * <p>Thus, this method scales very well for large numbers of entities grouped * into types. However, the execution time increases linearly for each entity of * unique type.</p> * * @param entities A varargs array of entities to delete. Method returns immediately * if length == 0. */ @SuppressWarnings("unchecked") public void delete(RawEntity<?>... entities) throws SQLException { if (entities.length == 0) { return; } Map<Class<? extends RawEntity<?>>, List<RawEntity<?>>> organizedEntities = new HashMap<Class<? extends RawEntity<?>>, List<RawEntity<?>>>(); for (RawEntity<?> entity : entities) { Class<? extends RawEntity<?>> type = getProxyForEntity(entity).getType(); if (!organizedEntities.containsKey(type)) { organizedEntities.put(type, new LinkedList<RawEntity<?>>()); } organizedEntities.get(type).add(entity); } entityCacheLock.writeLock().lock(); try { Connection conn = getProvider().getConnection(); try { for (Class<? extends RawEntity<?>> type : organizedEntities.keySet()) { List<RawEntity<?>> entityList = organizedEntities.get(type); StringBuilder sql = new StringBuilder("DELETE FROM "); tableNameConverterLock.readLock().lock(); try { sql.append(tableNameConverter.getName(type)); } finally { tableNameConverterLock.readLock().unlock(); } sql.append(" WHERE ").append(Common.getPrimaryKeyField(type, getFieldNameConverter())).append(" IN (?"); for (int i = 1; i < entityList.size(); i++) { sql.append(",?"); } sql.append(')'); Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString()); PreparedStatement stmt = conn.prepareStatement(sql.toString()); int index = 1; for (RawEntity<?> entity : entityList) { TypeManager.getInstance().getType((Class) entity.getEntityType()).putToDatabase(index++, stmt, entity); } relationsCache.remove(type); stmt.executeUpdate(); stmt.close(); } } finally { conn.close(); } for (RawEntity<?> entity : entities) { entityCache.remove(new CacheKey<Object>(Common.getPrimaryKeyValue(entity), (Class<? extends RawEntity<Object>>) entity.getEntityType())); } proxyLock.writeLock().lock(); try { for (RawEntity<?> entity : entities) { proxies.remove(entity); } } finally { proxyLock.writeLock().unlock(); } } finally { entityCacheLock.writeLock().unlock(); } } /** * Returns all entities of the given type. This actually peers the call to * the {@link #find(Class, Query)} method. * * @param type The type of entity to retrieve. * @return An array of all entities which correspond to the given type. */ public <T extends RawEntity<K>, K> T[] find(Class<T> type) throws SQLException { return find(type, Query.select()); } /** * <p>Convenience method to select all entities of the given type with the * specified, parameterized criteria. The <code>criteria</code> String * specified is appended to the SQL prepared statement immediately * following the <code>WHERE</code>.</p> * * <p>Example:</p> * * <pre>manager.find(Person.class, "name LIKE ? OR age &gt; ?", "Joe", 9);</pre> * * <p>This actually delegates the call to the {@link #find(Class, Query)} * method, properly parameterizing the {@link Query} object.</p> * * @param type The type of the entities to retrieve. * @param criteria A parameterized WHERE statement used to determine the results. * @param parameters A varargs array of parameters to be passed to the executed * prepared statement. The length of this array <i>must</i> match the number of * parameters (denoted by the '?' char) in the <code>criteria</code>. * @return An array of entities of the given type which match the specified criteria. */ public <T extends RawEntity<K>, K> T[] find(Class<T> type, String criteria, Object... parameters) throws SQLException { return find(type, Query.select().where(criteria, parameters)); } /** * <p>Selects all entities matching the given type and {@link Query}. By default, the * entities will be created based on the values within the primary key field for the * specified type (this is usually the desired behavior).</p> * * <p>Example:</p> * * <pre>manager.find(Person.class, Query.select().where("name LIKE ? OR age &gt; ?", "Joe", 9).limit(10));</pre> * * <p>This method delegates the call to {@link #find(Class, String, Query)}, passing the * primary key field for the given type as the <code>String</code> parameter.</p> * * @param type The type of the entities to retrieve. * @param query The {@link Query} instance to be used to determine the results. * @return An array of entities of the given type which match the specified query. */ public <T extends RawEntity<K>, K> T[] find(Class<T> type, Query query) throws SQLException { String selectField = Common.getPrimaryKeyField(type, getFieldNameConverter()); query.resolveFields(type, getFieldNameConverter()); String[] fields = query.getFields(); if (fields.length == 1) { selectField = fields[0]; } return find(type, selectField, query); } /** * <p>Selects all entities of the specified type which match the given * <code>Query</code>. This method creates a <code>PreparedStatement</code> * using the <code>Query</code> instance specified against the table * represented by the given type. This query is then executed (with the * parameters specified in the query). The method then iterates through * the result set and extracts the specified field, mapping an entity * of the given type to each row. This array of entities is returned.</p> * * @param type The type of the entities to retrieve. * @param field The field value to use in the creation of the entities. This is usually * the primary key field of the corresponding table. * @param query The {@link Query} instance to use in determining the results. * @return An array of entities of the given type which match the specified query. */ public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException { List<T> back = new ArrayList<T>(); query.resolveFields(type, getFieldNameConverter()); Preload preloadAnnotation = type.getAnnotation(Preload.class); if (preloadAnnotation != null) { if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) { String[] oldFields = query.getFields(); List<String> newFields = new ArrayList<String>(); for (String newField : preloadAnnotation.value()) { newField = newField.trim(); - int fieldLoc = Arrays.binarySearch(oldFields, newField); + int fieldLoc = -1; + for (int i = 0; i < oldFields.length; i++) { + if (oldFields[i].equals(newField)) { + fieldLoc = i; + break; + } + } if (fieldLoc < 0) { newFields.add(newField); } else { newFields.add(oldFields[fieldLoc]); } } if (!newFields.contains("*")) { for (String oldField : oldFields) { if (!newFields.contains(oldField)) { newFields.add(oldField); } } } query.setFields(newFields.toArray(new String[newFields.size()])); } } Connection conn = getProvider().getConnection(); try { String sql = null; tableNameConverterLock.readLock().lock(); try { sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false); } finally { tableNameConverterLock.readLock().unlock(); } Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); provider.setQueryStatementProperties(stmt, query); query.setParameters(this, stmt); ResultSet res = stmt.executeQuery(); ResultSetMetaData md = res.getMetaData(); provider.setQueryResultSetProperties(res, query); while (res.next()) { T entity = get(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field)); CacheLayer cacheLayer = getCache().getCacheLayer(entity); for (int i = 0; i < md.getColumnCount(); i++) { cacheLayer.put(md.getColumnLabel(i + 1), res.getObject(i + 1)); } back.add(entity); } res.close(); stmt.close(); } finally { conn.close(); } return back.toArray((T[]) Array.newInstance(type, back.size())); } /** * <p>Executes the specified SQL and extracts the given key field, wrapping each * row into a instance of the specified type. The SQL itself is executed as * a {@link PreparedStatement} with the given parameters.</p> * * <p>Example:</p> * * <pre>manager.findWithSQL(Person.class, "personID", "SELECT personID FROM chairs WHERE position &lt; ? LIMIT ?", 10, 5);</pre> * * <p>The SQL is not parsed or modified in any way by ActiveObjects. As such, it is * possible to execute database-specific queries using this method without realizing * it. For example, the above query will not run on MS SQL Server or Oracle, due to * the lack of a LIMIT clause in their SQL implementation. As such, be extremely * careful about what SQL is executed using this method, or else be conscious of the * fact that you may be locking yourself to a specific DBMS.</p> * * @param type The type of the entities to retrieve. * @param keyField The field value to use in the creation of the entities. This is usually * the primary key field of the corresponding table. * @param sql The SQL statement to execute. * @param parameters A varargs array of parameters to be passed to the executed * prepared statement. The length of this array <i>must</i> match the number of * parameters (denoted by the '?' char) in the <code>criteria</code>. * @return An array of entities of the given type which match the specified query. */ @SuppressWarnings("unchecked") public <T extends RawEntity<K>, K> T[] findWithSQL(Class<T> type, String keyField, String sql, Object... parameters) throws SQLException { List<T> back = new ArrayList<T>(); Connection conn = getProvider().getConnection(); try { Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql); TypeManager manager = TypeManager.getInstance(); for (int i = 0; i < parameters.length; i++) { Class javaType = parameters[i].getClass(); if (parameters[i] instanceof RawEntity) { javaType = ((RawEntity<?>) parameters[i]).getEntityType(); } manager.getType(javaType).putToDatabase(i + 1, stmt, parameters[i]); } ResultSet res = stmt.executeQuery(); while (res.next()) { back.add(get(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, (Class<? extends K>) type, keyField))); } res.close(); stmt.close(); } finally { conn.close(); } return back.toArray((T[]) Array.newInstance(type, back.size())); } /** * Counts all entities of the specified type. This method is actually * a delegate for: <code>count(Class&lt;? extends Entity&gt;, Query)</code> * * @param type The type of the entities which should be counted. * @return The number of entities of the specified type. */ public <K> int count(Class<? extends RawEntity<K>> type) throws SQLException { return count(type, Query.select()); } /** * Counts all entities of the specified type matching the given criteria * and parameters. This is a convenience method for: * <code>count(type, Query.select().where(criteria, parameters))</code> * * @param type The type of the entities which should be counted. * @param criteria A parameterized WHERE statement used to determine the result * set which will be counted. * @param parameters A varargs array of parameters to be passed to the executed * prepared statement. The length of this array <i>must</i> match the number of * parameters (denoted by the '?' char) in the <code>criteria</code>. * @return The number of entities of the given type which match the specified criteria. */ public <K> int count(Class<? extends RawEntity<K>> type, String criteria, Object... parameters) throws SQLException { return count(type, Query.select().where(criteria, parameters)); } /** * Counts all entities of the specified type matching the given {@link Query} * instance. The SQL runs as a <code>SELECT COUNT(*)</code> to * ensure maximum performance. * * @param type The type of the entities which should be counted. * @param query The {@link Query} instance used to determine the result set which * will be counted. * @return The number of entities of the given type which match the specified query. */ public <K> int count(Class<? extends RawEntity<K>> type, Query query) throws SQLException { int back = -1; Connection conn = getProvider().getConnection(); try { String sql = null; tableNameConverterLock.readLock().lock(); try { sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), true); } finally { tableNameConverterLock.readLock().unlock(); } Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql); provider.setQueryStatementProperties(stmt, query); query.setParameters(this, stmt); ResultSet res = stmt.executeQuery(); if (res.next()) { back = res.getInt(1); } res.close(); stmt.close(); } finally { conn.close(); } return back; } /** * <p>Specifies the {@link TableNameConverter} instance to use for * name conversion of all entity types. Name conversion is the process * of determining the appropriate table name from an arbitrary interface * extending {@link RawEntity}.</p> * * <p>The default table name converter is {@link CamelCaseTableNameConverter}.</p> * * @see #getTableNameConverter() */ public void setTableNameConverter(TableNameConverter tableNameConverter) { tableNameConverterLock.writeLock().lock(); try { this.tableNameConverter = tableNameConverter; } finally { tableNameConverterLock.writeLock().unlock(); } } /** * Retrieves the {@link TableNameConverter} instance used for name * conversion of all entity types. * * @see #setTableNameConverter(TableNameConverter) */ public TableNameConverter getTableNameConverter() { tableNameConverterLock.readLock().lock(); try { return tableNameConverter; } finally { tableNameConverterLock.readLock().unlock(); } } /** * <p>Specifies the {@link FieldNameConverter} instance to use for * field name conversion of all entity methods. Name conversion is the * process of determining the appropriate field name from an arbitrary * method within an interface extending {@link RawEntity}.</p> * * <p>The default field name converter is {@link CamelCaseFieldNameConverter}.</p> * * @see #getFieldNameConverter() */ public void setFieldNameConverter(FieldNameConverter fieldNameConverter) { fieldNameConverterLock.writeLock().lock(); try { this.fieldNameConverter = fieldNameConverter; } finally { fieldNameConverterLock.writeLock().unlock(); } } /** * Retrieves the {@link FieldNameConverter} instance used for name * conversion of all entity methods. * * @see #setFieldNameConverter(FieldNameConverter) */ public FieldNameConverter getFieldNameConverter() { fieldNameConverterLock.readLock().lock(); try { return fieldNameConverter; } finally { fieldNameConverterLock.readLock().unlock(); } } /** * Specifies the {@link PolymorphicTypeMapper} instance to use for * all flag value conversion of polymorphic types. The default type * mapper is an empty {@link DefaultPolymorphicTypeMapper} instance * (thus using the fully qualified classname for all values). * * @see #getPolymorphicTypeMapper() */ public void setPolymorphicTypeMapper(PolymorphicTypeMapper typeMapper) { typeMapperLock.writeLock().lock(); try { this.typeMapper = typeMapper; if (typeMapper instanceof DefaultPolymorphicTypeMapper) { ((DefaultPolymorphicTypeMapper) typeMapper).resolveMappings(getTableNameConverter()); } } finally { typeMapperLock.writeLock().unlock(); } } /** * Retrieves the {@link PolymorphicTypeMapper} instance used for flag * value conversion of polymorphic types. * * @see #setPolymorphicTypeMapper(PolymorphicTypeMapper) */ public PolymorphicTypeMapper getPolymorphicTypeMapper() { typeMapperLock.readLock().lock(); try { if (typeMapper == null) { throw new RuntimeException("No polymorphic type mapper was specified"); } return typeMapper; } finally { typeMapperLock.readLock().unlock(); } } public void setCache(Cache cache) { cacheLock.writeLock().lock(); try { if (!this.cache.equals(cache)) { this.cache.dispose(); this.cache = cache; } } finally { cacheLock.writeLock().unlock(); } } public Cache getCache() { cacheLock.readLock().lock(); try { return cache; } finally { cacheLock.readLock().unlock(); } } /** * <p>Retrieves the database provider used by this <code>EntityManager</code> * for all database operations. This method can be used reliably to obtain * a database provider and hence a {@link Connection} instance which can * be used for JDBC operations outside of ActiveObjects. Thus:</p> * * <pre>Connection conn = manager.getProvider().getConnection(); * try { * // ... * } finally { * conn.close(); * }</pre> */ public DatabaseProvider getProvider() { return provider; } <T extends RawEntity<K>, K> EntityProxy<T, K> getProxyForEntity(T entity) { proxyLock.readLock().lock(); try { return (EntityProxy<T, K>) proxies.get(entity); } finally { proxyLock.readLock().unlock(); } } RelationsCache getRelationsCache() { return relationsCache; } private Reference<RawEntity<?>> createRef(RawEntity<?> entity) { if (weaklyCache) { return new WeakReference<RawEntity<?>>(entity); } return new SoftReference<RawEntity<?>>(entity); } private static class CacheKey<T> { private T key; private Class<? extends RawEntity<?>> type; public CacheKey(T key, Class<? extends RawEntity<T>> type) { this.key = key; this.type = type; } @Override public int hashCode() { return (type.hashCode() + key.hashCode()) % (2 << 15); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CacheKey) { CacheKey<T> keyObj = (CacheKey<T>) obj; if (key.equals(keyObj.key) && type.equals(keyObj.type)) { return true; } } return false; } } }
true
true
public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException { List<T> back = new ArrayList<T>(); query.resolveFields(type, getFieldNameConverter()); Preload preloadAnnotation = type.getAnnotation(Preload.class); if (preloadAnnotation != null) { if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) { String[] oldFields = query.getFields(); List<String> newFields = new ArrayList<String>(); for (String newField : preloadAnnotation.value()) { newField = newField.trim(); int fieldLoc = Arrays.binarySearch(oldFields, newField); if (fieldLoc < 0) { newFields.add(newField); } else { newFields.add(oldFields[fieldLoc]); } } if (!newFields.contains("*")) { for (String oldField : oldFields) { if (!newFields.contains(oldField)) { newFields.add(oldField); } } } query.setFields(newFields.toArray(new String[newFields.size()])); } } Connection conn = getProvider().getConnection(); try { String sql = null; tableNameConverterLock.readLock().lock(); try { sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false); } finally { tableNameConverterLock.readLock().unlock(); } Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); provider.setQueryStatementProperties(stmt, query); query.setParameters(this, stmt); ResultSet res = stmt.executeQuery(); ResultSetMetaData md = res.getMetaData(); provider.setQueryResultSetProperties(res, query); while (res.next()) { T entity = get(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field)); CacheLayer cacheLayer = getCache().getCacheLayer(entity); for (int i = 0; i < md.getColumnCount(); i++) { cacheLayer.put(md.getColumnLabel(i + 1), res.getObject(i + 1)); } back.add(entity); } res.close(); stmt.close(); } finally { conn.close(); } return back.toArray((T[]) Array.newInstance(type, back.size())); }
public <T extends RawEntity<K>, K> T[] find(Class<T> type, String field, Query query) throws SQLException { List<T> back = new ArrayList<T>(); query.resolveFields(type, getFieldNameConverter()); Preload preloadAnnotation = type.getAnnotation(Preload.class); if (preloadAnnotation != null) { if (!query.getFields()[0].equals("*") && query.getJoins().isEmpty()) { String[] oldFields = query.getFields(); List<String> newFields = new ArrayList<String>(); for (String newField : preloadAnnotation.value()) { newField = newField.trim(); int fieldLoc = -1; for (int i = 0; i < oldFields.length; i++) { if (oldFields[i].equals(newField)) { fieldLoc = i; break; } } if (fieldLoc < 0) { newFields.add(newField); } else { newFields.add(oldFields[fieldLoc]); } } if (!newFields.contains("*")) { for (String oldField : oldFields) { if (!newFields.contains(oldField)) { newFields.add(oldField); } } } query.setFields(newFields.toArray(new String[newFields.size()])); } } Connection conn = getProvider().getConnection(); try { String sql = null; tableNameConverterLock.readLock().lock(); try { sql = query.toSQL(type, provider, tableNameConverter, getFieldNameConverter(), false); } finally { tableNameConverterLock.readLock().unlock(); } Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); provider.setQueryStatementProperties(stmt, query); query.setParameters(this, stmt); ResultSet res = stmt.executeQuery(); ResultSetMetaData md = res.getMetaData(); provider.setQueryResultSetProperties(res, query); while (res.next()) { T entity = get(type, Common.getPrimaryKeyType(type).pullFromDatabase(this, res, Common.getPrimaryKeyClassType(type), field)); CacheLayer cacheLayer = getCache().getCacheLayer(entity); for (int i = 0; i < md.getColumnCount(); i++) { cacheLayer.put(md.getColumnLabel(i + 1), res.getObject(i + 1)); } back.add(entity); } res.close(); stmt.close(); } finally { conn.close(); } return back.toArray((T[]) Array.newInstance(type, back.size())); }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java index e224c9137..2b5e23700 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoratorConfiguration.java @@ -1,77 +1,77 @@ package org.eclipse.team.internal.ccvs.ui; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.Map; import org.eclipse.core.runtime.IStatus; import org.eclipse.team.ccvs.core.CVSStatus; public class CVSDecoratorConfiguration { // bindings for public static final String RESOURCE_NAME = "name"; //$NON-NLS-1$ public static final String RESOURCE_TAG = "tag"; //$NON-NLS-1$ public static final String FILE_REVISION = "revision"; //$NON-NLS-1$ public static final String FILE_KEYWORD = "keyword"; //$NON-NLS-1$ // bindings for repository location public static final String REMOTELOCATION_METHOD = "method"; //$NON-NLS-1$ public static final String REMOTELOCATION_USER = "user"; //$NON-NLS-1$ public static final String REMOTELOCATION_HOST = "host"; //$NON-NLS-1$ public static final String REMOTELOCATION_ROOT = "root"; //$NON-NLS-1$ public static final String REMOTELOCATION_REPOSITORY = "repository"; //$NON-NLS-1$ // bindings for resource states public static final String DIRTY_FLAG = "dirty_flag"; //$NON-NLS-1$ public static final String ADDED_FLAG = "added_flag"; //$NON-NLS-1$ public static final String DEFAULT_DIRTY_FLAG = ">"; //$NON-NLS-1$ public static final String DEFAULT_ADDED_FLAG = "*"; //$NON-NLS-1$ // default text decoration formats public static final String DEFAULT_FILETEXTFORMAT = "{dirty_flag}{name} {revision} {tag}"; //$NON-NLS-1$ public static final String DEFAULT_FOLDERTEXTFORMAT = "{dirty_flag}{name} {tag}"; //$NON-NLS-1$ public static final String DEFAULT_PROJECTTEXTFORMAT = "{dirty_flag}{name} {tag} [{host}]"; //$NON-NLS-1$ // prefix characters that can be removed if the following binding is not found private static final char KEYWORD_SEPSPACE = ' '; private static final char KEYWORD_SEPCOLON = ':'; private static final char KEYWORD_SEPAT = '@'; public static String bind(String format, Map bindings) { StringBuffer output = new StringBuffer(80); int length = format.length(); int start = -1; int end = length; while (true) { if ((end = format.indexOf('{', start)) > -1) { output.append(format.substring(start + 1, end)); if ((start = format.indexOf('}', end)) > -1) { String s = (String)bindings.get(format.substring(end + 1, start)); if(s!=null) { output.append(s); } else { // support for removing prefix character if binding is null int curLength = output.length(); if(curLength>0) { char c = output.charAt(curLength - 1); - if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPSPACE || c == KEYWORD_SEPCOLON) { + if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPCOLON) { output.deleteCharAt(curLength - 1); } } } } else { output.append(format.substring(end, length)); break; } } else { output.append(format.substring(start + 1, length)); break; } } return output.toString(); } }
true
true
public static String bind(String format, Map bindings) { StringBuffer output = new StringBuffer(80); int length = format.length(); int start = -1; int end = length; while (true) { if ((end = format.indexOf('{', start)) > -1) { output.append(format.substring(start + 1, end)); if ((start = format.indexOf('}', end)) > -1) { String s = (String)bindings.get(format.substring(end + 1, start)); if(s!=null) { output.append(s); } else { // support for removing prefix character if binding is null int curLength = output.length(); if(curLength>0) { char c = output.charAt(curLength - 1); if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPSPACE || c == KEYWORD_SEPCOLON) { output.deleteCharAt(curLength - 1); } } } } else { output.append(format.substring(end, length)); break; } } else { output.append(format.substring(start + 1, length)); break; } } return output.toString(); }
public static String bind(String format, Map bindings) { StringBuffer output = new StringBuffer(80); int length = format.length(); int start = -1; int end = length; while (true) { if ((end = format.indexOf('{', start)) > -1) { output.append(format.substring(start + 1, end)); if ((start = format.indexOf('}', end)) > -1) { String s = (String)bindings.get(format.substring(end + 1, start)); if(s!=null) { output.append(s); } else { // support for removing prefix character if binding is null int curLength = output.length(); if(curLength>0) { char c = output.charAt(curLength - 1); if(c == KEYWORD_SEPCOLON || c == KEYWORD_SEPCOLON) { output.deleteCharAt(curLength - 1); } } } } else { output.append(format.substring(end, length)); break; } } else { output.append(format.substring(start + 1, length)); break; } } return output.toString(); }
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskTutorView.java b/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskTutorView.java index 27a22e2..83f3d5a 100644 --- a/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskTutorView.java +++ b/source/de/tuclausthal/submissioninterface/servlets/view/ShowTaskTutorView.java @@ -1,219 +1,223 @@ /* * Copyright 2009 - 2010 Sven Strickroth <[email protected]> * * This file is part of the SubmissionInterface. * * SubmissionInterface is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>. */ package de.tuclausthal.submissioninterface.servlets.view; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory; import de.tuclausthal.submissioninterface.persistence.dao.TestResultDAOIf; import de.tuclausthal.submissioninterface.persistence.datamodel.Group; import de.tuclausthal.submissioninterface.persistence.datamodel.Participation; import de.tuclausthal.submissioninterface.persistence.datamodel.ParticipationRole; import de.tuclausthal.submissioninterface.persistence.datamodel.Similarity; import de.tuclausthal.submissioninterface.persistence.datamodel.SimilarityTest; import de.tuclausthal.submissioninterface.persistence.datamodel.Submission; import de.tuclausthal.submissioninterface.persistence.datamodel.Task; import de.tuclausthal.submissioninterface.persistence.datamodel.Test; import de.tuclausthal.submissioninterface.template.Template; import de.tuclausthal.submissioninterface.template.TemplateFactory; import de.tuclausthal.submissioninterface.util.HibernateSessionHelper; import de.tuclausthal.submissioninterface.util.Util; /** * View-Servlet for displaying a task in tutor view * @author Sven Strickroth */ public class ShowTaskTutorView extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Session session = HibernateSessionHelper.getSessionFactory().openSession(); Task task = (Task) request.getAttribute("task"); Participation participation = (Participation) request.getAttribute("participation"); template.printTemplateHeader(task); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Beschreibung:</th>"); // HTML must be possible here out.println("<td>" + task.getDescription() + "&nbsp;</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Startdatum:</th>"); out.println("<td>" + Util.mknohtml(task.getStart().toLocaleString()) + "</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Enddatum:</th>"); out.println("<td>" + Util.mknohtml(task.getDeadline().toLocaleString())); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println(" Keine Abgabe mehr m�glich"); } out.println("</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Punkte:</th>"); out.println("<td class=points>" + task.getMaxPoints() + "</td>"); out.println("</tr>"); out.println("</table>"); if (participation.getRoleType() == ParticipationRole.ADVISOR) { out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=editTask") + "\">Aufgabe bearbeiten</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=deleteTask") + "\">Aufgabe l�schen</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Aufgabe f�r Studenten durchf�hren</a></div>"); } if (task.getSubmissions() != null && task.getSubmissions().size() > 0) { out.println("<p><h2>Abgaben</h2><p>"); Iterator<Submission> submissionIterator = DAOFactory.SubmissionDAOIf(session).getSubmissionsForTaskOrdered(task).iterator(); Group lastGroup = null; boolean first = true; int sumOfSubmissions = 0; int sumOfPoints = 0; int groupSumOfSubmissions = 0; int groupSumOfPoints = 0; int testCols = 0; + for (Test test : task.getTests()) { + if (test.isForTutors()) { + testCols++; + } + } int lastSID = 0; TestResultDAOIf testResultDAO = DAOFactory.TestResultDAOIf(session); List<Test> tests = DAOFactory.TestDAOIf(session).getTutorTests(task); boolean hasUnapprochedPoints = false; // dynamic splitter for groups while (submissionIterator.hasNext()) { Submission submission = submissionIterator.next(); Group group = submission.getSubmitters().iterator().next().getGroup(); if (first == true || lastGroup != group) { lastGroup = group; if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); - out.println("<td colspan=" + (1 + submission.getTestResults().size() + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); + out.println("<td colspan=" + (1 + testCols + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); groupSumOfSubmissions = 0; groupSumOfPoints = 0; } first = false; hasUnapprochedPoints = false; if (group == null) { out.println("<h3>Ohne Gruppe</h3>"); } else { out.println("<h3>Gruppe: " + Util.mknohtml(group.getName()) + "</h3>"); out.println("<div class=mid><a href=\"ShowTask?taskid=" + task.getTaskid() + "&action=grouplist&groupid=" + group.getGid() + "\" target=\"_blank\">Druckbare Liste</a></div>"); } out.println("<form method=post action=\"MarkApproved?taskid=" + task.getTaskid() + "\">"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Benutzer</th>"); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { out.println("<th>" + Util.mknohtml(test.getTestTitle()) + "</th>"); } - testCols = Math.max(testCols, submission.getTestResults().size()); for (SimilarityTest similarityTest : task.getSimularityTests()) { out.println("<th><span title=\"Max. �hnlichkeit\">" + similarityTest + "</span></th>"); } out.println("<th>Punkte</th>"); out.println("<th>Abnehmen</th>"); } out.println("</tr>"); } if (lastSID != submission.getSubmissionid()) { out.println("<tr>"); out.println("<td><a href=\"" + response.encodeURL("ShowSubmission?sid=" + submission.getSubmissionid()) + "\">" + Util.mknohtml(submission.getSubmitterNames()) + "</a></td>"); lastSID = submission.getSubmissionid(); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { if (testResultDAO.getResult(test, submission) != null) { out.println("<td>" + Util.boolToHTML(testResultDAO.getResult(test, submission).getPassedTest()) + "</td>"); } else { out.println("<td>n/a</td>"); } } for (SimilarityTest similarityTest : task.getSimularityTests()) { //TODO: tooltip and who it is String users = ""; for (Similarity similarity : DAOFactory.SimilarityDAOIf(session).getUsersWithMaxSimilarity(similarityTest, submission)) { users += Util.mknohtml(similarity.getSubmissionTwo().getSubmitterNames()) + "\n"; } out.println("<td class=points><span title=\"" + users + "\">" + DAOFactory.SimilarityDAOIf(session).getMaxSimilarity(similarityTest, submission) + "</span></td>"); } if (submission.getPoints() != null) { if (submission.getPoints().getPointsOk()) { out.println("<td align=right>" + submission.getPoints().getPoints() + "</td>"); out.println("<td></td>"); } else { out.println("<td align=right>(" + submission.getPoints().getPoints() + ")</td>"); out.println("<td><input type=checkbox name=\"sid" + submission.getSubmissionid() + "\"></td>"); hasUnapprochedPoints = true; } sumOfPoints += submission.getPoints().getPoints(); groupSumOfPoints += submission.getPoints().getPoints(); sumOfSubmissions++; groupSumOfSubmissions++; } else { out.println("<td>n/a</td>"); out.println("<td></td>"); } } out.println("</tr>"); } } if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); out.println("<td colspan=" + (1 + testCols + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); out.println("<h3>Gesamtdurchschnitt: " + Float.valueOf(sumOfPoints / (float) sumOfSubmissions).intValue() + "</h3>"); } } template.printTemplateFooter(); } }
false
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Session session = HibernateSessionHelper.getSessionFactory().openSession(); Task task = (Task) request.getAttribute("task"); Participation participation = (Participation) request.getAttribute("participation"); template.printTemplateHeader(task); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Beschreibung:</th>"); // HTML must be possible here out.println("<td>" + task.getDescription() + "&nbsp;</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Startdatum:</th>"); out.println("<td>" + Util.mknohtml(task.getStart().toLocaleString()) + "</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Enddatum:</th>"); out.println("<td>" + Util.mknohtml(task.getDeadline().toLocaleString())); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println(" Keine Abgabe mehr m�glich"); } out.println("</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Punkte:</th>"); out.println("<td class=points>" + task.getMaxPoints() + "</td>"); out.println("</tr>"); out.println("</table>"); if (participation.getRoleType() == ParticipationRole.ADVISOR) { out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=editTask") + "\">Aufgabe bearbeiten</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=deleteTask") + "\">Aufgabe l�schen</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Aufgabe f�r Studenten durchf�hren</a></div>"); } if (task.getSubmissions() != null && task.getSubmissions().size() > 0) { out.println("<p><h2>Abgaben</h2><p>"); Iterator<Submission> submissionIterator = DAOFactory.SubmissionDAOIf(session).getSubmissionsForTaskOrdered(task).iterator(); Group lastGroup = null; boolean first = true; int sumOfSubmissions = 0; int sumOfPoints = 0; int groupSumOfSubmissions = 0; int groupSumOfPoints = 0; int testCols = 0; int lastSID = 0; TestResultDAOIf testResultDAO = DAOFactory.TestResultDAOIf(session); List<Test> tests = DAOFactory.TestDAOIf(session).getTutorTests(task); boolean hasUnapprochedPoints = false; // dynamic splitter for groups while (submissionIterator.hasNext()) { Submission submission = submissionIterator.next(); Group group = submission.getSubmitters().iterator().next().getGroup(); if (first == true || lastGroup != group) { lastGroup = group; if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); out.println("<td colspan=" + (1 + submission.getTestResults().size() + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); groupSumOfSubmissions = 0; groupSumOfPoints = 0; } first = false; hasUnapprochedPoints = false; if (group == null) { out.println("<h3>Ohne Gruppe</h3>"); } else { out.println("<h3>Gruppe: " + Util.mknohtml(group.getName()) + "</h3>"); out.println("<div class=mid><a href=\"ShowTask?taskid=" + task.getTaskid() + "&action=grouplist&groupid=" + group.getGid() + "\" target=\"_blank\">Druckbare Liste</a></div>"); } out.println("<form method=post action=\"MarkApproved?taskid=" + task.getTaskid() + "\">"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Benutzer</th>"); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { out.println("<th>" + Util.mknohtml(test.getTestTitle()) + "</th>"); } testCols = Math.max(testCols, submission.getTestResults().size()); for (SimilarityTest similarityTest : task.getSimularityTests()) { out.println("<th><span title=\"Max. �hnlichkeit\">" + similarityTest + "</span></th>"); } out.println("<th>Punkte</th>"); out.println("<th>Abnehmen</th>"); } out.println("</tr>"); } if (lastSID != submission.getSubmissionid()) { out.println("<tr>"); out.println("<td><a href=\"" + response.encodeURL("ShowSubmission?sid=" + submission.getSubmissionid()) + "\">" + Util.mknohtml(submission.getSubmitterNames()) + "</a></td>"); lastSID = submission.getSubmissionid(); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { if (testResultDAO.getResult(test, submission) != null) { out.println("<td>" + Util.boolToHTML(testResultDAO.getResult(test, submission).getPassedTest()) + "</td>"); } else { out.println("<td>n/a</td>"); } } for (SimilarityTest similarityTest : task.getSimularityTests()) { //TODO: tooltip and who it is String users = ""; for (Similarity similarity : DAOFactory.SimilarityDAOIf(session).getUsersWithMaxSimilarity(similarityTest, submission)) { users += Util.mknohtml(similarity.getSubmissionTwo().getSubmitterNames()) + "\n"; } out.println("<td class=points><span title=\"" + users + "\">" + DAOFactory.SimilarityDAOIf(session).getMaxSimilarity(similarityTest, submission) + "</span></td>"); } if (submission.getPoints() != null) { if (submission.getPoints().getPointsOk()) { out.println("<td align=right>" + submission.getPoints().getPoints() + "</td>"); out.println("<td></td>"); } else { out.println("<td align=right>(" + submission.getPoints().getPoints() + ")</td>"); out.println("<td><input type=checkbox name=\"sid" + submission.getSubmissionid() + "\"></td>"); hasUnapprochedPoints = true; } sumOfPoints += submission.getPoints().getPoints(); groupSumOfPoints += submission.getPoints().getPoints(); sumOfSubmissions++; groupSumOfSubmissions++; } else { out.println("<td>n/a</td>"); out.println("<td></td>"); } } out.println("</tr>"); } } if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); out.println("<td colspan=" + (1 + testCols + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); out.println("<h3>Gesamtdurchschnitt: " + Float.valueOf(sumOfPoints / (float) sumOfSubmissions).intValue() + "</h3>"); } } template.printTemplateFooter(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Session session = HibernateSessionHelper.getSessionFactory().openSession(); Task task = (Task) request.getAttribute("task"); Participation participation = (Participation) request.getAttribute("participation"); template.printTemplateHeader(task); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Beschreibung:</th>"); // HTML must be possible here out.println("<td>" + task.getDescription() + "&nbsp;</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Startdatum:</th>"); out.println("<td>" + Util.mknohtml(task.getStart().toLocaleString()) + "</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Enddatum:</th>"); out.println("<td>" + Util.mknohtml(task.getDeadline().toLocaleString())); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println(" Keine Abgabe mehr m�glich"); } out.println("</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Punkte:</th>"); out.println("<td class=points>" + task.getMaxPoints() + "</td>"); out.println("</tr>"); out.println("</table>"); if (participation.getRoleType() == ParticipationRole.ADVISOR) { out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=editTask") + "\">Aufgabe bearbeiten</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("TaskManager?lecture=" + task.getLecture().getId() + "&amp;taskid=" + task.getTaskid() + "&amp;action=deleteTask") + "\">Aufgabe l�schen</a></div>"); out.println("<p><div class=mid><a href=\"" + response.encodeURL("SubmitSolution?taskid=" + task.getTaskid()) + "\">Aufgabe f�r Studenten durchf�hren</a></div>"); } if (task.getSubmissions() != null && task.getSubmissions().size() > 0) { out.println("<p><h2>Abgaben</h2><p>"); Iterator<Submission> submissionIterator = DAOFactory.SubmissionDAOIf(session).getSubmissionsForTaskOrdered(task).iterator(); Group lastGroup = null; boolean first = true; int sumOfSubmissions = 0; int sumOfPoints = 0; int groupSumOfSubmissions = 0; int groupSumOfPoints = 0; int testCols = 0; for (Test test : task.getTests()) { if (test.isForTutors()) { testCols++; } } int lastSID = 0; TestResultDAOIf testResultDAO = DAOFactory.TestResultDAOIf(session); List<Test> tests = DAOFactory.TestDAOIf(session).getTutorTests(task); boolean hasUnapprochedPoints = false; // dynamic splitter for groups while (submissionIterator.hasNext()) { Submission submission = submissionIterator.next(); Group group = submission.getSubmitters().iterator().next().getGroup(); if (first == true || lastGroup != group) { lastGroup = group; if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); out.println("<td colspan=" + (1 + testCols + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); groupSumOfSubmissions = 0; groupSumOfPoints = 0; } first = false; hasUnapprochedPoints = false; if (group == null) { out.println("<h3>Ohne Gruppe</h3>"); } else { out.println("<h3>Gruppe: " + Util.mknohtml(group.getName()) + "</h3>"); out.println("<div class=mid><a href=\"ShowTask?taskid=" + task.getTaskid() + "&action=grouplist&groupid=" + group.getGid() + "\" target=\"_blank\">Druckbare Liste</a></div>"); } out.println("<form method=post action=\"MarkApproved?taskid=" + task.getTaskid() + "\">"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Benutzer</th>"); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { out.println("<th>" + Util.mknohtml(test.getTestTitle()) + "</th>"); } for (SimilarityTest similarityTest : task.getSimularityTests()) { out.println("<th><span title=\"Max. �hnlichkeit\">" + similarityTest + "</span></th>"); } out.println("<th>Punkte</th>"); out.println("<th>Abnehmen</th>"); } out.println("</tr>"); } if (lastSID != submission.getSubmissionid()) { out.println("<tr>"); out.println("<td><a href=\"" + response.encodeURL("ShowSubmission?sid=" + submission.getSubmissionid()) + "\">" + Util.mknohtml(submission.getSubmitterNames()) + "</a></td>"); lastSID = submission.getSubmissionid(); if (task.getDeadline().before(Util.correctTimezone(new Date()))) { for (Test test : tests) { if (testResultDAO.getResult(test, submission) != null) { out.println("<td>" + Util.boolToHTML(testResultDAO.getResult(test, submission).getPassedTest()) + "</td>"); } else { out.println("<td>n/a</td>"); } } for (SimilarityTest similarityTest : task.getSimularityTests()) { //TODO: tooltip and who it is String users = ""; for (Similarity similarity : DAOFactory.SimilarityDAOIf(session).getUsersWithMaxSimilarity(similarityTest, submission)) { users += Util.mknohtml(similarity.getSubmissionTwo().getSubmitterNames()) + "\n"; } out.println("<td class=points><span title=\"" + users + "\">" + DAOFactory.SimilarityDAOIf(session).getMaxSimilarity(similarityTest, submission) + "</span></td>"); } if (submission.getPoints() != null) { if (submission.getPoints().getPointsOk()) { out.println("<td align=right>" + submission.getPoints().getPoints() + "</td>"); out.println("<td></td>"); } else { out.println("<td align=right>(" + submission.getPoints().getPoints() + ")</td>"); out.println("<td><input type=checkbox name=\"sid" + submission.getSubmissionid() + "\"></td>"); hasUnapprochedPoints = true; } sumOfPoints += submission.getPoints().getPoints(); groupSumOfPoints += submission.getPoints().getPoints(); sumOfSubmissions++; groupSumOfSubmissions++; } else { out.println("<td>n/a</td>"); out.println("<td></td>"); } } out.println("</tr>"); } } if (first == false) { if (task.getDeadline().before(Util.correctTimezone(new Date()))) { out.println("<tr>"); out.println("<td colspan=" + (1 + testCols + task.getSimularityTests().size()) + ">Durchschnittspunkte:</td>"); out.println("<td class=points>" + Float.valueOf(groupSumOfPoints / (float) groupSumOfSubmissions).intValue() + "</td>"); if (hasUnapprochedPoints) { out.println("<td><input type=submit value=Save></td>"); } else { out.println("<td></td>"); } out.println("</tr>"); } out.println("</table><p>"); out.println("</form>"); out.println("<h3>Gesamtdurchschnitt: " + Float.valueOf(sumOfPoints / (float) sumOfSubmissions).intValue() + "</h3>"); } } template.printTemplateFooter(); }
diff --git a/projects/java_dann/src/com/syncleus/dann/math/visualization/MathFunctionDataBinder.java b/projects/java_dann/src/com/syncleus/dann/math/visualization/MathFunctionDataBinder.java index 26835ff..fb3323f 100644 --- a/projects/java_dann/src/com/syncleus/dann/math/visualization/MathFunctionDataBinder.java +++ b/projects/java_dann/src/com/syncleus/dann/math/visualization/MathFunctionDataBinder.java @@ -1,268 +1,268 @@ /****************************************************************************** * * * Copyright: (c) Syncleus, Inc. * * * * You may redistribute and modify this source code under the terms and * * conditions of the Open Source Community License - Type C version 1.0 * * or any later version as published by Syncleus, Inc. at www.syncleus.com. * * There should be a copy of the license included with this file. If a copy * * of the license is not included you are granted no right to distribute or * * otherwise use this file except through a legal and valid license. You * * should also contact Syncleus, Inc. at the information below if you cannot * * find a license: * * * * Syncleus, Inc. * * 2604 South 12th Street * * Philadelphia, PA 19148 * * * ******************************************************************************/ package com.syncleus.dann.math.visualization; import com.syncleus.dann.math.AbstractMathFunction; import org.freehep.j3d.plot.*; import javax.vecmath.*; import java.awt.Color; import java.security.InvalidParameterException; public final class MathFunctionDataBinder implements Binned2DData { private final AbstractMathFunction function; private final int functionXIndex; private final int functionYIndex; private final float minX; private final float maxX; private final float minY; private final float maxY; private final float minZ; private final float maxZ; private final int resolution; public MathFunctionDataBinder(AbstractMathFunction function, String functionXParam, String functionYParam, float xMin, float xMax, float yMin, float yMax, int resolution) { if( resolution <= 0 ) throw new InvalidParameterException("resolution must be greater than 0"); this.function = function; this.functionXIndex = this.function.getParameterNameIndex(functionXParam); this.functionYIndex = this.function.getParameterNameIndex(functionYParam); this.minX = xMin; this.maxX = xMax; this.minY = yMin; this.maxY = yMax; this.resolution = resolution; boolean zMaxSet = false; boolean zMinSet = false; float newZMax = 1.0f; float newZMin = -1.0f; for(int xIndex = 0;xIndex < this.xBins();xIndex++) { this.setX(this.convertFromXIndex(xIndex)); for(int yIndex = 0;yIndex < this.yBins();yIndex++) { this.setY(this.convertFromYIndex(yIndex)); final float currentZ = (float)this.calculateZ(); if(!Float.isNaN(currentZ)) { - if((this.maxZ < currentZ) || (!zMaxSet)) + if((newZMax < currentZ) || (!zMaxSet)) { newZMax = currentZ; zMaxSet = true; } - if((this.minZ > currentZ) || (!zMinSet)) + if((newZMin > currentZ) || (!zMinSet)) { newZMin = currentZ; zMinSet = true; } } } } if(newZMax == newZMin) { newZMax += 1.0; newZMin += -1.0; } this.maxZ = newZMax; this.minZ = newZMin; - if( Float.isNaN(maxZ) || Float.isNaN(minZ)) + if( Float.isNaN(this.maxZ) || Float.isNaN(this.minZ)) throw new InvalidParameterException("z does not deviate, nothing to plot!"); } private float convertFromXIndex(final int xCoord) { final float xSize = this.maxX - this.minX; return (((float)xCoord) / ((float)this.xBins())) * xSize + this.minX; } private float convertFromYIndex(final int yCoord) { final float ySize = this.maxY - this.minY; return (((float)(this.yBins() - yCoord)) / ((float)this.yBins())) * ySize + this.minY; } public AbstractMathFunction getFunction() { return this.function; } public int getXIndex() { return this.functionXIndex; } public int getYIndex() { return this.functionYIndex; } public int getResolution() { return this.resolution; } private void setX(final double xCoord) { this.function.setParameter(this.functionXIndex, xCoord); } private void setY(final double yCoord) { this.function.setParameter(this.functionYIndex, yCoord); } private double calculateZ() { return this.function.calculate(); } public Color3b colorAt(final int xIndex, final int yIndex) { final float xCoord = this.convertFromXIndex(xIndex); final float yCoord = this.convertFromYIndex(yIndex); this.setX(xCoord); this.setY(yCoord); final double zCoord = this.calculateZ(); if(zCoord > this.maxZ) return new Color3b(new Color(0.0f, 0.0f, 0.0f)); else if(zCoord < this.minZ) return new Color3b(new Color(0.0f, 0.0f, 0.0f)); else { final float redValue = (float)(zCoord - this.minZ) / (this.maxZ - this.minZ); final float blueValue = 1.0f - redValue; final float greenValue = 0.0f; return new Color3b(new Color(redValue, greenValue, blueValue)); } } public int xBins() { return this.resolution; } public float xMax() { return this.maxX; } public float xMin() { return this.minX; } public int yBins() { return this.resolution; } public float yMax() { return this.maxY; } public float yMin() { return this.minY; } public float zAt(final int xIndex, final int yIndex) { final float xCoord = this.convertFromXIndex(xIndex); final float yCoord = this.convertFromYIndex(yIndex); this.setX(xCoord); this.setY(yCoord); final float zCoord = (float)this.calculateZ(); if(zCoord < this.minZ) return this.minZ; else if(zCoord > this.maxZ) return this.maxZ; else if(Float.isNaN(zCoord)) return 0.0f; else return zCoord; } public float zMax() { return this.maxZ; } public float zMin() { return this.minZ; } }
false
true
public MathFunctionDataBinder(AbstractMathFunction function, String functionXParam, String functionYParam, float xMin, float xMax, float yMin, float yMax, int resolution) { if( resolution <= 0 ) throw new InvalidParameterException("resolution must be greater than 0"); this.function = function; this.functionXIndex = this.function.getParameterNameIndex(functionXParam); this.functionYIndex = this.function.getParameterNameIndex(functionYParam); this.minX = xMin; this.maxX = xMax; this.minY = yMin; this.maxY = yMax; this.resolution = resolution; boolean zMaxSet = false; boolean zMinSet = false; float newZMax = 1.0f; float newZMin = -1.0f; for(int xIndex = 0;xIndex < this.xBins();xIndex++) { this.setX(this.convertFromXIndex(xIndex)); for(int yIndex = 0;yIndex < this.yBins();yIndex++) { this.setY(this.convertFromYIndex(yIndex)); final float currentZ = (float)this.calculateZ(); if(!Float.isNaN(currentZ)) { if((this.maxZ < currentZ) || (!zMaxSet)) { newZMax = currentZ; zMaxSet = true; } if((this.minZ > currentZ) || (!zMinSet)) { newZMin = currentZ; zMinSet = true; } } } } if(newZMax == newZMin) { newZMax += 1.0; newZMin += -1.0; } this.maxZ = newZMax; this.minZ = newZMin; if( Float.isNaN(maxZ) || Float.isNaN(minZ)) throw new InvalidParameterException("z does not deviate, nothing to plot!"); }
public MathFunctionDataBinder(AbstractMathFunction function, String functionXParam, String functionYParam, float xMin, float xMax, float yMin, float yMax, int resolution) { if( resolution <= 0 ) throw new InvalidParameterException("resolution must be greater than 0"); this.function = function; this.functionXIndex = this.function.getParameterNameIndex(functionXParam); this.functionYIndex = this.function.getParameterNameIndex(functionYParam); this.minX = xMin; this.maxX = xMax; this.minY = yMin; this.maxY = yMax; this.resolution = resolution; boolean zMaxSet = false; boolean zMinSet = false; float newZMax = 1.0f; float newZMin = -1.0f; for(int xIndex = 0;xIndex < this.xBins();xIndex++) { this.setX(this.convertFromXIndex(xIndex)); for(int yIndex = 0;yIndex < this.yBins();yIndex++) { this.setY(this.convertFromYIndex(yIndex)); final float currentZ = (float)this.calculateZ(); if(!Float.isNaN(currentZ)) { if((newZMax < currentZ) || (!zMaxSet)) { newZMax = currentZ; zMaxSet = true; } if((newZMin > currentZ) || (!zMinSet)) { newZMin = currentZ; zMinSet = true; } } } } if(newZMax == newZMin) { newZMax += 1.0; newZMin += -1.0; } this.maxZ = newZMax; this.minZ = newZMin; if( Float.isNaN(this.maxZ) || Float.isNaN(this.minZ)) throw new InvalidParameterException("z does not deviate, nothing to plot!"); }