repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
wbstr/dbunit | src/test/java/org/dbunit/dataset/LowerCaseTableMetaDataTest.java | 3791 | /*
*
* The DbUnit Database Testing Framework
* Copyright (C)2002-2004, DbUnit.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 (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.dbunit.dataset;
import junit.framework.TestCase;
import org.dbunit.dataset.datatype.DataType;
/**
* @author Manuel Laflamme
* @version $Revision: 421 $
* @since Feb 17, 2002
*/
public class LowerCaseTableMetaDataTest extends TestCase
{
public LowerCaseTableMetaDataTest(String s)
{
super(s);
}
public void testGetTableName() throws Exception
{
String original = "TABLE_NAME";
String expected = original.toLowerCase();
ITableMetaData metaData = new LowerCaseTableMetaData(
new DefaultTableMetaData(original, new Column[0]));
assertEquals("table name", expected, metaData.getTableName());
}
public void testGetColumns() throws Exception
{
Column[] columns = new Column[]{
new Column("NUMBER_COLUMN", DataType.NUMERIC, "qwerty", Column.NULLABLE),
new Column("STRING_COLUMN", DataType.VARCHAR, "toto", Column.NO_NULLS),
new Column("BOOLEAN_COLUMN", DataType.BOOLEAN),
};
ITableMetaData metaData = new LowerCaseTableMetaData(
"TABLE_NAME", columns);
Column[] lowerColumns = metaData.getColumns();
assertEquals("column count", columns.length, lowerColumns.length);
for (int i = 0; i < columns.length; i++)
{
Column column = columns[i];
Column lowerColumn = lowerColumns[i];
assertEquals("name", column.getColumnName().toLowerCase(),
lowerColumn.getColumnName());
assertTrue("name not equals",
!column.getColumnName().equals(lowerColumn.getColumnName()));
assertEquals("type", column.getDataType(), lowerColumn.getDataType());
assertEquals("sql type", column.getSqlTypeName(), lowerColumn.getSqlTypeName());
assertEquals("nullable", column.getNullable(), lowerColumn.getNullable());
}
assertEquals("key count", 0, metaData.getPrimaryKeys().length);
}
public void testGetPrimaryKeys() throws Exception
{
Column[] columns = new Column[]{
new Column("NUMBER_COLUMN", DataType.NUMERIC, "qwerty", Column.NULLABLE),
new Column("STRING_COLUMN", DataType.VARCHAR, "toto", Column.NO_NULLS),
new Column("BOOLEAN_COLUMN", DataType.BOOLEAN),
};
String[] keyNames = new String[]{"Boolean_Column", "Number_Column"};
ITableMetaData metaData = new LowerCaseTableMetaData(
"TABLE_NAME", columns, keyNames);
Column[] keys = metaData.getPrimaryKeys();
assertEquals("key count", keyNames.length, keys.length);
for (int i = 0; i < keys.length; i++)
{
assertTrue("name not equals",
!keyNames[i].equals(keys[i].getColumnName()));
assertEquals("key name", keyNames[i].toLowerCase(),
keys[i].getColumnName());
}
}
}
| lgpl-2.1 |
sbonoc/opencms-core | src/org/opencms/gwt/CmsClientUserSettingConverter.java | 8618 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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.opencms.gwt;
import org.opencms.configuration.CmsDefaultUserSettings;
import org.opencms.configuration.preferences.I_CmsPreference;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsUser;
import org.opencms.gwt.shared.CmsGwtConstants;
import org.opencms.gwt.shared.CmsUserSettingsBean;
import org.opencms.i18n.CmsMessages;
import org.opencms.i18n.CmsMultiMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.workplace.commons.CmsPreferences;
import org.opencms.xml.content.CmsXmlContentProperty;
import org.opencms.xml.content.CmsXmlContentPropertyHelper;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
/**
* Helper class to deal with loading and saving user preferences from the ADE user interface.<p>
*/
public class CmsClientUserSettingConverter {
/**
* Subclass of the normal action element which can be created even if we are not being called from a JSP.<p>
*/
class NoJspActionElement extends CmsJspActionElement {
/** The CMS object to use. */
private CmsObject m_setCms;
/**
* Creates a new instance.<p>
*
* @param cms the CMS context to use
* @param req the current request
* @param res the current response
*/
public NoJspActionElement(CmsObject cms, HttpServletRequest req, HttpServletResponse res) {
super(null, req, res);
m_setCms = cms;
}
/**
* @see org.opencms.jsp.CmsJspBean#getCmsObject()
*/
@Override
public CmsObject getCmsObject() {
return m_setCms;
}
/**
* @see org.opencms.jsp.CmsJspBean#handleMissingFlexController()
*/
@Override
protected void handleMissingFlexController() {
// ignore
}
}
/** Logger instance for this class. */
private static final Log LOG = CmsLog.getLog(CmsClientUserSettingConverter.class);
/** The CMS context to use. */
private CmsObject m_cms;
/** The workplace preferences dialog instance used for loading/saving user settings. */
private CmsPreferences m_preferences;
/** The current request. */
private HttpServletRequest m_request;
/** The macro resolver used for macros in preference property definitions. */
private CmsMacroResolver m_macroResolver = new CmsMacroResolver();
/** The current preferences. */
private CmsDefaultUserSettings m_currentPreferences;
/**
* Creates a new instance.<p>
*
* @param cms the current CMS context
* @param request the current request
* @param response the current response
*/
public CmsClientUserSettingConverter(CmsObject cms, HttpServletRequest request, HttpServletResponse response) {
m_cms = cms;
m_request = request;
m_preferences = new CmsPreferences(new NoJspActionElement(cms, request, response));
m_currentPreferences = new CmsDefaultUserSettings();
m_currentPreferences.init(cms.getRequestContext().getCurrentUser());
m_preferences.setUserSettings(m_currentPreferences);
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
CmsMultiMessages messages = new CmsMultiMessages(locale);
messages.addMessages(OpenCms.getWorkplaceManager().getMessages(locale));
messages.addMessages(org.opencms.workplace.commons.Messages.get().getBundle(locale));
m_macroResolver.setMessages(messages);
}
/**
* Loads the current user's preferences into a CmsUserSettingsBean.<p>
*
* @return the bean representing the current user's preferences
*/
public CmsUserSettingsBean loadSettings() {
CmsUserSettingsBean result = new CmsUserSettingsBean();
CmsDefaultUserSettings currentSettings = new CmsDefaultUserSettings();
currentSettings.init(m_preferences.getUserSettings().getUser());
for (I_CmsPreference pref : OpenCms.getWorkplaceManager().getDefaultUserSettings().getPreferences().values()) {
String tab = pref.getTab();
if (CmsGwtConstants.TAB_HIDDEN.equals(tab)) {
continue;
}
CmsXmlContentProperty prop2 = pref.getPropertyDefinition(m_cms);
String value = pref.getValue(currentSettings);
CmsXmlContentProperty resolvedProp = CmsXmlContentPropertyHelper.resolveMacrosInProperty(
prop2.withDefaultWidget("string"),
m_macroResolver);
result.addSetting(value, resolvedProp, CmsGwtConstants.TAB_BASIC.equals(tab));
}
addAccountInfo(result);
return result;
}
/**
* Saves the given user preference values.<p>
*
* @param settings the user preference values to save
*
* @throws Exception if something goes wrong
*/
public void saveSettings(Map<String, String> settings) throws Exception {
for (Map.Entry<String, String> entry : settings.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
saveSetting(key, value);
}
m_preferences.getUserSettings().save(m_cms);
m_preferences.updatePreferences(m_cms, m_request);
}
/**
* Adds the account information to a user settings bean.<p>
*
* @param prefs the user settings bean to which the information should be added
*/
private void addAccountInfo(CmsUserSettingsBean prefs) {
Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms);
CmsMessages wpMessages = org.opencms.workplace.commons.Messages.get().getBundle(wpLocale);
CmsUser user = m_currentPreferences.getUser();
prefs.addAccountInfo(wpMessages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_USER_0), user.getName());
prefs.addAccountInfo(wpMessages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_EMAIL_0), user.getEmail());
prefs.addAccountInfo(
wpMessages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_LASTNAME_0),
user.getLastname());
prefs.addAccountInfo(
wpMessages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_FIRSTNAME_0),
user.getFirstname());
prefs.addAccountInfo(
wpMessages.key(org.opencms.workplace.commons.Messages.GUI_INPUT_ADRESS_0),
user.getAddress());
prefs.addAccountInfo(
wpMessages.key(org.opencms.workplace.commons.Messages.GUI_LABEL_DESCRIPTION_0),
user.getDescription(wpLocale));
}
/**
* Saves an individual user preference value.<p>
*
* @param key the key of the user preference
* @param value the value of the user preference
*
* @throws Exception if something goes wrong
*/
private void saveSetting(String key, String value) throws Exception {
Map<String, I_CmsPreference> prefs = OpenCms.getWorkplaceManager().getDefaultUserSettings().getPreferences();
if (prefs.containsKey(key)) {
prefs.get(key).setValue(m_currentPreferences, value);
} else {
LOG.error("Can't save user setting '" + key + "'");
}
}
}
| lgpl-2.1 |
deegree/deegree3 | deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/controller/capabilities/serialize/CopySerializer.java | 1922 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2015 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.services.wms.controller.capabilities.serialize;
import static org.apache.commons.io.IOUtils.copy;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Copies exact the incoming stream in the response stream.
*
* @author <a href="mailto:goltz@lat-lon.de">Lyn Goltz</a>
*/
public class CopySerializer implements CapabilitiesSerializer {
@Override
public void serialize( InputStream capabilitiesXmlStream, OutputStream responseStream )
throws IOException {
copy( capabilitiesXmlStream, responseStream );
}
}
| lgpl-2.1 |
threerings/nenya | core/src/main/java/com/threerings/media/timer/PerfTimer.java | 1587 | //
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved
// https://github.com/threerings/nenya
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.media.timer;
import sun.misc.Perf;
/**
* A timer that uses the performance clock exposed by Sun in JDK 1.4.2.
* @deprecated Use {@link NanoTimer} instead.
*/
@Deprecated
// warning: sun.misc.Perf is Sun proprietary API and may be removed in a future release
@SuppressWarnings("all")
public class PerfTimer extends CalibratingTimer
{
public PerfTimer ()
{
_timer = Perf.getPerf();
init(_timer.highResFrequency() / 1000, _timer.highResFrequency() / 1000000);
}
@Override
public long current ()
{
return _timer.highResCounter();
}
/** A performance timer object. */
protected Perf _timer;
}
| lgpl-2.1 |
jstourac/wildfly | testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/weld/alternative/WeldAlternativeTestCase.java | 2293 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.weld.alternative;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* A test of the Jakarta Contexts and Dependency Injection alternatives. This tests that the alternative
* information in the beans.xml file is being parsed correctly.
*
* @author Stuart Douglas
*/
@RunWith(Arquillian.class)
public class WeldAlternativeTestCase {
@Deployment
public static Archive<?> deploy() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class);
jar.addPackage(WeldAlternativeTestCase.class.getPackage());
jar.addAsManifestResource(new StringAsset("<beans><alternatives><class>" + AlternativeBean.class.getName() + "</class></alternatives></beans>"), "beans.xml");
return jar;
}
@Inject
private SimpleBean bean;
@Test
public void testAlternatives() {
Assert.assertEquals("Hello World", bean.sayHello());
}
}
| lgpl-2.1 |
s-match/s-match-core | src/main/java/it/unitn/disi/smatch/matchers/structure/node/NodeMatcherException.java | 539 | package it.unitn.disi.smatch.matchers.structure.node;
import it.unitn.disi.smatch.matchers.structure.tree.TreeMatcherException;
/**
* Exception for Node Matchers.
*
* @author <a rel="author" href="http://autayeu.com/">Aliaksandr Autayeu</a>
*/
public class NodeMatcherException extends TreeMatcherException {
public NodeMatcherException(String errorDescription) {
super(errorDescription);
}
public NodeMatcherException(String errorDescription, Throwable cause) {
super(errorDescription, cause);
}
}
| lgpl-2.1 |
gagoncal/Selenium | Tester/src/test/java/com/LearningSeleniumWithJava/EE/WhenSearchingForDrupalUsingGoogleTest.java | 1587 | package com.LearningSeleniumWithJava.EE;/*
Created by gabrielgoncalves on 22/09/16.
*/
import Pages.GooglePage;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
public class WhenSearchingForDrupalUsingGoogleTest {
private String baseUrl;
private WebDriver driver;
private GooglePage.ScreenshotHelper screenshotHelper;
private GooglePage.WaitForElement waitForElement
private String CSSForText = "div[class='hdtb-mitem hdtb-msel hdtb-imb']"
@Before
public void openBrowser() {
baseUrl = "https://www.google.pt/";
driver = new ChromeDriver();
driver.get(baseUrl);
screenshotHelper = new GooglePage.ScreenshotHelper();
}
@After
public void saveScreenshotAndCloseBrowser() throws IOException {
screenshotHelper.saveScreenshot("screenshot.png");
driver.quit();
}
@Test
public void pageTitleAfterSearchShouldBeginWithDrupal() throws IOException {
Assert.assertEquals("The page title should equal Google at the start of the test.", "Google", driver.getTitle());
WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys("Drupal!");
searchField.submit();
waitForElement = WaitForElements.isElementLoaded(CSSForText);
Assert.assertTrue(driver.getTitle().contains("Drupal"));
}
}
| lgpl-2.1 |
joansmith/orbeon-forms | src/main/java/org/orbeon/oxf/processor/converter/AbstractRewrite.java | 39658 | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* 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 Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor.converter;
import org.orbeon.oxf.externalcontext.URLRewriter;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.ProcessorImpl;
import org.orbeon.oxf.processor.ProcessorInputOutputInfo;
import org.orbeon.oxf.processor.ProcessorOutput;
import org.orbeon.oxf.processor.impl.CacheableTransformerOutputImpl;
import org.orbeon.oxf.util.NetUtils;
import org.orbeon.oxf.util.ScalaUtils;
import org.orbeon.oxf.xml.SAXUtils;
import org.orbeon.oxf.xml.XMLConstants;
import org.orbeon.oxf.xml.XMLReceiver;
import org.orbeon.oxf.xml.saxrewrite.DocumentRootState;
import org.orbeon.oxf.xml.saxrewrite.FragmentRootState;
import org.orbeon.oxf.xml.saxrewrite.State;
import org.orbeon.oxf.xml.saxrewrite.StatefulHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Java impl of oxf-rewrite.xsl. Uses GOF state pattern + SAX to get the job done. The state machine ad hoc and relies a
* bit on the simplicity of the transformation that we are performing.
*
* Wrt the transformation, here is the comment from oxf-rewrite.xsl :
*
* This stylesheet rewrites HTML or XHTML for servlets and portlets. URLs are parsed, so it must be made certain that
* the URLs are well-formed. Absolute URLs are not modified. Relative or absolute paths are supported, as well as the
* special case of a URL starting with a query string (e.g. "?name=value"). This last syntax is supported by most Web
* browsers.
*
* A. For portlets, it does the following:
*
* 1. Rewrite form/@action to WSRP action URL encoding
* 2. Rewrite a/@href and link/@href to WSRP render encoding
* 3. Rewrite img/@src, input[@type='image']/@src and script/@src to WSRP resource URL encoding
* 4. If no form/@method is supplied, force an HTTP POST
* 5. Escape any wsrp_rewrite occurrence in text not within a script or
*
* SCRIPT element to wsrp_rewritewsrp_rewrite. WSRP 1.0 does not appear to specify a particular escape sequence, but we
* use this one in Orbeon Forms Portal. The escaped sequence is recognized by the Orbeon Forms Portlet and restored to
* the original sequence, so it is possible to include the string wsrp_rewrite within documents.
*
* 6. Occurrences of wsrp_rewrite found within script or SCRIPT elements, as well as occurrences within attributes,
* are left untouched. This allows them to be recognized by the Orbeon Forms Portlet and rewritten.
*
* Known issues for portlets:
*
* o The input document should not contain;
* o elements and attribute containing wsrp_rewrite
* o namespace URIs containing wsrp_rewrite
* o processing instructions containing wsrp_rewrite
*
* B. For servlets, it rewrites the URLs to be absolute paths, and prepends the context path.
*/
abstract class AbstractRewrite extends ProcessorImpl {
static final String SCRIPT_ELT = "script";
static final String OBJECT_ELT = "object";
static final String ACTION_ATT = "action";
static final String METHOD_ATT = "method";
static final String HREF_ATT = "href";
static final String SRC_ATT = "src";
static final String BACKGROUND_ATT = "background";
static final String NOREWRITE_ATT = "url-norewrite";
/**
* Base state. Simply forwards data to the destination content handler and returns itself. That is unless the
* (element) depth becomes negative after an end element event. In this case the previous state is returned. This
* means btw that we are really only considering state changes on start and end element events.
*/
protected static abstract class State2 extends State {
/**
* Performs the URL rewrites.
*/
protected final URLRewriter response;
/**
* Could have been another State. However since the value is determined in one state and then used by a
* 'descendant' state doing so would have meant that descendant would have to walk it's ancestors to get the
* value. So, since making this a field instead of a separate State sub-class was easier to implement and is
* faster a field was used.
*/
protected int scriptDepth;
protected final String rewriteURI;
/**
* @param previousState The previous state.
* @param xmlReceiver The destination for the rewrite transformation.
* @param response Used to perform URL rewrites.
* @param scriptDepth How below script elt we are.
* @param rewriteURI URI of elements (i.e. xhtml uri or "") of elements that need rewriting.
*/
State2(final State previousState, final XMLReceiver xmlReceiver, final URLRewriter response,
final int scriptDepth, final String rewriteURI) {
super(previousState, xmlReceiver);
this.response = response;
this.scriptDepth = scriptDepth;
this.rewriteURI = rewriteURI;
}
/**
* Adjusts scriptDepth
*/
final void scriptDepthOnStart(final String ns, final String lnam) {
if (rewriteURI.equals(ns) && SCRIPT_ELT.equals(lnam)) {
scriptDepth++;
}
}
/**
* Adjusts scriptDepth
*/
final void scriptDepthOnEnd(final String ns, final String lnam) {
if (rewriteURI.equals(ns) && SCRIPT_ELT.equals(lnam)) {
scriptDepth--;
}
}
@Override
protected void endElementStart(final String ns, final String lnam, final String qnam)
throws SAXException {
scriptDepthOnEnd(ns, lnam);
super.endElementStart(ns, lnam, qnam);
}
}
/**
* The rewrite state. Essentially this corresponds to the default mode of oxf-rewrite.xsl.
* Basically this:
* <ul>
* <li>Rewrites attributes in start element event when need be.
* <li>Accumulates text from characters events so that proper char content rewriting can
* happen.
* <li>On an event that indicates the end of potentially rewritable text, e.g. start element,
* rewrites and forwards the accumulated characters.
* <li>When explicit no write is indicated, e.g. we see attributes no-rewrite=true, then
* transition to the NoRewriteState.
* </ul>
*/
static class RewriteState extends State2 {
/**
* Used to accumulate characters from characters event. Lazily init'd in characters.
*
* NOTE: We use CharBuffer for historical reasons. Since we support Java 1.5 and up, we could use StringBuilder.
*/
private java.nio.CharBuffer charactersBuf;
private final ArrayList<Boolean> fObjectParent = new ArrayList<Boolean>();
/**
* Calls super( ... ) and initializes wsrprewriteMatcher with "wsrp_rewrite"
*
* @param rewriteURI
*/
RewriteState(final State stt, final XMLReceiver xmlReceiver, final URLRewriter response
, final int scriptDepth, final String rewriteURI) {
super(stt, xmlReceiver, response, scriptDepth, rewriteURI);
}
/**
* Handler for {http://www.w3.org/1999/xhtml}{elt name}. Assumes namespace test has already
* happened. Implements :
* <pre>
* <xsl:template match="xhtml:{elt name}[@{res attrib name}]" >
* <xsl:copy>
* <xsl:copy-of select="@*[namespace-uri() = '']"/>
* <xsl:attribute name="{res attrib name}">
* <xsl:value-of select="context:rewriteResourceURL(@{res attrib name})"/>
* </xsl:attribute>
* <xsl:apply-templates/>
* </xsl:copy>
* </xsl:template>
* </pre>
*
* If match is satisfied then modified event is sent to destination contentHandler.
*
* @return null if match is not satisfied and this otherwise.
* @throws SAXException if destination contentHandler throws SAXException
*/
private State2 handleEltWithResource
(final String elt, final String resAtt, final String ns, final String lnam
, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
done :
if (elt.equals(lnam)) {
final String res = atts.getValue("", resAtt);
if (res == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
final String newRes = response.rewriteResourceURL(res, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", resAtt);
newAtts.setValue(idx, newRes);
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handle xhtml:object
*/
private State2 handleObject
(final String ns, final String lnam
, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
done :
if (OBJECT_ELT.equals(lnam)) {
final String codebaseAttribute = atts.getValue("", "codebase");
final String classidAttribute = atts.getValue("", "classid");
final String dataAttribute = atts.getValue("", "data");
final String usemapAttribute = atts.getValue("", "usemap");
final String archiveAttribute = atts.getValue("", "archive");// space-separated
if (classidAttribute == null && codebaseAttribute == null && dataAttribute == null && usemapAttribute == null && archiveAttribute == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
if (codebaseAttribute != null) {
final String newAttribute = response.rewriteResourceURL(codebaseAttribute, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", "codebase");
newAtts.setValue(idx, newAttribute);
} else {
// We don't rewrite these attributes if there is a codebase
if (classidAttribute != null) {
final String newAttribute = response.rewriteResourceURL(classidAttribute, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", "classid");
newAtts.setValue(idx, newAttribute);
}
if (dataAttribute != null) {
final String newAttribute = response.rewriteResourceURL(dataAttribute, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", "data");
newAtts.setValue(idx, newAttribute);
}
if (usemapAttribute != null) {
final String newAttribute = response.rewriteResourceURL(usemapAttribute, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", "usemap");
newAtts.setValue(idx, newAttribute);
}
if (archiveAttribute != null) {
final StringTokenizer st = new StringTokenizer(archiveAttribute, " ");
final StringBuilder sb = new StringBuilder(archiveAttribute.length() * 2);
boolean first = true;
while (st.hasMoreTokens()) {
final String currentArchive = ScalaUtils.trimAllToEmpty(st.nextToken());
final String newArchive = response.rewriteResourceURL(currentArchive, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
if (!first) {
sb.append(' ');
}
sb.append(newArchive);
first = false;
}
final int idx = newAtts.getIndex("", "archive");
newAtts.setValue(idx, sb.toString());
}
}
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handle xhtml:applet
*/
private State2 handleApplet
(final String ns, final String lnam
, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
done :
if ("applet".equals(lnam)) {
final String codebaseAttribute = atts.getValue("", "codebase");
final String archiveAttribute = atts.getValue("", "archive");// comma-separated
// final String codeAttribute = atts.getValue("", "code");// not clear whether this needs to be rewritten
if (archiveAttribute == null && codebaseAttribute == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
if (codebaseAttribute != null) {
final String newAttribute = response.rewriteResourceURL(codebaseAttribute, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
final int idx = newAtts.getIndex("", "codebase");
newAtts.setValue(idx, newAttribute);
} else {
// We don't rewrite the @archive attribute if there is a codebase
final StringTokenizer st = new StringTokenizer(archiveAttribute, ",");
final StringBuilder sb = new StringBuilder(archiveAttribute.length() * 2);
boolean first = true;
while (st.hasMoreTokens()) {
final String currentArchive = ScalaUtils.trimAllToEmpty(st.nextToken());
final String newArchive = response.rewriteResourceURL(currentArchive, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
if (!first) {
sb.append(' ');
}
sb.append(newArchive);
first = false;
}
final int idx = newAtts.getIndex("", "archive");
newAtts.setValue(idx, sb.toString());
}
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handle xhtml:param
*/
private State2 handleParam
(final String ns, final String lnam
, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
final boolean inObject = fObjectParent.size() >= 2 && fObjectParent.get(fObjectParent.size() - 2).booleanValue();
done :
if (inObject && "param".equals(lnam)) {
final String nameAttribute = atts.getValue("", "name");
final String valueAttribute = atts.getValue("", "value");
if (nameAttribute == null || valueAttribute == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
if ("archive".equals(ScalaUtils.trimAllToEmpty(nameAttribute)))
{
final StringTokenizer st = new StringTokenizer(valueAttribute, ",");
final StringBuilder sb = new StringBuilder(valueAttribute.length() * 2);
boolean first = true;
while (st.hasMoreTokens()) {
final String currentArchive = ScalaUtils.trimAllToEmpty(st.nextToken());
final String newArchive = response.rewriteResourceURL(currentArchive, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
if (!first) {
sb.append(' ');
}
sb.append(newArchive);
first = false;
}
final int idx = newAtts.getIndex("", "value");
newAtts.setValue(idx, sb.toString());
}
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handler for {http://www.w3.org/1999/xhtml}a. Assumes namespace test has already
* happened. Implements :
* <pre>
* <xsl:template match="xhtml:a[@href]" >
* <xsl:copy>
* <xsl:copy-of select="@*[namespace-uri() = '']"/>
* <xsl:attribute name="href">
* <xsl:choose>
* <xsl:when test="not(@f:url-type) or @f:url-type = 'render'">
* <xsl:value-of select="context:rewriteRenderURL(@href)"/>
* </xsl:when>
* <xsl:when test="@f:url-type = 'action'">
* <xsl:value-of select="context:rewriteActionURL(@href)"/>
* </xsl:when>
* <xsl:when test="@f:url-type = 'resource'">
* <xsl:value-of select="context:rewriteResourceURL(@href)"/>
* </xsl:when>
* </xsl:choose>
* </xsl:attribute>
* <xsl:apply-templates/>
* </xsl:copy>
* </xsl:template>
* </pre>
*
* If match is satisfied then modified event is sent to destination contentHandler.
*
* @return null if match is not satisfied and this otherwise.
* @throws SAXException if destination contentHandler throws SAXException
*/
private State2 handleA
(final String ns, final String lnam, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
done :
if ("a".equals(lnam)) {
final String href = atts.getValue("", HREF_ATT);
if (href == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
final String urlType = atts.getValue(XMLConstants.OPS_FORMATTING_URI, "url-type");
final String portletMode = atts.getValue(XMLConstants.OPS_FORMATTING_URI, "portlet-mode");
final String windowState = atts.getValue(XMLConstants.OPS_FORMATTING_URI, "window-state");
final String newHref;
if (urlType == null || "render".equals(urlType)) {
newHref = response.rewriteRenderURL(href, portletMode, windowState);
} else if ("action".equals(urlType)) {
newHref = response.rewriteActionURL(href, portletMode, windowState);
} else if ("resource".equals(urlType)) {
newHref = response.rewriteResourceURL(href, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
} else {
newHref = null;
}
final int idx = newAtts.getIndex("", HREF_ATT);
if (newHref == null && idx != -1) {
newAtts.removeAttribute(idx);
} else {
newAtts.setValue(idx, newHref);
}
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handler for {http://www.w3.org/1999/xhtml}area. Assumes namespace test has already
* happened. Implements :
* <pre>
* <xsl:template match="xhtml:area[@href]" >
* <xsl:copy>
* <xsl:copy-of select="@*[namespace-uri() = '']"/>
* <xsl:attribute name="href">
* <xsl:value-of select="context:rewriteActionURL(@href)"/>
* </xsl:attribute>
* <xsl:apply-templates/>
* </xsl:copy>
* </xsl:template>
* </pre>
*
* If match is satisfied then modified event is sent to destination contentHandler.
*
* @return null if match is not satisfied and this otherwise.
* @throws SAXException if destination contentHandler throws SAXException
*/
private State2 handleArea
(final String ns, final String lnam, final String qnam, final Attributes atts)
throws SAXException {
State2 ret = null;
done :
if ("area".equals(lnam)) {
final String href = atts.getValue("", HREF_ATT);
if (href == null) break done;
ret = this;
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
final String newHref = response.rewriteActionURL(href);
final int idx = newAtts.getIndex("", HREF_ATT);
newAtts.setValue(idx, newHref);
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
}
return ret;
}
/**
* Handler for {http://www.w3.org/1999/xhtml}input. Assumes namespace test has already
* happened. Implements :
* <pre>
* <xsl:template match="xhtml:input[@type='image' and @src]" >
* <xsl:copy>
* <xsl:copy-of select="@*[namespace-uri() = '']"/>
* <xsl:attribute name="src">
* <xsl:value-of select="context:rewriteActionURL(@src)"/>
* </xsl:attribute>
* <xsl:apply-templates/>
* </xsl:copy>
* </xsl:template>
* </pre>
*
* If match is satisfied then modified event is sent to destination contentHandler.
*
* @return null if @type='image' test is not satisfied and
* handleEltWithResource( "input", "src", ... ) otherwise.
* @throws SAXException if destination contentHandler throws SAXException
*/
private State2 handleInput
(final String ns, final String lnam, final String qnam, final Attributes atts)
throws SAXException {
final State2 ret;
final String typ = atts.getValue("", "type");
if ("image".equals(typ)) {
ret = handleEltWithResource("input", SRC_ATT, ns, lnam, qnam, atts);
} else {
ret = null;
}
return ret;
}
/**
* Handler for {http://www.w3.org/1999/xhtml}form. Assumes namespace test has already
* happened. Implements :
* <pre>
* <xsl:template match="form | xhtml:form">
* <xsl:copy>
* <xsl:copy-of select="@*[namespace-uri() = '']"/>
* <xsl:choose>
* <xsl:when test="@action">
* <xsl:attribute name="action">
* <xsl:value-of select="context:rewriteActionURL(@action)"/>
* </xsl:attribute>
* </xsl:when>
* <xsl:otherwise>
* <xsl:attribute name="action">
* <xsl:value-of select="context:rewriteActionURL('')"/>
* </xsl:attribute>
* </xsl:otherwise>
* </xsl:choose>
* <!-- Default is POST instead of GET for portlets -->
* <xsl:if test="not(@method) and $container-type/* = 'portlet'">
* <xsl:attribute name="method">post</xsl:attribute>
* </xsl:if>
* <xsl:apply-templates/>
* </xsl:copy>
* </xsl:template>
* </pre>
*
* If match is satisfied then modified event is sent to destination contentHandler.
*
* @return null match is not satisfied, this otherwise.
* @throws SAXException if destination contentHandler throws SAXException
*/
private State2 handleForm
(final String ns, final String lnam, final String qnam, final Attributes atts)
throws SAXException {
final State2 ret;
if ("form".equals(lnam)) {
final AttributesImpl newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
final String actn = newAtts.getValue("", ACTION_ATT);
final String newActn;
if (actn == null) {
newActn = response.rewriteActionURL("");
newAtts.addAttribute("", ACTION_ATT, ACTION_ATT, "", newActn);
} else {
final int idx = newAtts.getIndex("", ACTION_ATT);
newActn = response.rewriteActionURL(actn);
newAtts.setValue(idx, newActn);
}
if (atts.getValue("", METHOD_ATT) == null) {
newAtts.addAttribute("", METHOD_ATT, METHOD_ATT, "", "post");
}
ret = this;
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
} else {
ret = null;
}
return ret;
}
/**
* If we have accumulated character data rewrite it and forward it. Implements :
* <pre>
* <xsl:template match="text()">
* <xsl:value-of
* select="replace(current(), 'wsrp_rewrite', 'wsrp_rewritewsrp_rewrite')"/>
* <xsl:apply-templates/>
* </xsl:template>
* </pre>
* If there no character data has been accumulated do nothing. Also clears buffer.
*/
private void flushCharacters() throws SAXException {
final int bfLen = charactersBuf == null ? 0 : charactersBuf.position();
if (bfLen > 0) {
charactersBuf.flip();
final char[] chs = charactersBuf.array();
final int chsStrt = charactersBuf.arrayOffset();
int last = 0;
if (last < bfLen) {
final int len = bfLen - last;
xmlReceiver.characters(chs, chsStrt + last, len);
}
charactersBuf.clear();
}
}
/**
* Just calls flushCharacters and super.endElement( ... )
*/
@Override
protected void endElementStart(final String ns, final String lnam, final String qnam)
throws SAXException {
fObjectParent.remove(fObjectParent.size() - 1);
flushCharacters();
super.endElementStart(ns, lnam, qnam);
}
/**
* Just calls flushCharacters then tests the event data. If
* <ul>
* <li>
*
* @url-norewrite='true' then forward the event to the destination content handler and
* return new NoRewriteState( ... ), otherwise
* </li>
* <li>
* if ns.equals( XHTML_URI ) then
* <ul>
* <li>if one of the handleXXX methods returns non-null do nothing, otherwise</li>
* <li>
* forward the event to the destination content handler and return this, otherwise
* </li>
* </ul>
* </li>
* <li>
* if the element is {http://orbeon.org/oxf/xml/formatting}rewrite then implement :
* <pre>
* <xsl:choose>
* <xsl:when test="@type = 'action'">
* <xsl:value-of select="context:rewriteActionURL(@url)"/>
* </xsl:when>
* <xsl:when test="@type = 'render'">
* <xsl:value-of select="context:rewriteRenderURL(@url)"/>
* </xsl:when>
* <xsl:otherwise>
* <xsl:value-of select="context:rewriteResourceURL(@url)"/>
* </xsl:otherwise>
* </xsl:choose>
* </pre>
* Note this means that we forward characters to the destination content handler instead
* of a start element event, otherwise
* </li>
* <li>
* simply forward the event as is to the destination content handler and return this.
* </li>
* </ul>
*/
protected State startElementStart(final String ns, final String lnam, final String qnam, Attributes atts) throws SAXException {
fObjectParent.add(Boolean.valueOf(OBJECT_ELT.equals(lnam) && XMLConstants.XHTML_NAMESPACE_URI.equals(ns)));
final int noRewriteIndex = atts.getIndex(XMLConstants.OPS_FORMATTING_URI, NOREWRITE_ATT);
final String noRewriteValue = atts.getValue(noRewriteIndex);
State ret = null;
flushCharacters();
if (noRewriteValue != null) {
// Remove f:url-norewrite attribute
final AttributesImpl attributesImpl = new AttributesImpl(atts);
attributesImpl.removeAttribute(noRewriteIndex);
atts = attributesImpl;
}
done :
if ("true".equals(noRewriteValue)) {
final State stt = new NoRewriteState(this, xmlReceiver, response, scriptDepth, rewriteURI);
ret = stt.startElement(ns, lnam, qnam, atts);
} else if (XMLConstants.OPS_FORMATTING_URI.equals(ns) && "rewrite".equals(lnam)) {
final String typ = atts.getValue("", "type");
final String url = atts.getValue("", "url");
if (url != null) {
final String newURL;
if ("action".equals(typ)) {
newURL = response.rewriteActionURL(url);
} else if ("render".equals(typ)) {
newURL = response.rewriteRenderURL(url);
} else {
newURL = response.rewriteResourceURL(url, ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE);
}
final char[] chs = newURL.toCharArray();
xmlReceiver.characters(chs, 0, chs.length);
}
} else {
scriptDepthOnStart(ns, lnam);
if (rewriteURI.equals(ns)) {
ret = handleA(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleForm(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleArea(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("link", HREF_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("img", SRC_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("frame", SRC_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("iframe", SRC_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource(SCRIPT_ELT, SRC_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleInput(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("td", BACKGROUND_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleEltWithResource("body", BACKGROUND_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleObject(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleApplet(ns, lnam, qnam, atts);
if (ret != null) break done;
ret = handleParam(ns, lnam, qnam, atts);
if (ret != null) break done;
// Not valid in HTML, but useful for e.g. Dojo contentPane
ret = handleEltWithResource("div", HREF_ATT, ns, lnam, qnam, atts);
if (ret != null) break done;
}
ret = this;
xmlReceiver.startElement(ns, lnam, qnam, atts);
}
return ret;
}
/**
* If haveScriptAncestor then just forward data to destination contentHandler. Otherwise store that data in the
* buffer and do not forward. Also manages init'ing and growing charactersBuf as need be.
*/
@Override
public State characters(final char[] ch, final int strt, final int len)
throws SAXException {
if (scriptDepth > 0) {
xmlReceiver.characters(ch, strt, len);
} else {
final int bufLen = charactersBuf == null ? 0 : charactersBuf.position();
final int cpcty = bufLen + (len * 2);
if (charactersBuf == null || charactersBuf.remaining() < cpcty) {
final java.nio.CharBuffer newBuf = java.nio.CharBuffer.allocate(cpcty);
if (charactersBuf != null) {
charactersBuf.flip();
newBuf.put(charactersBuf);
}
charactersBuf = newBuf;
}
charactersBuf.put(ch, strt, len);
}
return this;
}
/**
* Just calls flushCharacters and super.ignorableWhitespace( ... )
*/
@Override
public State ignorableWhitespace(final char[] ch, final int strt, final int len)
throws SAXException {
flushCharacters();
return super.ignorableWhitespace(ch, strt, len);
}
/**
* Just calls flushCharacters and super.processingInstruction( ... )
*/
@Override
public State processingInstruction(final String trgt, final String dat)
throws SAXException {
flushCharacters();
return super.processingInstruction(trgt, dat);
}
/**
* Just calls flushCharacters and super.skippedEntity( ... )
*/
@Override
public State skippedEntity(final String nam) throws SAXException {
flushCharacters();
return super.skippedEntity(nam);
}
}
/**
* Essentially this corresponds to the norewrite mode of oxf-rewrite.xsl. i.e. Just forwards events to the
* destination content handler until we finish the initial element (depth < 0) or until it encounters
* @url-norewrite='false'. In the first case transitions to the previous state and in the second case it transitions
* to new RewriteState(this, contentHandler, response, haveScriptAncestor).
*/
static class NoRewriteState extends State2 {
NoRewriteState(final State2 previousState, final XMLReceiver xmlReceiver, final URLRewriter response,
final int scriptDepth, final String rewriteURI) {
super(previousState, xmlReceiver, response, scriptDepth, rewriteURI);
}
protected State startElementStart(final String ns, final String lnam, final String qnam, Attributes atts) throws SAXException {
final int noRewriteIndex = atts.getIndex(XMLConstants.OPS_FORMATTING_URI, NOREWRITE_ATT);
final String noRewriteValue = atts.getValue(noRewriteIndex);
final State ret;
if (noRewriteValue != null) {
// Remove f:url-norewrite attribute
final AttributesImpl attributesImpl = new AttributesImpl(atts);
attributesImpl.removeAttribute(noRewriteIndex);
atts = attributesImpl;
}
if ("false".equals(noRewriteValue)) {
final State stt = new RewriteState(this, xmlReceiver, response, scriptDepth, rewriteURI);
ret = stt.startElement(ns, lnam, qnam, atts);
} else {
scriptDepthOnStart(ns, lnam);
final Attributes newAtts = SAXUtils.getAttributesFromDefaultNamespace(atts);
xmlReceiver.startElement(ns, lnam, qnam, newAtts);
ret = this;
}
return ret;
}
}
/**
* Namespace of the elements that are to be rewritten.
*/
final String rewriteURI;
/**
* Just declares input 'data' and output 'data'.
*
* @param rewriteURI e.g. "http://www.w3.org/1999/xhtml" or ""
*/
public AbstractRewrite(final String rewriteURI) {
this.rewriteURI = rewriteURI;
addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
@Override
public ProcessorOutput createOutput(final String name) {
final ProcessorOutput processorOutput = new CacheableTransformerOutputImpl(AbstractRewrite.this, name) {
public void readImpl(final PipelineContext pipelineContext, final XMLReceiver xmlReceiver) {
readInputAsSAX(pipelineContext, INPUT_DATA, getRewriteXMLReceiver(NetUtils.getExternalContext().getResponse(), xmlReceiver, false));
}
};
addOutput(name, processorOutput);
return processorOutput;
}
public XMLReceiver getRewriteXMLReceiver(final URLRewriter rewriter, final XMLReceiver xmlReceiver, final boolean fragment) {
final State rootState;
if (fragment) {
// Start directly with rewrite state
final FragmentRootState fragmentRootState = new FragmentRootState(null, xmlReceiver);
final State afterRootState = new RewriteState(fragmentRootState, xmlReceiver, rewriter, 0, rewriteURI);
fragmentRootState.setNextState(afterRootState);
rootState = fragmentRootState;
} else {
// Start with root filter
final DocumentRootState documentRootState = new DocumentRootState(null, xmlReceiver);
final State afterRootState = new RewriteState(documentRootState, xmlReceiver, rewriter, 0, rewriteURI);
documentRootState.setNextState(afterRootState);
rootState = documentRootState;
}
return new StatefulHandler(rootState);
}
}
| lgpl-2.1 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/contextmenu/CmsResourceInfo.java | 2870 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) Alkacon Software (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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.opencms.gwt.client.ui.contextmenu;
import org.opencms.gwt.client.ui.resourceinfo.CmsResourceInfoDialog;
import org.opencms.gwt.shared.CmsContextMenuEntryBean;
import org.opencms.util.CmsUUID;
import java.util.HashMap;
/**
* Context menu entry for displaying resource information.<p>
*/
public class CmsResourceInfo implements I_CmsHasContextMenuCommand, I_CmsContextMenuCommand {
/**
* Gets the context menu command instance.<p>
*
* @return the context menu command instance
*/
public static I_CmsContextMenuCommand getContextMenuCommand() {
return new CmsResourceInfo();
}
/**
* @see org.opencms.gwt.client.ui.contextmenu.I_CmsContextMenuCommand#execute(org.opencms.util.CmsUUID, org.opencms.gwt.client.ui.contextmenu.I_CmsContextMenuHandler, org.opencms.gwt.shared.CmsContextMenuEntryBean)
*/
public void execute(CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) {
CmsResourceInfoDialog.load(structureId, true, null, new HashMap<String, String>(), null);
}
/**
* @see org.opencms.gwt.client.ui.contextmenu.I_CmsContextMenuCommand#getItemWidget(org.opencms.util.CmsUUID, org.opencms.gwt.client.ui.contextmenu.I_CmsContextMenuHandler, org.opencms.gwt.shared.CmsContextMenuEntryBean)
*/
public A_CmsContextMenuItem getItemWidget(
CmsUUID structureId,
I_CmsContextMenuHandler handler,
CmsContextMenuEntryBean bean) {
return null;
}
/**
* @see org.opencms.gwt.client.ui.contextmenu.I_CmsContextMenuCommand#hasItemWidget()
*/
public boolean hasItemWidget() {
return false;
}
}
| lgpl-2.1 |
sbonoc/opencms-core | src-gwt/org/opencms/acacia/client/widgets/CmsLocalizationWidgetFactory.java | 2433 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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.opencms.acacia.client.widgets;
import org.opencms.acacia.client.I_CmsWidgetFactory;
import org.opencms.ade.contenteditor.widgetregistry.client.WidgetRegistry;
import org.opencms.gwt.client.I_CmsHasInit;
import com.google.gwt.dom.client.Element;
/**
* Factory to generate basic input widget.<p>
*/
public class CmsLocalizationWidgetFactory implements I_CmsWidgetFactory, I_CmsHasInit {
/** The widget name. */
private static final String WIDGET_NAME = "org.opencms.widgets.CmsLocalizationWidget";
/**
* Initializes this class.<p>
*/
public static void initClass() {
WidgetRegistry.getInstance().registerWidgetFactory(WIDGET_NAME, new CmsLocalizationWidgetFactory());
}
/**
* @see org.opencms.acacia.client.I_CmsWidgetFactory#createFormWidget(java.lang.String)
*/
public I_CmsFormEditWidget createFormWidget(String configuration) {
return new CmsFormWidgetWrapper(new CmsTextboxWidget(configuration));
}
/**
* @see org.opencms.acacia.client.I_CmsWidgetFactory#createInlineWidget(java.lang.String, com.google.gwt.dom.client.Element)
*/
public I_CmsEditWidget createInlineWidget(String configuration, Element element) {
return null;
}
}
| lgpl-2.1 |
elkafoury/tux | src/org/eclipse/swt/browser/FilePicker.java | 10726 | /*******************************************************************************
* Copyright (c) 2003, 2012 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.swt.browser;
import org.eclipse.swt.SWT;
import org.eclipse.swt.internal.*;
import org.eclipse.swt.internal.mozilla.*;
import org.eclipse.swt.widgets.*;
class FilePicker {
XPCOMObject supports;
XPCOMObject filePicker;
int refCount = 0;
short mode;
int /*long*/ parentHandle;
String[] files, masks;
String defaultFilename, directory, title;
static final String SEPARATOR = System.getProperty ("file.separator"); //$NON-NLS-1$
FilePicker () {
createCOMInterfaces ();
}
int AddRef () {
refCount++;
return refCount;
}
void createCOMInterfaces () {
/* Create each of the interfaces that this object implements */
supports = new XPCOMObject (new int[] {2, 0, 0}) {
public int /*long*/ method0 (int /*long*/[] args) {return QueryInterface (args[0], args[1]);}
public int /*long*/ method1 (int /*long*/[] args) {return AddRef ();}
public int /*long*/ method2 (int /*long*/[] args) {return Release ();}
};
filePicker = new XPCOMObject (new int[] {2, 0, 0, 3, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) {
public int /*long*/ method0 (int /*long*/[] args) {return QueryInterface (args[0], args[1]);}
public int /*long*/ method1 (int /*long*/[] args) {return AddRef ();}
public int /*long*/ method2 (int /*long*/[] args) {return Release ();}
public int /*long*/ method3 (int /*long*/[] args) {return Init (args[0], args[1], (short)args[2]);}
public int /*long*/ method4 (int /*long*/[] args) {return AppendFilters ((int)/*64*/args[0]);}
public int /*long*/ method5 (int /*long*/[] args) {return AppendFilter (args[0], args[1]);}
public int /*long*/ method6 (int /*long*/[] args) {return GetDefaultString (args[0]);}
public int /*long*/ method7 (int /*long*/[] args) {return SetDefaultString (args[0]);}
public int /*long*/ method8 (int /*long*/[] args) {return GetDefaultExtension (args[0]);}
public int /*long*/ method9 (int /*long*/[] args) {return SetDefaultExtension (args[0]);}
public int /*long*/ method10 (int /*long*/[] args) {return GetFilterIndex (args[0]);}
public int /*long*/ method11 (int /*long*/[] args) {return SetFilterIndex ((int)/*64*/args[0]);}
public int /*long*/ method12 (int /*long*/[] args) {return GetDisplayDirectory (args[0]);}
public int /*long*/ method13 (int /*long*/[] args) {return SetDisplayDirectory (args[0]);}
public int /*long*/ method14 (int /*long*/[] args) {return GetFile (args[0]);}
public int /*long*/ method15 (int /*long*/[] args) {return GetFileURL (args[0]);}
public int /*long*/ method16 (int /*long*/[] args) {return GetFiles (args[0]);}
public int /*long*/ method17 (int /*long*/[] args) {return Show (args[0]);}
};
}
void disposeCOMInterfaces () {
if (supports != null) {
supports.dispose ();
supports = null;
}
if (filePicker != null) {
filePicker.dispose ();
filePicker = null;
}
}
int /*long*/ getAddress () {
return filePicker.getAddress ();
}
int QueryInterface (int /*long*/ riid, int /*long*/ ppvObject) {
if (riid == 0 || ppvObject == 0) return XPCOM.NS_ERROR_NO_INTERFACE;
nsID guid = new nsID ();
XPCOM.memmove (guid, riid, nsID.sizeof);
if (guid.Equals (nsISupports.NS_ISUPPORTS_IID)) {
XPCOM.memmove (ppvObject, new int /*long*/[] {supports.getAddress ()}, C.PTR_SIZEOF);
AddRef ();
return XPCOM.NS_OK;
}
if (guid.Equals (nsIFilePicker.NS_IFILEPICKER_IID)) {
XPCOM.memmove(ppvObject, new int /*long*/[] {filePicker.getAddress ()}, C.PTR_SIZEOF);
AddRef ();
return XPCOM.NS_OK;
}
if (guid.Equals (nsIFilePicker_1_8.NS_IFILEPICKER_IID)) {
XPCOM.memmove(ppvObject, new int /*long*/[] {filePicker.getAddress ()}, C.PTR_SIZEOF);
AddRef ();
return XPCOM.NS_OK;
}
if (guid.Equals (nsIFilePicker_1_8.NS_IFILEPICKER_10_IID)) {
XPCOM.memmove(ppvObject, new int /*long*/[] {filePicker.getAddress ()}, C.PTR_SIZEOF);
AddRef ();
return XPCOM.NS_OK;
}
XPCOM.memmove (ppvObject, new int /*long*/[] {0}, C.PTR_SIZEOF);
return XPCOM.NS_ERROR_NO_INTERFACE;
}
int Release () {
refCount--;
if (refCount == 0) disposeCOMInterfaces ();
return refCount;
}
Browser getBrowser (int /*long*/ aDOMWindow) {
if (aDOMWindow == 0) return null;
return Mozilla.getBrowser (aDOMWindow);
}
/*
* As of Mozilla 1.8 some of nsIFilePicker's string arguments changed type. This method
* answers a java string based on the type of string that is appropriate for the Mozilla
* version being used.
*/
String parseAString (int /*long*/ string) {
return null;
}
/* nsIFilePicker */
int Init (int /*long*/ parent, int /*long*/ title, short mode) {
parentHandle = parent;
this.mode = mode;
this.title = parseAString (title);
return XPCOM.NS_OK;
}
int Show (int /*long*/ _retval) {
if (mode == nsIFilePicker.modeGetFolder) {
/* picking a directory */
int result = showDirectoryPicker ();
XPCOM.memmove (_retval, new short[] {(short)result}, 2); /* PRInt16 */
return XPCOM.NS_OK;
}
/* picking a file */
int style = mode == nsIFilePicker.modeSave ? SWT.SAVE : SWT.OPEN;
if (mode == nsIFilePicker.modeOpenMultiple) style |= SWT.MULTI;
Browser browser = getBrowser (parentHandle);
Shell parent = null;
if (browser != null) {
parent = browser.getShell ();
} else {
parent = new Shell ();
}
FileDialog dialog = new FileDialog (parent, style);
if (title != null) dialog.setText (title);
if (directory != null) dialog.setFilterPath (directory);
if (masks != null) dialog.setFilterExtensions (masks);
if (defaultFilename != null) dialog.setFileName (defaultFilename);
String filename = dialog.open ();
files = dialog.getFileNames ();
directory = dialog.getFilterPath ();
title = defaultFilename = null;
masks = null;
int result = filename == null ? nsIFilePicker.returnCancel : nsIFilePicker.returnOK;
XPCOM.memmove (_retval, new short[] {(short)result}, 2); /* PRInt16 */
return XPCOM.NS_OK;
}
int showDirectoryPicker () {
Browser browser = getBrowser (parentHandle);
Shell parent = null;
if (browser != null) {
parent = browser.getShell ();
} else {
parent = new Shell ();
}
DirectoryDialog dialog = new DirectoryDialog (parent, SWT.NONE);
if (title != null) dialog.setText (title);
if (directory != null) dialog.setFilterPath (directory);
directory = dialog.open ();
title = defaultFilename = null;
files = masks = null;
return directory == null ? nsIFilePicker.returnCancel : nsIFilePicker.returnOK;
}
int GetFiles (int /*long*/ aFiles) {
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int GetFileURL (int /*long*/ aFileURL) {
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int GetFile (int /*long*/ aFile) {
String filename = ""; //$NON-NLS-1$
if (directory != null) filename += directory + SEPARATOR;
if (files != null && files.length > 0) filename += files[0];
nsEmbedString path = new nsEmbedString (filename);
int /*long*/[] file = new int /*long*/[1];
int rc = XPCOM.NS_NewLocalFile (path.getAddress (), 1, file);
path.dispose ();
if (rc != XPCOM.NS_OK) Mozilla.error (rc);
if (file[0] == 0) Mozilla.error (XPCOM.NS_ERROR_NULL_POINTER);
XPCOM.memmove (aFile, file, C.PTR_SIZEOF);
return XPCOM.NS_OK;
}
int SetDisplayDirectory (int /*long*/ aDisplayDirectory) {
if (aDisplayDirectory == 0) return XPCOM.NS_OK;
nsILocalFile file = new nsILocalFile (aDisplayDirectory);
int /*long*/ pathname = XPCOM.nsEmbedString_new ();
int rc = file.GetPath (pathname);
if (rc != XPCOM.NS_OK) Mozilla.error (rc);
int length = XPCOM.nsEmbedString_Length (pathname);
int /*long*/ buffer = XPCOM.nsEmbedString_get (pathname);
char[] chars = new char[length];
XPCOM.memmove (chars, buffer, length * 2);
XPCOM.nsEmbedString_delete (pathname);
directory = new String (chars);
return XPCOM.NS_OK;
}
int GetDisplayDirectory (int /*long*/ aDisplayDirectory) {
String directoryName = directory != null ? directory : ""; //$NON-NLS-1$
nsEmbedString path = new nsEmbedString (directoryName);
int /*long*/[] file = new int /*long*/[1];
int rc = XPCOM.NS_NewLocalFile (path.getAddress (), 1, file);
path.dispose ();
if (rc != XPCOM.NS_OK) Mozilla.error (rc);
if (file[0] == 0) Mozilla.error (XPCOM.NS_ERROR_NULL_POINTER);
XPCOM.memmove (aDisplayDirectory, file, C.PTR_SIZEOF);
return XPCOM.NS_OK;
}
int SetFilterIndex (int aFilterIndex) {
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int GetFilterIndex (int /*long*/ aFilterIndex) {
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int SetDefaultExtension (int /*long*/ aDefaultExtension) {
/* note that the type of argument 1 changed as of Mozilla 1.8 */
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int GetDefaultExtension (int /*long*/ aDefaultExtension) {
/* note that the type of argument 1 changed as of Mozilla 1.8 */
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int SetDefaultString (int /*long*/ aDefaultString) {
defaultFilename = parseAString (aDefaultString);
return XPCOM.NS_OK;
}
int GetDefaultString (int /*long*/ aDefaultString) {
/* note that the type of argument 1 changed as of Mozilla 1.8 */
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int AppendFilter (int /*long*/ title, int /*long*/ filter) {
/* note that the type of arguments 1 and 2 changed as of Mozilla 1.8 */
return XPCOM.NS_ERROR_NOT_IMPLEMENTED;
}
int AppendFilters (int filterMask) {
String[] addFilters = null;
switch (filterMask) {
case nsIFilePicker.filterAll:
case nsIFilePicker.filterApps:
masks = null; /* this is equivalent to no filter */
break;
case nsIFilePicker.filterHTML:
addFilters = new String[] {"*.htm;*.html"}; //$NON-NLS-1$
break;
case nsIFilePicker.filterImages:
addFilters = new String[] {"*.gif;*.jpeg;*.jpg;*.png"}; //$NON-NLS-1$
break;
case nsIFilePicker.filterText:
addFilters = new String[] {"*.txt"}; //$NON-NLS-1$
break;
case nsIFilePicker.filterXML:
addFilters = new String[] {"*.xml"}; //$NON-NLS-1$
break;
case nsIFilePicker.filterXUL:
addFilters = new String[] {"*.xul"}; //$NON-NLS-1$
break;
}
if (masks == null) {
masks = addFilters;
} else {
if (addFilters != null) {
String[] newFilters = new String[masks.length + addFilters.length];
System.arraycopy (masks, 0, newFilters, 0, masks.length);
System.arraycopy (addFilters, 0, newFilters, masks.length, addFilters.length);
masks = newFilters;
}
}
return XPCOM.NS_OK;
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | designer/datasource-editor-scriptable/src/main/java/org/pentaho/reporting/ui/datasources/scriptable/ScriptableDataSourceEditor.java | 23728 | /*!
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.ui.datasources.scriptable;
import org.apache.bsf.BSFManager;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeContext;
import org.pentaho.reporting.engine.classic.core.designtime.datafactory.DataFactoryEditorSupport;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.ExceptionDialog;
import org.pentaho.reporting.engine.classic.core.util.ReportParameterValues;
import org.pentaho.reporting.engine.classic.extensions.datasources.scriptable.ScriptableDataFactory;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.libraries.designtime.swing.BorderlessButton;
import org.pentaho.reporting.libraries.designtime.swing.CommonDialog;
import org.pentaho.reporting.libraries.designtime.swing.background.CancelEvent;
import org.pentaho.reporting.libraries.designtime.swing.background.DataPreviewDialog;
import org.pentaho.reporting.libraries.designtime.swing.background.PreviewWorker;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* @author David Kincade
*/
public class ScriptableDataSourceEditor extends CommonDialog {
private class UpdateLanguageHandler implements ActionListener, ListSelectionListener {
private UpdateLanguageHandler() {
}
public void actionPerformed( final ActionEvent e ) {
updateComponents();
}
/**
* Called whenever the value of the selection changes.
*
* @param e the event that characterizes the change.
*/
public void valueChanged( final ListSelectionEvent e ) {
updateComponents();
}
}
private static class InternalBSFManager extends BSFManager {
private InternalBSFManager() {
}
public static String[] getRegisteredLanguages() {
final ArrayList<String> list = new ArrayList<String>();
final Iterator iterator = registeredEngines.entrySet().iterator();
while ( iterator.hasNext() ) {
final Map.Entry entry = (Map.Entry) iterator.next();
final String lang = (String) entry.getKey();
final String className = (String) entry.getValue();
try {
// this is how BSH will load the class
Class.forName( className, false, Thread.currentThread().getContextClassLoader() );
list.add( lang );
} catch ( Throwable t ) {
// ignored.
}
}
return list.toArray( new String[ list.size() ] );
}
}
private class QueryRemoveAction extends AbstractAction implements ListSelectionListener {
private QueryRemoveAction() {
final URL resource = ScriptableDataSourceEditor.class.getResource
( "/org/pentaho/reporting/ui/datasources/scriptable/resources/Remove.png" );
if ( resource != null ) {
putValue( Action.SMALL_ICON, new ImageIcon( resource ) );
} else {
putValue( Action.NAME, Messages.getString( "ScriptableDataSourceEditor.RemoveQuery.Name" ) );
}
putValue( Action.SHORT_DESCRIPTION, Messages.getString( "ScriptableDataSourceEditor.RemoveQuery.Description" ) );
}
public void actionPerformed( final ActionEvent e ) {
final DataSetQuery query = (DataSetQuery) queryNameList.getSelectedValue();
if ( query != null ) {
queries.remove( query.getQueryName() );
}
inModifyingQueryNameList = true;
updateQueryList();
queryNameList.clearSelection();
inModifyingQueryNameList = false;
updateComponents();
}
public void valueChanged( final ListSelectionEvent e ) {
setEnabled( queryNameList.isSelectionEmpty() == false );
}
}
private class QueryNameTextFieldDocumentListener implements DocumentListener {
public void insertUpdate( final DocumentEvent e ) {
update();
}
public void removeUpdate( final DocumentEvent e ) {
update();
}
public void changedUpdate( final DocumentEvent e ) {
update();
}
private void update() {
if ( inModifyingQueryNameList ) {
return;
}
final String queryName = queryNameTextField.getText();
final DataSetQuery currentQuery = (DataSetQuery) queryNameList.getSelectedValue();
if ( currentQuery == null ) {
return;
}
if ( queryName.equals( currentQuery.getQueryName() ) ) {
return;
}
if ( queries.containsKey( queryName ) ) {
return;
}
inQueryNameUpdate = true;
queries.remove( currentQuery.getQueryName() );
currentQuery.setQueryName( queryName );
queries.put( currentQuery.getQueryName(), currentQuery );
updateQueryList();
queryNameList.setSelectedValue( currentQuery, true );
inQueryNameUpdate = false;
}
}
private static class QueryNameListCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent( final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus ) {
final JLabel listCellRendererComponent =
(JLabel) super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus );
if ( value != null ) {
final String queryName = ( (DataSetQuery) value ).getQueryName();
if ( StringUtils.isEmpty( queryName ) == false ) {
listCellRendererComponent.setText( queryName );
} else {
listCellRendererComponent.setText( " " );
}
}
return listCellRendererComponent;
}
}
private class QueryNameListSelectionListener implements ListSelectionListener {
public void valueChanged( final ListSelectionEvent e ) {
if ( !inQueryNameUpdate ) {
final DataSetQuery query = (DataSetQuery) queryNameList.getSelectedValue();
if ( query != null ) {
queryNameTextField.setText( query.getQueryName() );
queryTextArea.setText( query.getQuery() );
updateComponents();
} else {
queryNameTextField.setText( "" );
queryTextArea.setText( "" );
updateComponents();
}
}
}
}
private class QueryAddAction extends AbstractAction {
private QueryAddAction() {
final URL resource = ScriptableDataSourceEditor.class.getResource
( "/org/pentaho/reporting/ui/datasources/scriptable/resources/Add.png" );
if ( resource != null ) {
putValue( Action.SMALL_ICON, new ImageIcon( resource ) );
} else {
putValue( Action.NAME, Messages.getString( "ScriptableDataSourceEditor.AddQuery.Name" ) );
}
putValue( Action.SHORT_DESCRIPTION, Messages.getString( "ScriptableDataSourceEditor.AddQuery.Description" ) );
}
public void actionPerformed( final ActionEvent e ) {
// Find a unique query name
String queryName = Messages.getString( "ScriptableDataSourceEditor.Query" );
for ( int i = 1; i < 1000; ++i ) {
final String newQueryName = Messages.getString( "ScriptableDataSourceEditor.Query" ) + ' ' + i;
if ( !queries.containsKey( newQueryName ) ) {
queryName = newQueryName;
break;
}
}
final DataSetQuery newQuery = new DataSetQuery( queryName, "" );
queries.put( newQuery.getQueryName(), newQuery );
inModifyingQueryNameList = true;
updateQueryList();
queryNameList.setSelectedValue( newQuery, true );
inModifyingQueryNameList = false;
updateComponents();
}
}
private class QueryDocumentListener implements DocumentListener {
private QueryDocumentListener() {
}
public void insertUpdate( final DocumentEvent e ) {
update();
}
public void removeUpdate( final DocumentEvent e ) {
update();
}
public void changedUpdate( final DocumentEvent e ) {
update();
}
private void update() {
final DataSetQuery currentQuery = (DataSetQuery) queryNameList.getSelectedValue();
if ( currentQuery == null ) {
return;
}
currentQuery.setQuery( queryTextArea.getText() );
}
}
private class PreviewAction extends AbstractAction {
private PreviewAction() {
putValue( Action.NAME, Messages.getString( "ScriptableDataSourceEditor.Preview.Name" ) );
}
public void actionPerformed( final ActionEvent aEvt ) {
try {
final ScriptableDataFactory dataFactory = produceFactory();
DataFactoryEditorSupport.configureDataFactoryForPreview( dataFactory, designTimeContext );
final DataPreviewDialog previewDialog = new DataPreviewDialog( ScriptableDataSourceEditor.this );
final ScriptablePreviewWorker worker = new ScriptablePreviewWorker( dataFactory, queryNameTextField.getText() );
previewDialog.showData( worker );
final ReportDataFactoryException factoryException = worker.getException();
if ( factoryException != null ) {
ExceptionDialog.showExceptionDialog( ScriptableDataSourceEditor.this,
Messages.getString( "ScriptableDataSourceEditor.PreviewError.Title" ),
Messages.getString( "ScriptableDataSourceEditor.PreviewError.Message" ), factoryException );
}
} catch ( Exception e ) {
ExceptionDialog.showExceptionDialog( ScriptableDataSourceEditor.this,
Messages.getString( "ScriptableDataSourceEditor.PreviewError.Title" ),
Messages.getString( "ScriptableDataSourceEditor.PreviewError.Message" ), e );
}
}
}
private static class ScriptablePreviewWorker implements PreviewWorker {
private ScriptableDataFactory dataFactory;
private TableModel resultTableModel;
private ReportDataFactoryException exception;
private String query;
private ScriptablePreviewWorker( final ScriptableDataFactory dataFactory,
final String query ) {
if ( dataFactory == null ) {
throw new NullPointerException();
}
this.query = query;
this.dataFactory = dataFactory;
}
public ReportDataFactoryException getException() {
return exception;
}
public TableModel getResultTableModel() {
return resultTableModel;
}
public void close() {
}
/**
* Requests that the thread stop processing as soon as possible.
*/
public void cancelProcessing( final CancelEvent event ) {
dataFactory.cancelRunningQuery();
}
/**
* When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread
* causes the object's <code>run</code> method to be called in that separately executing thread.
* <p/>
* The general contract of the method <code>run</code> is that it may take any action whatsoever.
*
* @see Thread#run()
*/
public void run() {
try {
resultTableModel = dataFactory.queryData( query, new ReportParameterValues() );
} catch ( ReportDataFactoryException e ) {
exception = e;
} finally {
dataFactory.close();
}
}
}
private JList queryNameList;
private JTextField queryNameTextField;
private JList languageField;
private RSyntaxTextArea queryTextArea;
private RSyntaxTextArea initScriptTextArea;
private RSyntaxTextArea shutdownScriptTextArea;
private Map<String, DataSetQuery> queries;
private boolean inQueryNameUpdate;
private boolean inModifyingQueryNameList;
private PreviewAction previewAction;
private DesignTimeContext designTimeContext;
public ScriptableDataSourceEditor( final DesignTimeContext designTimeContext ) {
init( designTimeContext );
}
public ScriptableDataSourceEditor( final DesignTimeContext designTimeContext, final Dialog owner ) {
super( owner );
init( designTimeContext );
}
public ScriptableDataSourceEditor( final DesignTimeContext designTimeContext, final Frame owner ) {
super( owner );
init( designTimeContext );
}
private void init( final DesignTimeContext designTimeContext ) {
if ( designTimeContext == null ) {
throw new NullPointerException();
}
this.designTimeContext = designTimeContext;
setTitle( Messages.getString( "ScriptableDataSourceEditor.Title" ) );
setModal( true );
previewAction = new PreviewAction();
queryNameTextField = new JTextField( null, 0 );
queryNameTextField.setColumns( 35 );
queryNameTextField.getDocument().addDocumentListener( new QueryNameTextFieldDocumentListener() );
queryTextArea = new RSyntaxTextArea();
queryTextArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_NONE );
queryTextArea.getDocument().addDocumentListener( new QueryDocumentListener() );
initScriptTextArea = new RSyntaxTextArea();
initScriptTextArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_NONE );
shutdownScriptTextArea = new RSyntaxTextArea();
shutdownScriptTextArea.setSyntaxEditingStyle( SyntaxConstants.SYNTAX_STYLE_NONE );
languageField = new JList( new DefaultComboBoxModel( InternalBSFManager.getRegisteredLanguages() ) );
languageField.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
languageField.getSelectionModel().addListSelectionListener( new UpdateLanguageHandler() );
queryNameList = new JList();
queryNameList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
queryNameList.setVisibleRowCount( 5 );
queryNameList.addListSelectionListener( new QueryNameListSelectionListener() );
queryNameList.setCellRenderer( new QueryNameListCellRenderer() );
final QueryRemoveAction removeQueryAction = new QueryRemoveAction();
queryNameList.addListSelectionListener( removeQueryAction );
super.init();
}
protected String getDialogId() {
return "ScriptableDataSourceEditor";
}
protected Component createContentPane() {
final JPanel initScriptContentHolder = new JPanel( new BorderLayout() );
initScriptContentHolder
.add( BorderLayout.NORTH, new JLabel( Messages.getString( "ScriptableDataSourceEditor.InitScript" ) ) );
initScriptContentHolder.add( BorderLayout.CENTER, new RTextScrollPane( 500, 600, initScriptTextArea, true ) );
final JPanel shutdownScriptContentHolder = new JPanel( new BorderLayout() );
shutdownScriptContentHolder
.add( BorderLayout.NORTH, new JLabel( Messages.getString( "ScriptableDataSourceEditor.ShutdownScript" ) ) );
shutdownScriptContentHolder
.add( BorderLayout.CENTER, new RTextScrollPane( 500, 600, shutdownScriptTextArea, true ) );
final JPanel queryDetailsNamePanel = new JPanel( new BorderLayout() );
queryDetailsNamePanel
.add( new JLabel( Messages.getString( "ScriptableDataSourceEditor.QueryName" ) ), BorderLayout.NORTH );
queryDetailsNamePanel.add( queryNameTextField, BorderLayout.CENTER );
final JPanel queryContentHolder = new JPanel( new BorderLayout() );
queryContentHolder
.add( BorderLayout.NORTH, new JLabel( Messages.getString( "ScriptableDataSourceEditor.QueryLabel" ) ) );
queryContentHolder.add( BorderLayout.CENTER, new RTextScrollPane( 500, 300, queryTextArea, true ) );
// Create the query details panel
final JPanel queryDetailsPanel = new JPanel( new BorderLayout() );
queryDetailsPanel.setBorder( new EmptyBorder( 0, 8, 8, 8 ) );
queryDetailsPanel.add( BorderLayout.NORTH, queryDetailsNamePanel );
queryDetailsPanel.add( BorderLayout.CENTER, queryContentHolder );
final JPanel previewButtonPanel = new JPanel( new FlowLayout( FlowLayout.RIGHT ) );
previewButtonPanel.add( new JButton( previewAction ) );
final JPanel queryContentPanel = new JPanel( new BorderLayout() );
queryContentPanel.add( BorderLayout.NORTH, createQueryListPanel() );
queryContentPanel.add( BorderLayout.CENTER, queryDetailsPanel );
final JTabbedPane scriptsTabPane = new JTabbedPane();
scriptsTabPane.addTab( Messages.getString( "ScriptableDataSourceEditor.QueryTab" ), queryContentPanel );
scriptsTabPane.addTab( Messages.getString( "ScriptableDataSourceEditor.InitScriptTab" ), initScriptContentHolder );
scriptsTabPane
.addTab( Messages.getString( "ScriptableDataSourceEditor.ShutdownScriptTab" ), shutdownScriptContentHolder );
final JLabel languageLabel = new JLabel( Messages.getString( "ScriptableDataSourceEditor.Language" ) );
languageLabel.setBorder( new EmptyBorder( 0, 0, 3, 0 ) );
final JPanel languagesPanel = new JPanel( new BorderLayout() );
languagesPanel.setBorder( new EmptyBorder( 8, 8, 8, 0 ) );
languagesPanel.add( BorderLayout.NORTH, languageLabel );
languagesPanel.add( BorderLayout.CENTER, new JScrollPane( languageField ) );
final JPanel contentPanel = new JPanel( new BorderLayout() );
contentPanel.add( BorderLayout.WEST, languagesPanel );
contentPanel.add( BorderLayout.CENTER, scriptsTabPane );
contentPanel.add( BorderLayout.SOUTH, previewButtonPanel );
return contentPanel;
}
private JPanel createQueryListPanel() {
final QueryRemoveAction queryRemoveAction = new QueryRemoveAction();
queryNameList.addListSelectionListener( queryRemoveAction );
final JPanel theQueryButtonsPanel = new JPanel( new FlowLayout( FlowLayout.RIGHT ) );
theQueryButtonsPanel.add( new BorderlessButton( new QueryAddAction() ) );
theQueryButtonsPanel.add( new BorderlessButton( queryRemoveAction ) );
final JPanel theQueryControlsPanel = new JPanel( new BorderLayout() );
theQueryControlsPanel
.add( BorderLayout.WEST, new JLabel( Messages.getString( "ScriptableDataSourceEditor.AvailableQueries" ) ) );
theQueryControlsPanel.add( BorderLayout.EAST, theQueryButtonsPanel );
final JPanel queryListPanel = new JPanel( new BorderLayout() );
queryListPanel.setBorder( BorderFactory.createEmptyBorder( 0, 8, 0, 8 ) );
queryListPanel.add( BorderLayout.NORTH, theQueryControlsPanel );
queryListPanel.add( BorderLayout.CENTER, new JScrollPane( queryNameList ) );
return queryListPanel;
}
public ScriptableDataFactory performConfiguration( final ScriptableDataFactory dataFactory,
final String selectedQuery ) {
// Reset the confirmed / cancel flag
// Initialize the internal storage
queries = new TreeMap<String, DataSetQuery>();
// Load the current configuration
if ( dataFactory != null ) {
languageField.setSelectedValue( dataFactory.getLanguage(), true );
final String[] queryNames = dataFactory.getQueryNames();
for ( int i = 0; i < queryNames.length; i++ ) {
final String queryName = queryNames[ i ];
final String query = dataFactory.getQuery( queryName );
queries.put( queryName, new DataSetQuery( queryName, query ) );
}
initScriptTextArea.setText( dataFactory.getScript() );
shutdownScriptTextArea.setText( dataFactory.getShutdownScript() );
}
// Prepare the data and the enable the proper buttons
updateComponents();
updateQueryList();
setSelectedQuery( selectedQuery );
// Enable the dialog
if ( !performEdit() ) {
return null;
}
return produceFactory();
}
private ScriptableDataFactory produceFactory() {
final ScriptableDataFactory returnDataFactory = new ScriptableDataFactory();
returnDataFactory.setLanguage( (String) languageField.getSelectedValue() );
if ( StringUtils.isEmpty( initScriptTextArea.getText() ) ) {
returnDataFactory.setScript( null );
} else {
returnDataFactory.setScript( initScriptTextArea.getText() );
}
if ( StringUtils.isEmpty( shutdownScriptTextArea.getText() ) ) {
returnDataFactory.setShutdownScript( null );
} else {
returnDataFactory.setShutdownScript( shutdownScriptTextArea.getText() );
}
final DataSetQuery[] queries = this.queries.values().toArray( new DataSetQuery[ this.queries.size() ] );
for ( int i = 0; i < queries.length; i++ ) {
final DataSetQuery query = queries[ i ];
returnDataFactory.setQuery( query.getQueryName(), query.getQuery() );
}
return returnDataFactory;
}
protected void updateQueryList() {
queryNameList.removeAll();
queryNameList.setListData( queries.values().toArray( new DataSetQuery[ queries.size() ] ) );
}
private void setSelectedQuery( final String aQuery ) {
final ListModel theModel = queryNameList.getModel();
for ( int i = 0; i < theModel.getSize(); i++ ) {
final DataSetQuery theDataSet = (DataSetQuery) theModel.getElementAt( i );
if ( theDataSet.getQueryName().equals( aQuery ) ) {
queryNameList.setSelectedValue( theDataSet, true );
break;
}
}
}
protected void updateComponents() {
final boolean querySelected = queryNameList.getSelectedIndex() != -1;
final boolean hasQueries = queryNameList.getModel().getSize() > 0;
queryNameTextField.setEnabled( querySelected );
queryTextArea.setEnabled( querySelected );
getConfirmAction().setEnabled( hasQueries && languageField.getSelectedIndex() != -1 );
queryTextArea.setSyntaxEditingStyle( mapLanguageToSyntaxHighlighting( (String) languageField.getSelectedValue() ) );
initScriptTextArea
.setSyntaxEditingStyle( mapLanguageToSyntaxHighlighting( (String) languageField.getSelectedValue() ) );
shutdownScriptTextArea
.setSyntaxEditingStyle( mapLanguageToSyntaxHighlighting( (String) languageField.getSelectedValue() ) );
previewAction.setEnabled( querySelected );
}
private String mapLanguageToSyntaxHighlighting( final String language ) {
if ( "beanshell".equals( language ) ) {
return SyntaxConstants.SYNTAX_STYLE_JAVA;
}
if ( "groovy".equals( language ) ) {
return SyntaxConstants.SYNTAX_STYLE_GROOVY;
}
if ( "javascript".equals( language ) ) {
return SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT;
}
if ( "jython".equals( language ) ) {
return SyntaxConstants.SYNTAX_STYLE_PYTHON;
}
if ( "xslt".equals( language ) ) {
return SyntaxConstants.SYNTAX_STYLE_XML;
}
return SyntaxConstants.SYNTAX_STYLE_NONE;
}
}
| lgpl-2.1 |
sarabasiri62/Group2 | jdExtract/JD/src/util/InstanceOfIfStatement.java | 313 | package util;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
public class InstanceOfIfStatement implements StatementInstanceChecker {
public boolean instanceOf(Statement statement) {
if(statement instanceof IfStatement)
return true;
else
return false;
}
}
| lgpl-2.1 |
phoenixctms/ctsms | core/src/test/java/org/phoenixctms/ctsms/service/massmail/test/MassMailService_getMassMailTest.java | 1265 | // This file is part of the Phoenix CTMS project (www.phoenixctms.org),
// distributed under LGPL v2.1. Copyright (C) 2011 - 2017.
//
package org.phoenixctms.ctsms.service.massmail.test;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* <p>
* Test case for method <code>getMassMail</code> of service <code>MassMailService</code>.
* </p>
*
* @see org.phoenixctms.ctsms.service.massmail.MassMailService#getMassMail(org.phoenixctms.ctsms.vo.AuthenticationVO, java.lang.Long)
*/
@Test(groups={"service","MassMailService"})
public class MassMailService_getMassMailTest extends MassMailServiceBaseTest {
/**
* Test succes path for service method <code>getMassMail</code>
*
* Tests expected behaviour of service method.
*/
@Test
public void testSuccessPath() {
Assert.fail( "Test 'MassMailService_getMassMailTest.testSuccessPath()}' not implemented." );
}
/*
* Add test methods for each test case of the 'MassMailService.org.andromda.cartridges.spring.metafacades.SpringServiceOperationLogicImpl[org.phoenixctms.ctsms.service.massmail.MassMailService.getMassMail]()' service method.
*/
/**
* Test special case XYZ for service method <code></code>
*/
/*
@Test
public void testCaseXYZ() {
}
*/
} | lgpl-2.1 |
panifex/panifex-platform | panifex-module-api/src/main/java/org/panifex/module/api/tracker/SingleTracker.java | 1082 | /*******************************************************************************
* Panifex platform
* Copyright (C) 2013 Mario Krizmanic
*
* 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. 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
package org.panifex.module.api.tracker;
public interface SingleTracker<Service> extends Tracker<Service> {
Service service();
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsk/itemk80.java | 156 | package fr.toss.FF7itemsk;
public class itemk80 extends FF7itemskbase {
public itemk80(int id) {
super(id);
setUnlocalizedName("itemk80");
}
}
| lgpl-2.1 |
sudheesh001/loklak_server | src/org/loklak/api/search/GenericScraper.java | 3953 | /**
* GenericScraper
* Copyright 22.02.2015 by Damini Satya, @daminisatya
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.loklak.api.search;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import org.loklak.data.DAO;
import org.loklak.http.ClientConnection;
import org.loklak.http.RemoteAccess;
import org.loklak.server.Query;
import org.loklak.tools.CharacterCoding;
import org.loklak.tools.UTF8;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GenericScraper extends HttpServlet {
private static final long serialVersionUID = 4653635987712691127L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Query post = RemoteAccess.evaluate(request);
// manage DoS
if (post.isDoS_blackout()) {response.sendError(503, "your request frequency is too high"); return;}
// evaluate get parameters
String url = post.get("url", "");
JSONObject obj = new JSONObject();
//loading the data from the URL
Document page = Jsoup.connect(url).get();
String title = page.title();
List<String> linkHref = new ArrayList<String>();
List<String> linkText = new ArrayList<String>();
List<String> src = new ArrayList<String>();
List<String> image = new ArrayList<String>();
Elements links = page.getElementsByTag("a");
Elements links2 = page.getElementsByTag("link");
Elements srciptLinks =page.getElementsByTag("script");
Elements imageLinks =page.getElementsByTag("img");
Elements taglang = page.getElementsByTag("html");
String language = taglang.attr("lang");
for (Element link : links) {
if(link.attr("href") != null && link.attr("href").length() != 0){
linkHref.add(link.attr("href"));
}
if(link.text() != null && link.text().length() != 0){
linkText.add(link.text());
}
}
for (Element link : links2) {
if(link.attr("href") != null && link.attr("href").length() != 0){
linkHref.add(link.attr("href"));
}
}
for (Element link : srciptLinks) {
if(link.attr("src") != null && link.attr("src").length() != 0){
src.add(link.attr("src"));
}
}
for (Element link : imageLinks) {
if(link.attr("src") != null && link.attr("src").length() != 0){
image.add(link.attr("src"));
}
}
obj.put("title", title);
obj.put("language", language);
obj.put("Links", new JSONArray(linkHref));
obj.put("Text in Links", new JSONArray(linkText));
obj.put("source files", new JSONArray(src));
obj.put("Image files", new JSONArray(image));
//print JSON
response.setCharacterEncoding("UTF-8");
PrintWriter sos = response.getWriter();
sos.print(obj.toString(2));
sos.println();
}
}
| lgpl-2.1 |
JiriOndrusek/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/AbstractDeploymentUnitService.java | 8587 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.server.deployment;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.server.logging.ServerLogger;
import org.jboss.as.server.services.security.AbstractVaultReader;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StabilityMonitor;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.common.function.ExceptionConsumer;
/**
* Abstract service responsible for managing the life-cycle of a {@link DeploymentUnit}.
*
* @author John Bailey
* @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a>
*/
public abstract class AbstractDeploymentUnitService implements Service<DeploymentUnit> {
private static final String FIRST_PHASE_NAME = Phase.values()[0].name();
final ImmutableManagementResourceRegistration registration;
final ManagementResourceRegistration mutableRegistration;
final Resource resource;
final CapabilityServiceSupport capabilityServiceSupport;
final AbstractVaultReader vaultReader;
private final InjectedValue<DeployerChains> deployerChainsInjector = new InjectedValue<DeployerChains>();
private volatile DeploymentUnitPhaseBuilder phaseBuilder = null;
private volatile DeploymentUnit deploymentUnit;
private volatile StabilityMonitor monitor;
AbstractDeploymentUnitService(final ImmutableManagementResourceRegistration registration, final ManagementResourceRegistration mutableRegistration, final Resource resource, final CapabilityServiceSupport capabilityServiceSupport, final AbstractVaultReader vaultReader) {
this.mutableRegistration = mutableRegistration;
this.capabilityServiceSupport = capabilityServiceSupport;
this.registration = registration;
this.vaultReader = vaultReader;
this.resource = resource;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
ServiceTarget target = context.getChildTarget();
final String deploymentName = context.getController().getName().getSimpleName();
monitor = new StabilityMonitor();
monitor.addController(context.getController());
deploymentUnit = createAndInitializeDeploymentUnit(context.getController().getServiceContainer());
final String managementName = deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME);
if (deploymentUnit.getParent()==null) {
ServerLogger.DEPLOYMENT_LOGGER.startingDeployment(managementName, deploymentName);
} else {
ServerLogger.DEPLOYMENT_LOGGER.startingSubDeployment(deploymentName);
}
ExceptionConsumer<StartContext, StartException> installer = startContext -> {
ServiceName serviceName = this.deploymentUnit.getServiceName().append(FIRST_PHASE_NAME);
DeploymentUnitPhaseService<?> phaseService = DeploymentUnitPhaseService.create(this.deploymentUnit, Phase.values()[0]);
startContext.getChildTarget().addService(serviceName, phaseService)
.addDependency(Services.JBOSS_DEPLOYMENT_CHAINS, DeployerChains.class, phaseService.getDeployerChainsInjector())
.install();
};
// If a builder was previously attached, reattach to the new deployment unit instance and build the initial phase using that builder
if (this.phaseBuilder != null) {
this.deploymentUnit.putAttachment(Attachments.DEPLOYMENT_UNIT_PHASE_BUILDER, this.phaseBuilder);
Set<AttachmentKey<?>> initialAttachmentKeys = this.getDeploymentUnitAttachmentKeys();
Consumer<StopContext> uninstaller = stopContext -> {
// Cleanup any deployment unit attachments that were not properly removed during DUP undeploy
this.getDeploymentUnitAttachmentKeys().stream()
.filter(key -> !initialAttachmentKeys.contains(key))
.forEach(key -> this.deploymentUnit.removeAttachment(key));
};
ServiceName serviceName = this.deploymentUnit.getServiceName().append("installer");
this.phaseBuilder.build(target, serviceName, new FunctionalVoidService(installer, uninstaller)).install();
} else {
installer.accept(context);
}
}
/**
* Template method required for implementations to create and fully initialize a deployment unit instance. This method
* should be used to attach any initial deployment unit attachments required for the deployment type.
*
* @param registry The service registry
* @return An initialized DeploymentUnit instance
*/
protected abstract DeploymentUnit createAndInitializeDeploymentUnit(final ServiceRegistry registry);
@Override
public synchronized void stop(final StopContext context) {
final String deploymentName = context.getController().getName().getSimpleName();
final String managementName = deploymentUnit.getAttachment(Attachments.MANAGEMENT_NAME);
if (deploymentUnit.getParent()==null) {
ServerLogger.DEPLOYMENT_LOGGER.stoppedDeployment(managementName, deploymentName, (int) (context.getElapsedTime() / 1000000L));
} else {
ServerLogger.DEPLOYMENT_LOGGER.stoppedSubDeployment(deploymentName, (int) (context.getElapsedTime() / 1000000L));
}
// Retain any attached builder across restarts
this.phaseBuilder = this.deploymentUnit.getAttachment(Attachments.DEPLOYMENT_UNIT_PHASE_BUILDER);
//clear up all attachments
this.getDeploymentUnitAttachmentKeys().forEach(key -> deploymentUnit.removeAttachment(key));
deploymentUnit = null;
monitor.removeController(context.getController());
monitor = null;
DeploymentResourceSupport.cleanup(resource);
}
/**
* Returns a new set containing the keys of all current deployment unit attachments.
*/
private Set<AttachmentKey<?>> getDeploymentUnitAttachmentKeys() {
return ((SimpleAttachable) this.deploymentUnit).attachmentKeys();
}
public synchronized DeploymentUnit getValue() throws IllegalStateException, IllegalArgumentException {
return deploymentUnit;
}
public DeploymentStatus getStatus() {
StabilityMonitor monitor = this.monitor;
if (monitor == null) {
return DeploymentStatus.STOPPED;
}
final Set<ServiceController<?>> problems = new HashSet<ServiceController<?>>();
try {
monitor.awaitStability(problems, problems);
} catch (final InterruptedException e) {
// ignore
}
return problems.isEmpty() ? DeploymentStatus.OK : DeploymentStatus.FAILED;
}
Injector<DeployerChains> getDeployerChainsInjector() {
return deployerChainsInjector;
}
public enum DeploymentStatus {
NEW,
OK,
FAILED,
STOPPED
}
}
| lgpl-2.1 |
mcarniel/oswing | src/org/openswing/swing/client/FileControl.java | 13570 | package org.openswing.swing.client;
import java.io.*;
import java.util.ArrayList;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import org.openswing.swing.util.client.ClientSettings;
import org.openswing.swing.util.client.ClientUtils;
import javax.swing.JFileChooser;
import org.openswing.swing.form.client.Form;
/**
* <p>Title: OpenSwing Framework</p>
* <p>Description: Input control used for file upload: it allows to select a file from local file system,
* read it and store it as byte[] within the control.
* Moreover, it allows to download file starting from byte[] stored within the control.
* Optionally, another attribute can be binded to this control, in order to store the file name.
* </p>
* <p>Copyright: Copyright (C) 2006 Mauro Carniel</p>
*
* <p> This file is part of OpenSwing Framework.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the (LGPL) Lesser General Public
* License as published by the Free Software Foundation;
*
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 2.1, February 1999
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* The author may be contacted at:
* maurocarniel@tin.it</p>
*
* @author Mauro Carniel
* @version 1.0
*/
public class FileControl extends BaseInputControl implements InputControl {
/** flag used to define if a file import button must be showed; default value: <code>true</code> */
private boolean showUploadButton = true;
/** flag used to define if a file export button must be showed; default value: <code>true</code> */
private boolean showDownloadButton = true;
/** optional attribute name used to bind this attribute to the file name */
private String fileNameAttributeName = null;
/** file filter used to filter image file selection from select button; default value: jpg and gif files only */
private javax.swing.filechooser.FileFilter fileFilter = new javax.swing.filechooser.FileFilter() {
/**
* Whether the given file is accepted by this filter.
*/
public boolean accept(File f) {
return
f.isFile() ||
f.isDirectory();
}
/**
* The description of this filter.
* @see FileView#getName
*/
public String getDescription() {
return "All file formats (*.*)";
}
};
/** text field used to show file name */
private JTextField fileName = new JTextField();
/** button used to upadload file */
private JButton uploadButton = new JButton() {
public void paint(Graphics g) {
super.paint(g);
int width = g.getFontMetrics().stringWidth("...");
if (isEnabled())
g.setColor(UIManager.getColor("Button.foreground"));
else
g.setColor(UIManager.getColor("Button.disabledForeground"));
g.drawString("...", (this.getWidth()-width+1)/2, this.getHeight()/2+4);
}
};
/** button used to download file */
private JButton downloadButton = new JButton() {
public void paint(Graphics g) {
super.paint(g);
int width = g.getFontMetrics().stringWidth("...");
if (isEnabled())
g.setColor(UIManager.getColor("Button.foreground"));
else
g.setColor(UIManager.getColor("Button.disabledForeground"));
g.drawString("...", (this.getWidth()-width+1)/2, this.getHeight()/2+4);
}
};
/** bytes related to file */
private byte[] bytes;
/** used in focus management */
private String oldFileName = null;
public FileControl() {
uploadButton.setPreferredSize(new Dimension(21, fileName.getPreferredSize().height));
downloadButton.setPreferredSize(new Dimension(21, fileName.getPreferredSize().height));
this.setLayout(new GridBagLayout());
fileName.setColumns(10);
this.add(fileName, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
uploadButton.setToolTipText(ClientSettings.getInstance().getResources().getResource("upload file"));
downloadButton.setToolTipText(ClientSettings.getInstance().getResources().getResource("download file"));
this.add(uploadButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
this.add(downloadButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
downloadButton.setEnabled(false);
fileName.addFocusListener(new FocusAdapter() {
/**
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(FocusEvent e) {
oldFileName = fileName.getText();
}
/**
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(FocusEvent e) {
if (fileName.getText()==null || fileName.getText().trim().equals("")) {
bytes = null;
oldFileName = null;
downloadButton.setEnabled(false);
}
else if (!fileName.getText().equals(oldFileName)) {
readFile(fileName.getText());
}
}
});
uploadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser f = new JFileChooser();
f.setDialogTitle(ClientSettings.getInstance().getResources().getResource("upload file"));
f.setDialogType(f.OPEN_DIALOG);
f.setApproveButtonText(ClientSettings.getInstance().getResources().getResource("upload file"));
f.setFileSelectionMode(f.FILES_ONLY);
if (fileFilter!=null)
f.setFileFilter(fileFilter);
int res = f.showOpenDialog(ClientUtils.getParentWindow(FileControl.this));
if (res==f.APPROVE_OPTION) {
readFile(f.getSelectedFile().getAbsolutePath());
}
}
});
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (bytes==null)
return;
final JFileChooser f = new JFileChooser();
f.setDialogTitle(ClientSettings.getInstance().getResources().getResource("download file"));
f.setDialogType(f.SAVE_DIALOG);
f.setApproveButtonText(ClientSettings.getInstance().getResources().getResource("download file"));
Form form = ClientUtils.getLinkedForm(FileControl.this);
if (form != null &&
fileNameAttributeName!=null &&
!fileNameAttributeName.equals("")) {
Object name = form.getVOModel().getValue(fileNameAttributeName);
if (name!=null)
f.setSelectedFile(new File(name.toString()));
}
int res = f.showSaveDialog(ClientUtils.getParentWindow(FileControl.this));
if (res==f.APPROVE_OPTION) {
try {
File file = f.getSelectedFile();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(bytes);
out.close();
}
catch (Throwable ex) {
OptionPane.showMessageDialog(ClientUtils.getParentWindow(FileControl.this),ex.getMessage(),ClientSettings.getInstance().getResources().getResource("Error while saving"),JOptionPane.ERROR_MESSAGE);
}
}
}
});
initListeners();
}
private void readFile(String file) {
try {
File f = new File(file);
Form form = ClientUtils.getLinkedForm(this);
if (form != null &&
fileNameAttributeName!=null &&
!fileNameAttributeName.equals("")) {
form.getVOModel().setValue(fileNameAttributeName,f.getName());
fileName.setText(f.getName());
}
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
bytes = new byte[(int)f.length()];
in.read(bytes);
in.close();
// form.getVOModel().setValue(attributeName,bytes);
downloadButton.setEnabled(true);
}
catch (Exception ex) {
OptionPane.showMessageDialog(ClientUtils.getParentWindow(FileControl.this),"Error",ex.getMessage(),JOptionPane.ERROR_MESSAGE);
bytes = null;
}
}
/**
* @return define if a file import button must be showed
*/
public final boolean isShowUploadButton() {
return showUploadButton;
}
/**
* Define if a file import button must be showed.
* @param showUploadButton define if a file import button must be showed, in order to select and upload a file
*/
public final void setShowUploadButton(boolean showUploadButton) {
if (showUploadButton && !this.showUploadButton) {
this.add(uploadButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
this.revalidate();
}
else if (!showUploadButton && this.showUploadButton) {
this.remove(uploadButton);
this.revalidate();
}
this.showUploadButton = showUploadButton;
}
/**
* @return define if a file export button must be showed
*/
public final boolean isShowDownloadButton() {
return showDownloadButton;
}
/**
* Define if a file import button must be showed.
* @param showDownloadButton define if a file export button must be showed, in order to download the file stored in the cell
*/
public final void setShowDownloadButton(boolean showDownloadButton) {
if (showDownloadButton && !this.showDownloadButton) {
this.add(downloadButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
this.revalidate();
}
else if (!showDownloadButton && this.showDownloadButton) {
this.remove(downloadButton);
this.revalidate();
}
this.showDownloadButton = showDownloadButton;
}
/**
* @return file filter used to filter file selection from import button
*/
public final javax.swing.filechooser.FileFilter getFileFilter() {
return fileFilter;
}
/**
* @return attribute name used to bind this attribute to the file name
*/
public final String getFileNameAttributeName() {
return fileNameAttributeName;
}
/**
* Set the attribute name used to bind this attribute to the file name.
* @param fileNameAttributeName attribute name used to bind this attribute to the file name
*/
public final void setFileNameAttributeName(String fileNameAttributeName) {
this.fileNameAttributeName = fileNameAttributeName;
}
/**
* Set the file filter used to filter file selection from import button.
* Default value: *.*
* @param fileFilter file filter used to filter file selection from import button
*/
public final void setFileFilter(javax.swing.filechooser.FileFilter fileFilter) {
this.fileFilter = fileFilter;
}
/**
* @return file name
*/
public final String getFileName() {
return fileName.getText();
}
/**
* @return file content
*/
public final byte[] getFile() {
return bytes;
}
/**
* Set file content.
*/
public final void setFile(byte[] bytes) {
this.bytes = bytes;
}
/**
* Replace enabled setting with editable setting (this allow tab swithing).
* @param enabled flag used to set abilitation of control
*/
public final void setEnabled(boolean enabled) {
try {
if (!enabled) {
fileName.setForeground(UIManager.getColor("TextField.foreground"));
fileName.setBackground(UIManager.getColor("TextField.inactiveBackground"));
}
}
catch (Exception ex) {
}
fileName.setEditable(enabled);
uploadButton.setEnabled(enabled);
fileName.setFocusable(enabled || ClientSettings.DISABLED_INPUT_CONTROLS_FOCUSABLE);
}
/**
* @return current input control abilitation
*/
public final boolean isEnabled() {
try {
return fileName.isEditable();
}
catch (Exception ex) {
return false;
}
}
/**
* @return value related to the input control
*/
public final Object getValue() {
return bytes;
}
/**
* Set value to the input control.
* @param value value to set into the input control
*/
public final void setValue(Object value) {
bytes = (byte[])value;
downloadButton.setEnabled(bytes!=null && bytes.length>0);
Form form = ClientUtils.getLinkedForm(this);
if (form != null &&
fileNameAttributeName!=null &&
!fileNameAttributeName.equals("")) {
fileName.setText( (String)form.getVOModel().getValue(fileNameAttributeName) );
}
}
/**
* @return component inside this whose contains the value
*/
public final JComponent getBindingComponent() {
return fileName;
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/manytoonewithformula/Message.java | 1710 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.annotations.manytoonewithformula;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.JoinColumnOrFormula;
import org.hibernate.annotations.JoinColumnsOrFormulas;
import org.hibernate.annotations.JoinFormula;
/**
* @author Sharath Reddy
*/
@Entity
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String languageCode;
private String languageName;
private Language language;
@Id @GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="lang_code")
public String getLanguageCode() {
return languageCode;
}
public void setLanguageCode(String val) {
this.languageCode = val;
}
@Column(name="lang_name")
public String getLanguageName() {
return languageName;
}
public void setLanguageName(String val) {
this.languageName = val;
}
@ManyToOne
@JoinColumnsOrFormulas(
{
@JoinColumnOrFormula(formula=@JoinFormula(value="UPPER(lang_code)"))
//@JoinColumnOrFormula(formula=@JoinFormula(value="(select l.code from Language l where l.name = lang_name)"))
})
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
}
| lgpl-2.1 |
languagetool-org/languagetool | languagetool-office-extension/src/main/java/org/languagetool/openoffice/LtDictionary.java | 8136 | /* LanguageTool, a natural language style checker
* Copyright (C) 2011 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.openoffice;
import java.util.ArrayList;
import java.util.List;
import org.languagetool.JLanguageTool;
import com.sun.star.lang.Locale;
import com.sun.star.linguistic2.DictionaryType;
import com.sun.star.linguistic2.XDictionary;
import com.sun.star.linguistic2.XDictionaryEntry;
import com.sun.star.linguistic2.XSearchableDictionaryList;
import com.sun.star.uno.XComponentContext;
/**
* Class to add manual LT dictionaries temporarily to LibreOffice/OpenOffice
* @since 5.0
* @author Fred Kruse
*/
public class LtDictionary {
private static boolean debugMode; // should be false except for testing
private List<String> dictionaryList = new ArrayList<>();
private XDictionary listIgnoredWords = null;
public LtDictionary() {
debugMode = OfficeTools.DEBUG_MODE_LD;
}
/**
* Add a non permanent dictionary to LO/OO that contains additional words defined in LT
*/
public boolean setLtDictionary(XComponentContext xContext, Locale locale, LinguisticServices linguServices) {
XSearchableDictionaryList searchableDictionaryList = OfficeTools.getSearchableDictionaryList(xContext);
if (searchableDictionaryList == null) {
MessageHandler.printToLogFile("LtDictionary: setLtDictionary: searchableDictionaryList == null");
return false;
}
if (listIgnoredWords == null) {
XDictionary[] dictionaryList = searchableDictionaryList.getDictionaries();
listIgnoredWords = dictionaryList[dictionaryList.length - 1];
}
String shortCode = locale.Language;
String dictionaryName = "__LT_" + shortCode + "_internal.dic";
if (!dictionaryList.contains(dictionaryName)) {
dictionaryList.add(dictionaryName);
XDictionary manualDictionary = searchableDictionaryList.createDictionary(dictionaryName, locale, DictionaryType.POSITIVE, "");
for (String word : getManualWordList(locale, linguServices)) {
manualDictionary.add(word, false, "");
}
manualDictionary.setActive(true);
searchableDictionaryList.addDictionary(manualDictionary);
MessageHandler.printToLogFile("Internal LT dicitionary for language " + shortCode + " added: Number of words = " + manualDictionary.getCount());
if (debugMode) {
for (XDictionaryEntry entry : manualDictionary.getEntries()) {
MessageHandler.printToLogFile(entry.getDictionaryWord());
}
}
return true;
}
return false;
}
/**
* get the list of words out of spelling.txt files defined by LT
*/
private List<String> getManualWordList(Locale locale, LinguisticServices linguServices) {
List<String> words = new ArrayList<>();
String shortLangCode = locale.Language;
String path;
for (int i = 0; i < 4; i++) {
if (i == 0) {
path = "/" + shortLangCode + "/spelling.txt";
} else if (i == 1) {
path = "/" + shortLangCode + "/hunspell/spelling.txt";
} else if (i == 2) {
path = "/" + shortLangCode + "/hunspell/spelling-" + shortLangCode + "-" + locale.Country + ".txt";
} else {
path = "/" + shortLangCode + "/hunspell/spelling-" + shortLangCode + "_" + locale.Country + ".txt";
}
if (JLanguageTool.getDataBroker().resourceExists(path)) {
List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path);
if (lines != null) {
for (String line : lines) {
if (!line.isEmpty() && !line.startsWith("#")) {
String[] lineWords = line.trim().split("\\h");
lineWords = lineWords[0].trim().split("/");
lineWords[0] = lineWords[0].replaceAll("_","");
if (!lineWords[0].isEmpty() && !words.contains(lineWords[0]) && !linguServices.isCorrectSpell(lineWords[0], locale)) {
words.add(lineWords[0]);
}
}
}
}
}
}
return words;
}
/**
* Remove the non permanent LT dictionaries
*/
public boolean removeLtDictionaries(XComponentContext xContext) {
if (!dictionaryList.isEmpty()) {
XSearchableDictionaryList searchableDictionaryList = OfficeTools.getSearchableDictionaryList(xContext);
if (searchableDictionaryList == null) {
MessageHandler.printToLogFile("LtDictionary: removeLtDictionaries: searchableDictionaryList == null");
return false;
}
for (String dictionaryName : dictionaryList) {
XDictionary manualDictionary = searchableDictionaryList.getDictionaryByName(dictionaryName);
if (manualDictionary != null) {
searchableDictionaryList.removeDictionary(manualDictionary);
}
}
dictionaryList.clear();
return true;
}
return false;
}
/**
* Add a word to the List of ignored words
* Used for ignore all in spelling check
*/
public void addIgnoredWord(String word) {
listIgnoredWords.add(word, false, "");
}
/**
* Remove a word from the List of ignored words
* Used for ignore all in spelling check
*/
public void removeIgnoredWord(String word) {
listIgnoredWords.remove(word);
}
/**
* Add a word to a user dictionary
*/
public void addWordToDictionary(String dictionaryName, String word, XComponentContext xContext) {
XSearchableDictionaryList searchableDictionaryList = OfficeTools.getSearchableDictionaryList(xContext);
if (searchableDictionaryList == null) {
MessageHandler.printToLogFile("LtDictionary: addWordToDictionary: searchableDictionaryList == null");
return;
}
XDictionary dictionary = searchableDictionaryList.getDictionaryByName(dictionaryName);
dictionary.add(word, false, "");
}
/**
* Add a word to a user dictionary
*/
public void removeWordFromDictionary(String dictionaryName, String word, XComponentContext xContext) {
XSearchableDictionaryList searchableDictionaryList = OfficeTools.getSearchableDictionaryList(xContext);
if (searchableDictionaryList == null) {
MessageHandler.printToLogFile("LtDictionary: removeWordFromDictionary: searchableDictionaryList == null");
return;
}
XDictionary dictionary = searchableDictionaryList.getDictionaryByName(dictionaryName);
dictionary.remove(word);
}
/**
* Get all user dictionaries
*/
public String[] getUserDictionaries(XComponentContext xContext) {
XSearchableDictionaryList searchableDictionaryList = OfficeTools.getSearchableDictionaryList(xContext);
if (searchableDictionaryList == null) {
MessageHandler.printToLogFile("LtDictionary: getUserDictionaries: searchableDictionaryList == null");
return null;
}
XDictionary[] dictionaryList = searchableDictionaryList.getDictionaries();
if (listIgnoredWords == null) {
listIgnoredWords = dictionaryList[dictionaryList.length - 1];
}
List<String> userDictionaries = new ArrayList<String>();
for (XDictionary dictionary : dictionaryList) {
if (dictionary.isActive()) {
String name = dictionary.getName();
if (!name.startsWith("__LT_") && !name.equals(listIgnoredWords.getName())) {
userDictionaries.add(new String(name));
}
}
}
return userDictionaries.toArray(new String[userDictionaries.size()]);
}
}
| lgpl-2.1 |
windauer/exist | exist-core/src/test/java/org/exist/xquery/IntersectTest.java | 7426 | package org.exist.xquery;
import org.exist.dom.QName;
import org.exist.dom.memtree.MemTreeBuilder;
import org.exist.dom.persistent.DocumentImpl;
import org.exist.dom.persistent.NodeProxy;
import org.exist.numbering.DLN;
import org.exist.numbering.NodeId;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import org.exist.xquery.value.ValueSequence;
import org.junit.Test;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
/**
*
* @author <a href="mailto:adam.retter@googlemail.com">Adam Retter</a>
*/
public class IntersectTest {
/**
* Tests the XQuery `intersect` operator against an
* in-memory node on both the left and right sides
*/
@Test
public void memtree_intersect_memtree() throws XPathException, NoSuchMethodException {
final XQueryContext mockContext = createMock(XQueryContext.class);
final PathExpr mockLeft = createMock(PathExpr.class);
final PathExpr mockRight = createMock(PathExpr.class);
final Sequence mockContextSequence = createMock(Sequence.class);
final Item mockContextItem = createMock(Item.class);
final Profiler mockProfiler = createMock(Profiler.class);
expect(mockContext.nextExpressionId()).andReturn(1);
expect(mockContext.getProfiler()).andReturn(mockProfiler);
final org.exist.dom.memtree.ElementImpl memElement = (org.exist.dom.memtree.ElementImpl)createInMemoryDocument().getDocumentElement();
expect(mockLeft.eval(mockContextSequence, mockContextItem)).andReturn(memElement); //memtree node
expect(mockRight.eval(mockContextSequence, mockContextItem)).andReturn(memElement); //same memtree node
expect(mockContext.getProfiler()).andReturn(mockProfiler);
replay(mockRight, mockLeft, mockContext);
//test
final Intersect intersect = new Intersect(mockContext, mockLeft, mockRight);
final Sequence result = intersect.eval(mockContextSequence, mockContextItem);
assertEquals(1, ((ValueSequence)result).size());
verify(mockRight, mockLeft, mockContext);
}
/**
* Tests the XQuery `intersect` operator against an
* in-memory node on the left and a persistent node on the right
*/
@Test
public void memtree_intersect_persistent() throws XPathException, NoSuchMethodException {
final XQueryContext mockContext = createMock(XQueryContext.class);
final PathExpr mockLeft = createMock(PathExpr.class);
final PathExpr mockRight = createMock(PathExpr.class);
final Sequence mockContextSequence = createMock(Sequence.class);
final Item mockContextItem = createMock(Item.class);
final Profiler mockProfiler = createMock(Profiler.class);
final DocumentImpl mockPersistentDoc = createMock(DocumentImpl.class);
final NodeProxy mockPersistentNode = createMockBuilder(NodeProxy.class)
.withConstructor(DocumentImpl.class, NodeId.class)
.withArgs(mockPersistentDoc, new DLN(1))
.addMockedMethods(
NodeProxy.class.getMethod("isEmpty", new Class[]{}),
NodeProxy.class.getMethod("getItemType", new Class[]{}),
NodeProxy.class.getMethod("equals", new Class[]{Object.class})
).createMock();
expect(mockContext.nextExpressionId()).andReturn(1);
expect(mockContext.getProfiler()).andReturn(mockProfiler);
expect(mockLeft.eval(mockContextSequence, mockContextItem)).andReturn((org.exist.dom.memtree.ElementImpl)createInMemoryDocument().getDocumentElement()); //memtree node
expect(mockRight.eval(mockContextSequence, mockContextItem)).andReturn(mockPersistentNode); //persistent node
expect(mockPersistentNode.isEmpty()).andReturn(false);
expect(mockPersistentNode.getItemType()).andReturn(Type.NODE);
expect(mockContext.getProfiler()).andReturn(mockProfiler);
replay(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
//test
final Intersect intersect = new Intersect(mockContext, mockLeft, mockRight);
final Sequence result = intersect.eval(mockContextSequence, mockContextItem);
assertEquals(0, ((ValueSequence)result).size());
verify(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
}
/**
* Tests the XQuery `intersect` operator against a
* persistent node on the left and an in-memory node on the right
*/
@Test
public void persistent_intersect_memtree() throws XPathException, NoSuchMethodException {
final XQueryContext mockContext = createMock(XQueryContext.class);
final PathExpr mockLeft = createMock(PathExpr.class);
final PathExpr mockRight = createMock(PathExpr.class);
final Sequence mockContextSequence = createMock(Sequence.class);
final Item mockContextItem = createMock(Item.class);
final Profiler mockProfiler = createMock(Profiler.class);
final DocumentImpl mockPersistentDoc = createMock(DocumentImpl.class);
final NodeProxy mockPersistentNode = createMockBuilder(NodeProxy.class)
.withConstructor(DocumentImpl.class, NodeId.class)
.withArgs(mockPersistentDoc, new DLN(1))
.addMockedMethods(
NodeProxy.class.getMethod("isEmpty", new Class[]{}),
NodeProxy.class.getMethod("getItemType", new Class[]{}),
NodeProxy.class.getMethod("equals", new Class[]{Object.class})
).createMock();
expect(mockContext.nextExpressionId()).andReturn(1);
expect(mockContext.getProfiler()).andReturn(mockProfiler);
expect(mockLeft.eval(mockContextSequence, mockContextItem)).andReturn(mockPersistentNode); //persistent node
expect(mockRight.eval(mockContextSequence, mockContextItem)).andReturn((org.exist.dom.memtree.ElementImpl)createInMemoryDocument().getDocumentElement()); //memtree node
expect(mockPersistentNode.isEmpty()).andReturn(false);
expect(mockPersistentNode.getItemType()).andReturn(Type.NODE);
expect(mockPersistentDoc.getDocId()).andReturn(1).times(2);
expect(mockContext.getProfiler()).andReturn(mockProfiler);
replay(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
//test
final Intersect intersect = new Intersect(mockContext, mockLeft, mockRight);
final Sequence result = intersect.eval(mockContextSequence, mockContextItem);
assertEquals(0, ((ValueSequence)result).size());
verify(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
}
private Document createInMemoryDocument() {
final MemTreeBuilder memtree = new MemTreeBuilder();
memtree.startDocument();
memtree.startElement(new QName("m1", XMLConstants.NULL_NS_URI), null);
memtree.startElement(new QName("m2", XMLConstants.NULL_NS_URI), null);
memtree.characters("test data");
memtree.endElement();
memtree.endElement();
memtree.endDocument();
return memtree.getDocument();
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libformula/src/main/java/org/pentaho/reporting/libraries/formula/function/text/UpperFunction.java | 2517 | /*
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2006 - 2017 Hitachi Vantara and Contributors. All rights reserved.
*/
package org.pentaho.reporting.libraries.formula.function.text;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
import org.pentaho.reporting.libraries.formula.function.Function;
import org.pentaho.reporting.libraries.formula.function.ParameterCallback;
import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
import org.pentaho.reporting.libraries.formula.typing.Type;
import org.pentaho.reporting.libraries.formula.typing.coretypes.TextType;
/**
* This function returns the given text in upper case.
*
* @author Cedric Pronzato
*/
public class UpperFunction implements Function {
private static final long serialVersionUID = 2415465663289752026L;
public UpperFunction() {
}
public TypeValuePair evaluate( final FormulaContext context, final ParameterCallback parameters )
throws EvaluationException {
final int parameterCount = parameters.getParameterCount();
if ( parameterCount != 1 ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_ARGUMENTS_VALUE );
}
final Type type1 = parameters.getType( 0 );
final Object value1 = parameters.getValue( 0 );
final String result = context.getTypeRegistry().convertToText( type1, value1 );
if ( result == null ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE );
}
return new TypeValuePair( TextType.TYPE, result.toUpperCase( context.getLocalizationContext().getLocale() ) );
}
public String getCanonicalName() {
return "UPPER";
}
}
| lgpl-2.1 |
cytoscape/cytoscape-impl | webservice-impl/src/main/java/org/cytoscape/webservice/internal/ui/WebServiceContextMenu.java | 965 | package org.cytoscape.webservice.internal.ui;
/*
* #%L
* Cytoscape Webservice Impl (webservice-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2021 The Cytoscape Consortium
* %%
* 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%
*/
public interface WebServiceContextMenu {
String getCategory();
}
| lgpl-2.1 |
geotools/geotools | modules/library/coverage/src/test/java/org/geotools/image/DisposeStopperTest.java | 3003 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2014, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.image;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import com.sun.media.jai.operator.ImageReadDescriptor;
import it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader;
import it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import org.geotools.TestData;
import org.geotools.coverage.processing.MosaicTest;
import org.geotools.image.util.ImageUtilities;
import org.junit.Test;
public class DisposeStopperTest {
@Test
public void testDispose() throws FileNotFoundException, IOException {
final File tiff = TestData.file(MosaicTest.class, "sample0.tif");
boolean readSuccess = true;
final TIFFImageReader reader =
(it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader)
new TIFFImageReaderSpi().createReaderInstance();
try (ImageInputStream stream = ImageIO.createImageInputStream(tiff)) {
reader.setInput(stream);
RenderedImage image =
ImageReadDescriptor.create(
stream, 0, false, false, false, null, null, null, reader, null);
DisposeStopper stopper = new DisposeStopper(image);
// Try to dispose. It shouldn't since we are using the wrapper.
ImageUtilities.disposeImage(stopper);
assertNotNull(image);
// I still can get data since using the stopper the image isn't disposed
assertEquals(187, image.getData().getSample(1, 5, 0));
ImageUtilities.disposeImage(image);
image.getData().getSample(1, 5, 0);
} catch (RuntimeException ioe) {
// The dispose on the image (without using the disposeStopper wrapper)
// should have successfully disposed so the read can't success
readSuccess = false;
} finally {
if (reader != null) {
try {
reader.dispose();
} catch (Throwable t) {
}
}
}
assertFalse(readSuccess);
}
}
| lgpl-2.1 |
DorgenJones/spatialindex-master | src/spatialindex/rtree/RTree.java | 27751 | // Spatial Index Library
//
// Copyright (C) 2002 Navel Ltd.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License aint with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Contact information:
// Mailing address:
// Marios Hadjieleftheriou
// University of California, Riverside
// Department of Computer Science
// Surge Building, Room 310
// Riverside, CA 92521
//
// Email:
// marioh@cs.ucr.edu
package spatialindex.rtree;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Stack;
import spatialindex.spatialindex.IData;
import spatialindex.spatialindex.IEntry;
import spatialindex.spatialindex.INearestNeighborComparator;
import spatialindex.spatialindex.INode;
import spatialindex.spatialindex.INodeCommand;
import spatialindex.spatialindex.IQueryStrategy;
import spatialindex.spatialindex.IShape;
import spatialindex.spatialindex.ISpatialIndex;
import spatialindex.spatialindex.IStatistics;
import spatialindex.spatialindex.IVisitor;
import spatialindex.spatialindex.Point;
import spatialindex.spatialindex.RWLock;
import spatialindex.spatialindex.Region;
import spatialindex.spatialindex.SpatialIndex;
import spatialindex.storagemanager.IStorageManager;
import spatialindex.storagemanager.InvalidPageException;
import spatialindex.storagemanager.PropertySet;
public class RTree implements ISpatialIndex
{
RWLock m_rwLock;
IStorageManager m_pStorageManager;
int m_rootID;
int m_headerID;
int m_treeVariant;
double m_fillFactor;
int m_indexCapacity;
int m_leafCapacity;
int m_nearMinimumOverlapFactor;
// The R*-Tree 'p' constant, for calculating nearly minimum overlap cost.
// [Beckmann, Kriegel, Schneider, Seeger 'The R*-tree: An efficient and Robust Access Method
// for Points and Rectangles, Section 4.1]
double m_splitDistributionFactor;
// The R*-Tree 'm' constant, for calculating spliting distributions.
// [Beckmann, Kriegel, Schneider, Seeger 'The R*-tree: An efficient and Robust Access Method
// for Points and Rectangles, Section 4.2]
double m_reinsertFactor;
// The R*-Tree 'p' constant, for removing entries at reinserts.
// [Beckmann, Kriegel, Schneider, Seeger 'The R*-tree: An efficient and Robust Access Method
// for Points and Rectangles, Section 4.3]
int m_dimension;
Region m_infiniteRegion;
Statistics m_stats;
ArrayList m_writeNodeCommands = new ArrayList();
ArrayList m_readNodeCommands = new ArrayList();
ArrayList m_deleteNodeCommands = new ArrayList();
public RTree(PropertySet ps, IStorageManager sm)
{
m_rwLock = new RWLock();
m_pStorageManager = sm;
m_rootID = IStorageManager.NewPage;
m_headerID = IStorageManager.NewPage;
m_treeVariant = SpatialIndex.RtreeVariantRstar;
m_fillFactor = 0.7f;
m_indexCapacity = 100;
m_leafCapacity = 100;
m_nearMinimumOverlapFactor = 32;
m_splitDistributionFactor = 0.4f;
m_reinsertFactor = 0.3f;
m_dimension = 2;
m_infiniteRegion = new Region();
m_stats = new Statistics();
Object var = ps.getProperty("IndexIdentifier");
if (var != null)
{
if (! (var instanceof Integer)) throw new IllegalArgumentException("Property IndexIdentifier must an Integer");
m_headerID = ((Integer) var).intValue();
try
{
initOld(ps);
}
catch (IOException e)
{
System.err.println(e);
throw new IllegalStateException("initOld failed with IOException");
}
}
else
{
try
{
initNew(ps);
}
catch (IOException e)
{
System.err.println(e);
throw new IllegalStateException("initNew failed with IOException");
}
Integer i = new Integer(m_headerID);
ps.setProperty("IndexIdentifier", i);
}
}
//
// ISpatialIndex interface
//
public void insertData(final byte[] data, final IShape shape, int id)
{
if (shape.getDimension() != m_dimension) throw new IllegalArgumentException("insertData: Shape has the wrong number of dimensions.");
m_rwLock.write_lock();
try
{
Region mbr = shape.getMBR();
byte[] buffer = null;
if (data != null && data.length > 0)
{
buffer = new byte[data.length];
System.arraycopy(data, 0, buffer, 0, data.length);
}
insertData_impl(buffer, mbr, id);
// the buffer is stored in the tree. Do not delete here.
}
finally
{
m_rwLock.write_unlock();
}
}
public boolean deleteData(final IShape shape, int id)
{
if (shape.getDimension() != m_dimension) throw new IllegalArgumentException("deleteData: Shape has the wrong number of dimensions.");
m_rwLock.write_lock();
try
{
Region mbr = shape.getMBR();
return deleteData_impl(mbr, id);
}
finally
{
m_rwLock.write_unlock();
}
}
public void containmentQuery(final IShape query, final IVisitor v)
{
if (query.getDimension() != m_dimension) throw new IllegalArgumentException("containmentQuery: Shape has the wrong number of dimensions.");
rangeQuery(SpatialIndex.ContainmentQuery, query, v);
}
public void intersectionQuery(final IShape query, final IVisitor v)
{
if (query.getDimension() != m_dimension) throw new IllegalArgumentException("intersectionQuery: Shape has the wrong number of dimensions.");
rangeQuery(SpatialIndex.IntersectionQuery, query, v);
}
public void pointLocationQuery(final IShape query, final IVisitor v)
{
if (query.getDimension() != m_dimension) throw new IllegalArgumentException("pointLocationQuery: Shape has the wrong number of dimensions.");
Region r = null;
if (query instanceof Point)
{
r = new Region((Point) query, (Point) query);
}
else if (query instanceof Region)
{
r = (Region) query;
}
else
{
throw new IllegalArgumentException("pointLocationQuery: IShape can be Point or Region only.");
}
rangeQuery(SpatialIndex.IntersectionQuery, r, v);
}
public void nearestNeighborQuery(int k, final IShape query, final IVisitor v, final INearestNeighborComparator nnc)
{
if (query.getDimension() != m_dimension) throw new IllegalArgumentException("nearestNeighborQuery: Shape has the wrong number of dimensions.");
m_rwLock.read_lock();
try
{
// I need a priority queue here. It turns out that TreeSet sorts unique keys only and since I am
// sorting according to distances, it is not assured that all distances will be unique. TreeMap
// also sorts unique keys. Thus, I am simulating a priority queue using an ArrayList and binarySearch.
ArrayList queue = new ArrayList();
Node n = readNode(m_rootID);
queue.add(new NNEntry(n, 0.0));
int count = 0;
double knearest = 0.0;
while (queue.size() != 0)
{
NNEntry first = (NNEntry) queue.remove(0);
if (first.m_pEntry instanceof Node)
{
n = (Node) first.m_pEntry;
v.visitNode((INode) n);
for (int cChild = 0; cChild < n.m_children; cChild++)
{
IEntry e;
if (n.m_level == 0)
{
e = new Data(n.m_pData[cChild], n.m_pMBR[cChild], n.m_pIdentifier[cChild]);
}
else
{
e = (IEntry) readNode(n.m_pIdentifier[cChild]);
}
NNEntry e2 = new NNEntry(e, nnc.getMinimumDistance(query, e));
// Why don't I use a TreeSet here? See comment above...
int loc = Collections.binarySearch(queue, e2, new NNEntryComparator());
if (loc >= 0) queue.add(loc, e2);
else queue.add((-loc - 1), e2);
}
}
else
{
// report all nearest neighbors with equal furthest distances.
// (neighbors can be more than k, if many happen to have the same
// furthest distance).
if (count >= k && first.m_minDist > knearest) break;
v.visitData((IData) first.m_pEntry);
m_stats.m_queryResults++;
count++;
knearest = first.m_minDist;
}
}
}
finally
{
m_rwLock.read_unlock();
}
}
public void nearestNeighborQuery(int k, final IShape query, final IVisitor v)
{
if (query.getDimension() != m_dimension) throw new IllegalArgumentException("nearestNeighborQuery: Shape has the wrong number of dimensions.");
NNComparator nnc = new NNComparator();
nearestNeighborQuery(k, query, v, nnc);
}
public void queryStrategy(final IQueryStrategy qs)
{
m_rwLock.read_lock();
int[] next = new int[] {m_rootID};
try
{
while (true)
{
Node n = readNode(next[0]);
boolean[] hasNext = new boolean[] {false};
qs.getNextEntry(n, next, hasNext);
if (hasNext[0] == false) break;
}
}
finally
{
m_rwLock.read_unlock();
}
}
public PropertySet getIndexProperties()
{
PropertySet pRet = new PropertySet();
// dimension
pRet.setProperty("Dimension", new Integer(m_dimension));
// index capacity
pRet.setProperty("IndexCapacity", new Integer(m_indexCapacity));
// leaf capacity
pRet.setProperty("LeafCapacity", new Integer(m_leafCapacity));
// R-tree variant
pRet.setProperty("TreeVariant", new Integer(m_treeVariant));
// fill factor
pRet.setProperty("FillFactor", new Double(m_fillFactor));
// near minimum overlap factor
pRet.setProperty("NearMinimumOverlapFactor", new Integer(m_nearMinimumOverlapFactor));
// split distribution factor
pRet.setProperty("SplitDistributionFactor", new Double(m_splitDistributionFactor));
// reinsert factor
pRet.setProperty("ReinsertFactor", new Double(m_reinsertFactor));
return pRet;
}
public void addWriteNodeCommand(INodeCommand nc)
{
m_writeNodeCommands.add(nc);
}
public void addReadNodeCommand(INodeCommand nc)
{
m_readNodeCommands.add(nc);
}
public void addDeleteNodeCommand(INodeCommand nc)
{
m_deleteNodeCommands.add(nc);
}
public boolean isIndexValid()
{
boolean ret = true;
Stack st = new Stack();
Node root = readNode(m_rootID);
if (root.m_level != m_stats.m_treeHeight - 1)
{
System.err.println("Invalid tree height");
return false;
}
HashMap nodesInLevel = new HashMap();
nodesInLevel.put(new Integer(root.m_level), new Integer(1));
ValidateEntry e = new ValidateEntry(root.m_nodeMBR, root);
st.push(e);
while (! st.empty())
{
e = (ValidateEntry) st.pop();
Region tmpRegion = (Region) m_infiniteRegion.clone();
for (int cDim = 0; cDim < m_dimension; cDim++)
{
tmpRegion.m_pLow[cDim] = Double.POSITIVE_INFINITY;
tmpRegion.m_pHigh[cDim] = Double.NEGATIVE_INFINITY;
for (int cChild = 0; cChild < e.m_pNode.m_children; cChild++)
{
tmpRegion.m_pLow[cDim] = Math.min(tmpRegion.m_pLow[cDim], e.m_pNode.m_pMBR[cChild].m_pLow[cDim]);
tmpRegion.m_pHigh[cDim] = Math.max(tmpRegion.m_pHigh[cDim], e.m_pNode.m_pMBR[cChild].m_pHigh[cDim]);
}
}
if (! (tmpRegion.equals(e.m_pNode.m_nodeMBR)))
{
System.err.println("Invalid parent information");
ret = false;
}
else if (! (tmpRegion.equals(e.m_parentMBR)))
{
System.err.println("Error in parent");
ret = false;
}
if (e.m_pNode.m_level != 0)
{
for (int cChild = 0; cChild < e.m_pNode.m_children; cChild++)
{
ValidateEntry tmpEntry = new ValidateEntry(e.m_pNode.m_pMBR[cChild], readNode(e.m_pNode.m_pIdentifier[cChild]));
if (! nodesInLevel.containsKey(new Integer(tmpEntry.m_pNode.m_level)))
{
nodesInLevel.put(new Integer(tmpEntry.m_pNode.m_level), new Integer(1));
}
else
{
int i = ((Integer) nodesInLevel.get(new Integer(tmpEntry.m_pNode.m_level))).intValue();
nodesInLevel.put(new Integer(tmpEntry.m_pNode.m_level), new Integer(i + 1));
}
st.push(tmpEntry);
}
}
}
int nodes = 0;
for (int cLevel = 0; cLevel < m_stats.m_treeHeight; cLevel++)
{
int i1 = ((Integer) nodesInLevel.get(new Integer(cLevel))).intValue();
int i2 = ((Integer) m_stats.m_nodesInLevel.get(cLevel)).intValue();
if (i1 != i2)
{
System.err.println("Invalid nodesInLevel information");
ret = false;
}
nodes += i2;
}
if (nodes != m_stats.m_nodes)
{
System.err.println("Invalid number of nodes information");
ret = false;
}
return ret;
}
public IStatistics getStatistics()
{
return (IStatistics) m_stats.clone();
}
public void flush() throws IllegalStateException
{
try
{
storeHeader();
m_pStorageManager.flush();
}
catch (IOException e)
{
System.err.println(e);
throw new IllegalStateException("flush failed with IOException");
}
}
//
// Internals
//
private void initNew(PropertySet ps) throws IOException
{
Object var;
// tree variant.
var = ps.getProperty("TreeVariant");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i != SpatialIndex.RtreeVariantLinear && i != SpatialIndex.RtreeVariantQuadratic && i != SpatialIndex.RtreeVariantRstar)
throw new IllegalArgumentException("Property TreeVariant not a valid variant");
m_treeVariant = i;
}
else
{
throw new IllegalArgumentException("Property TreeVariant must be an Integer");
}
}
// fill factor.
var = ps.getProperty("FillFactor");
if (var != null)
{
if (var instanceof Double)
{
double f = ((Double) var).doubleValue();
if (f <= 0.0f || f >= 1.0f)
throw new IllegalArgumentException("Property FillFactor must be in (0.0, 1.0)");
m_fillFactor = f;
}
else
{
throw new IllegalArgumentException("Property FillFactor must be a Double");
}
}
// index capacity.
var = ps.getProperty("IndexCapacity");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i < 3) throw new IllegalArgumentException("Property IndexCapacity must be >= 3");
m_indexCapacity = i;
}
else
{
throw new IllegalArgumentException("Property IndexCapacity must be an Integer");
}
}
// leaf capacity.
var = ps.getProperty("LeafCapacity");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i < 3) throw new IllegalArgumentException("Property LeafCapacity must be >= 3");
m_leafCapacity = i;
}
else
{
throw new IllegalArgumentException("Property LeafCapacity must be an Integer");
}
}
// near minimum overlap factor.
var = ps.getProperty("NearMinimumOverlapFactor");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i < 1 || i > m_indexCapacity || i > m_leafCapacity)
throw new IllegalArgumentException("Property NearMinimumOverlapFactor must be less than both index and leaf capacities");
m_nearMinimumOverlapFactor = i;
}
else
{
throw new IllegalArgumentException("Property NearMinimumOverlapFactor must be an Integer");
}
}
// split distribution factor.
var = ps.getProperty("SplitDistributionFactor");
if (var != null)
{
if (var instanceof Double)
{
double f = ((Double) var).doubleValue();
if (f <= 0.0f || f >= 1.0f)
throw new IllegalArgumentException("Property SplitDistributionFactor must be in (0.0, 1.0)");
m_splitDistributionFactor = f;
}
else
{
throw new IllegalArgumentException("Property SplitDistriburionFactor must be a Double");
}
}
// reinsert factor.
var = ps.getProperty("ReinsertFactor");
if (var != null)
{
if (var instanceof Double)
{
double f = ((Double) var).doubleValue();
if (f <= 0.0f || f >= 1.0f)
throw new IllegalArgumentException("Property ReinsertFactor must be in (0.0, 1.0)");
m_reinsertFactor = f;
}
else
{
throw new IllegalArgumentException("Property ReinsertFactor must be a Double");
}
}
// dimension
var = ps.getProperty("Dimension");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i <= 1) throw new IllegalArgumentException("Property Dimension must be >= 1");
m_dimension = i;
}
else
{
throw new IllegalArgumentException("Property Dimension must be an Integer");
}
}
m_infiniteRegion.m_pLow = new double[m_dimension];
m_infiniteRegion.m_pHigh = new double[m_dimension];
for (int cDim = 0; cDim < m_dimension; cDim++)
{
m_infiniteRegion.m_pLow[cDim] = Double.POSITIVE_INFINITY;
m_infiniteRegion.m_pHigh[cDim] = Double.NEGATIVE_INFINITY;
}
m_stats.m_treeHeight = 1;
m_stats.m_nodesInLevel.add(new Integer(0));
Leaf root = new Leaf(this, -1);
m_rootID = writeNode(root);
storeHeader();
}
private void initOld(PropertySet ps) throws IOException
{
loadHeader();
// only some of the properties may be changed.
// the rest are just ignored.
Object var;
// tree variant.
var = ps.getProperty("TreeVariant");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i != SpatialIndex.RtreeVariantLinear && i != SpatialIndex.RtreeVariantQuadratic && i != SpatialIndex.RtreeVariantRstar)
throw new IllegalArgumentException("Property TreeVariant not a valid variant");
m_treeVariant = i;
}
else
{
throw new IllegalArgumentException("Property TreeVariant must be an Integer");
}
}
// near minimum overlap factor.
var = ps.getProperty("NearMinimumOverlapFactor");
if (var != null)
{
if (var instanceof Integer)
{
int i = ((Integer) var).intValue();
if (i < 1 || i > m_indexCapacity || i > m_leafCapacity)
throw new IllegalArgumentException("Property NearMinimumOverlapFactor must be less than both index and leaf capacities");
m_nearMinimumOverlapFactor = i;
}
else
{
throw new IllegalArgumentException("Property NearMinimumOverlapFactor must be an Integer");
}
}
// split distribution factor.
var = ps.getProperty("SplitDistributionFactor");
if (var != null)
{
if (var instanceof Double)
{
double f = ((Double) var).doubleValue();
if (f <= 0.0f || f >= 1.0f)
throw new IllegalArgumentException("Property SplitDistributionFactor must be in (0.0, 1.0)");
m_splitDistributionFactor = f;
}
else
{
throw new IllegalArgumentException("Property SplitDistriburionFactor must be a Double");
}
}
// reinsert factor.
var = ps.getProperty("ReinsertFactor");
if (var != null)
{
if (var instanceof Double)
{
double f = ((Double) var).doubleValue();
if (f <= 0.0f || f >= 1.0f)
throw new IllegalArgumentException("Property ReinsertFactor must be in (0.0, 1.0)");
m_reinsertFactor = f;
}
else
{
throw new IllegalArgumentException("Property ReinsertFactor must be a Double");
}
}
m_infiniteRegion.m_pLow = new double[m_dimension];
m_infiniteRegion.m_pHigh = new double[m_dimension];
for (int cDim = 0; cDim < m_dimension; cDim++)
{
m_infiniteRegion.m_pLow[cDim] = Double.POSITIVE_INFINITY;
m_infiniteRegion.m_pHigh[cDim] = Double.NEGATIVE_INFINITY;
}
}
private void storeHeader() throws IOException
{
ByteArrayOutputStream bs = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(bs);
ds.writeInt(m_rootID);
ds.writeInt(m_treeVariant);
ds.writeDouble(m_fillFactor);
ds.writeInt(m_indexCapacity);
ds.writeInt(m_leafCapacity);
ds.writeInt(m_nearMinimumOverlapFactor);
ds.writeDouble(m_splitDistributionFactor);
ds.writeDouble(m_reinsertFactor);
ds.writeInt(m_dimension);
ds.writeLong(m_stats.m_nodes);
ds.writeLong(m_stats.m_data);
ds.writeInt(m_stats.m_treeHeight);
for (int cLevel = 0; cLevel < m_stats.m_treeHeight; cLevel++)
{
ds.writeInt(((Integer) m_stats.m_nodesInLevel.get(cLevel)).intValue());
}
ds.flush();
m_headerID = m_pStorageManager.storeByteArray(m_headerID, bs.toByteArray());
}
private void loadHeader() throws IOException
{
byte[] data = m_pStorageManager.loadByteArray(m_headerID);
DataInputStream ds = new DataInputStream(new ByteArrayInputStream(data));
m_rootID = ds.readInt();
m_treeVariant = ds.readInt();
m_fillFactor = ds.readDouble();
m_indexCapacity = ds.readInt();
m_leafCapacity = ds.readInt();
m_nearMinimumOverlapFactor = ds.readInt();
m_splitDistributionFactor = ds.readDouble();
m_reinsertFactor = ds.readDouble();
m_dimension = ds.readInt();
m_stats.m_nodes = ds.readLong();
m_stats.m_data = ds.readLong();
m_stats.m_treeHeight = ds.readInt();
for (int cLevel = 0; cLevel < m_stats.m_treeHeight; cLevel++)
{
m_stats.m_nodesInLevel.add(new Integer(ds.readInt()));
}
}
protected void insertData_impl(byte[] pData, Region mbr, int id)
{
assert mbr.getDimension() == m_dimension;
boolean[] overflowTable;
Stack pathBuffer = new Stack();
Node root = readNode(m_rootID);
overflowTable = new boolean[root.m_level];
for (int cLevel = 0; cLevel < root.m_level; cLevel++) overflowTable[cLevel] = false;
Node l = root.chooseSubtree(mbr, 0, pathBuffer);
l.insertData(pData, mbr, id, pathBuffer, overflowTable);
m_stats.m_data++;
}
protected void insertData_impl(byte[] pData, Region mbr, int id, int level, boolean[] overflowTable)
{
assert mbr.getDimension() == m_dimension;
Stack pathBuffer = new Stack();
Node root = readNode(m_rootID);
Node n = root.chooseSubtree(mbr, level, pathBuffer);
n.insertData(pData, mbr, id, pathBuffer, overflowTable);
}
protected boolean deleteData_impl(final Region mbr, int id)
{
assert mbr.getDimension() == m_dimension;
boolean bRet = false;
Stack pathBuffer = new Stack();
Node root = readNode(m_rootID);
Leaf l = root.findLeaf(mbr, id, pathBuffer);
if (l != null)
{
l.deleteData(id, pathBuffer);
m_stats.m_data--;
bRet = true;
}
return bRet;
}
protected int writeNode(Node n) throws IllegalStateException
{
byte[] buffer = null;
try
{
buffer = n.store();
}
catch (IOException e)
{
System.err.println(e);
throw new IllegalStateException("writeNode failed with IOException");
}
int page;
if (n.m_identifier < 0) page = IStorageManager.NewPage;
else page = n.m_identifier;
try
{
page = m_pStorageManager.storeByteArray(page, buffer);
}
catch (InvalidPageException e)
{
System.err.println(e);
throw new IllegalStateException("writeNode failed with InvalidPageException");
}
if (n.m_identifier < 0)
{
n.m_identifier = page;
m_stats.m_nodes++;
int i = ((Integer) m_stats.m_nodesInLevel.get(n.m_level)).intValue();
m_stats.m_nodesInLevel.set(n.m_level, new Integer(i + 1));
}
m_stats.m_writes++;
for (int cIndex = 0; cIndex < m_writeNodeCommands.size(); cIndex++)
{
((INodeCommand) m_writeNodeCommands.get(cIndex)).execute(n);
}
return page;
}
protected Node readNode(int id)
{
byte[] buffer;
DataInputStream ds = null;
int nodeType = -1;
Node n = null;
try
{
buffer = m_pStorageManager.loadByteArray(id);
ds = new DataInputStream(new ByteArrayInputStream(buffer));
nodeType = ds.readInt();
if (nodeType == SpatialIndex.PersistentIndex) n = new Index(this, -1, 0);
else if (nodeType == SpatialIndex.PersistentLeaf) n = new Leaf(this, -1);
else throw new IllegalStateException("readNode failed reading the correct node type information");
n.m_pTree = this;
n.m_identifier = id;
n.load(buffer);
m_stats.m_reads++;
}
catch (InvalidPageException e)
{
System.err.println(e);
throw new IllegalStateException("readNode failed with InvalidPageException");
}
catch (IOException e)
{
System.err.println(e);
throw new IllegalStateException("readNode failed with IOException");
}
for (int cIndex = 0; cIndex < m_readNodeCommands.size(); cIndex++)
{
((INodeCommand) m_readNodeCommands.get(cIndex)).execute(n);
}
return n;
}
protected void deleteNode(Node n)
{
try
{
m_pStorageManager.deleteByteArray(n.m_identifier);
}
catch (InvalidPageException e)
{
System.err.println(e);
throw new IllegalStateException("deleteNode failed with InvalidPageException");
}
m_stats.m_nodes--;
int i = ((Integer) m_stats.m_nodesInLevel.get(n.m_level)).intValue();
m_stats.m_nodesInLevel.set(n.m_level, new Integer(i - 1));
for (int cIndex = 0; cIndex < m_deleteNodeCommands.size(); cIndex++)
{
((INodeCommand) m_deleteNodeCommands.get(cIndex)).execute(n);
}
}
private void rangeQuery(int type, final IShape query, final IVisitor v)
{
m_rwLock.read_lock();
try
{
Stack st = new Stack();
Node root = readNode(m_rootID);
if (root.m_children > 0 && query.intersects(root.m_nodeMBR)) st.push(root);
while (! st.empty())
{
Node n = (Node) st.pop();
if (n.m_level == 0)
{
v.visitNode((INode) n);
for (int cChild = 0; cChild < n.m_children; cChild++)
{
boolean b;
if (type == SpatialIndex.ContainmentQuery) b = query.contains(n.m_pMBR[cChild]);
else b = query.intersects(n.m_pMBR[cChild]);
if (b)
{
Data data = new Data(n.m_pData[cChild], n.m_pMBR[cChild], n.m_pIdentifier[cChild]);
v.visitData(data);
m_stats.m_queryResults++;
}
}
}
else
{
v.visitNode((INode) n);
for (int cChild = 0; cChild < n.m_children; cChild++)
{
if (query.intersects(n.m_pMBR[cChild]))
{
st.push(readNode(n.m_pIdentifier[cChild]));
}
}
}
}
}
finally
{
m_rwLock.read_unlock();
}
}
public String toString()
{
String s = "Dimension: " + m_dimension + "\n"
+ "Fill factor: " + m_fillFactor + "\n"
+ "Index capacity: " + m_indexCapacity + "\n"
+ "Leaf capacity: " + m_leafCapacity + "\n";
if (m_treeVariant == SpatialIndex.RtreeVariantRstar)
{
s += "Near minimum overlap factor: " + m_nearMinimumOverlapFactor + "\n"
+ "Reinsert factor: " + m_reinsertFactor + "\n"
+ "Split distribution factor: " + m_splitDistributionFactor + "\n";
}
s += "Utilization: " + 100 * m_stats.getNumberOfData() / (m_stats.getNumberOfNodesInLevel(0) * m_leafCapacity) + "%" + "\n"
+ m_stats;
return s;
}
class NNEntry
{
IEntry m_pEntry;
double m_minDist;
NNEntry(IEntry e, double f) { m_pEntry = e; m_minDist = f; }
}
class NNEntryComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
NNEntry n1 = (NNEntry) o1;
NNEntry n2 = (NNEntry) o2;
if (n1.m_minDist < n2.m_minDist) return -1;
if (n1.m_minDist > n2.m_minDist) return 1;
return 0;
}
}
class NNComparator implements INearestNeighborComparator
{
public double getMinimumDistance(IShape query, IEntry e)
{
IShape s = e.getShape();
return query.getMinimumDistance(s);
}
}
class ValidateEntry
{
Region m_parentMBR;
Node m_pNode;
ValidateEntry(Region r, Node pNode) { m_parentMBR = r; m_pNode = pNode; }
}
class Data implements IData
{
int m_id;
Region m_shape;
byte[] m_pData;
Data(byte[] pData, Region mbr, int id) { m_id = id; m_shape = mbr; m_pData = pData; }
public int getIdentifier() { return m_id; }
public IShape getShape() { return new Region(m_shape); }
public byte[] getData()
{
byte[] data = new byte[m_pData.length];
System.arraycopy(m_pData, 0, data, 0, m_pData.length);
return data;
}
}
}
| lgpl-2.1 |
lbtc-xxx/jboss-logmanager | src/main/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandler.java | 10419 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.logmanager.handlers;
import org.jboss.logmanager.ExtLogRecord;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.logging.ErrorManager;
/**
* A file handler which rotates the log at a preset time interval. The interval is determined by the content of the
* suffix string which is passed in to {@link #setSuffix(String)}.
*/
public class PeriodicRotatingFileHandler extends FileHandler {
private SimpleDateFormat format;
private String nextSuffix;
private Period period = Period.NEVER;
private long nextRollover = Long.MAX_VALUE;
private TimeZone timeZone = TimeZone.getDefault();
/**
* Construct a new instance with no formatter and no output file.
*/
public PeriodicRotatingFileHandler() {
}
/**
* Construct a new instance with the given output file.
*
* @param fileName the file name
*
* @throws java.io.FileNotFoundException if the file could not be found on open
*/
public PeriodicRotatingFileHandler(final String fileName) throws FileNotFoundException {
super(fileName);
}
/**
* Construct a new instance with the given output file and append setting.
*
* @param fileName the file name
* @param append {@code true} to append, {@code false} to overwrite
*
* @throws java.io.FileNotFoundException if the file could not be found on open
*/
public PeriodicRotatingFileHandler(final String fileName, final boolean append) throws FileNotFoundException {
super(fileName, append);
}
/**
* Construct a new instance with the given output file.
*
* @param file the file
* @param suffix the format suffix to use
*
* @throws java.io.FileNotFoundException if the file could not be found on open
*/
public PeriodicRotatingFileHandler(final File file, final String suffix) throws FileNotFoundException {
super(file);
setSuffix(suffix);
}
/**
* Construct a new instance with the given output file and append setting.
*
* @param file the file
* @param suffix the format suffix to use
* @param append {@code true} to append, {@code false} to overwrite
* @throws java.io.FileNotFoundException if the file could not be found on open
*/
public PeriodicRotatingFileHandler(final File file, final String suffix, final boolean append) throws FileNotFoundException {
super(file, append);
setSuffix(suffix);
}
@Override
public void setFile(final File file) throws FileNotFoundException {
synchronized (outputLock) {
super.setFile(file);
if (format != null && file != null && file.lastModified() > 0) {
calcNextRollover(file.lastModified());
}
}
}
/** {@inheritDoc} This implementation checks to see if the scheduled rollover time has yet occurred. */
protected void preWrite(final ExtLogRecord record) {
final long recordMillis = record.getMillis();
if (recordMillis >= nextRollover) {
rollOver();
calcNextRollover(recordMillis);
}
}
/**
* Set the suffix string. The string is in a format which can be understood by {@link java.text.SimpleDateFormat}.
* The period of the rotation is automatically calculated based on the suffix.
*
* @param suffix the suffix
* @throws IllegalArgumentException if the suffix is not valid
*/
public void setSuffix(String suffix) throws IllegalArgumentException {
final SimpleDateFormat format = new SimpleDateFormat(suffix);
format.setTimeZone(timeZone);
final int len = suffix.length();
Period period = Period.NEVER;
for (int i = 0; i < len; i ++) {
switch (suffix.charAt(i)) {
case 'y': period = min(period, Period.YEAR); break;
case 'M': period = min(period, Period.MONTH); break;
case 'w':
case 'W': period = min(period, Period.WEEK); break;
case 'D':
case 'd':
case 'F':
case 'E': period = min(period, Period.DAY); break;
case 'a': period = min(period, Period.HALF_DAY); break;
case 'H':
case 'k':
case 'K':
case 'h': period = min(period, Period.HOUR); break;
case 'm': period = min(period, Period.MINUTE); break;
case '\'': while (suffix.charAt(++i) != '\''); break;
case 's':
case 'S': throw new IllegalArgumentException("Rotating by second or millisecond is not supported");
}
}
synchronized (outputLock) {
this.format = format;
this.period = period;
final long now;
final File file = getFile();
if (file != null && file.lastModified() > 0) {
now = file.lastModified();
} else {
now = System.currentTimeMillis();
}
calcNextRollover(now);
}
}
/**
* Returns the suffix to be used.
*
* @return the suffix to be used
*/
protected final String getNextSuffix() {
return nextSuffix;
}
private void rollOver() {
try {
final File file = getFile();
// first, close the original file (some OSes won't let you move/rename a file that is open)
setFile(null);
// next, rotate it
file.renameTo(new File(file.getAbsolutePath() + nextSuffix));
// start new file
setFile(file);
} catch (FileNotFoundException e) {
reportError("Unable to rotate log file", e, ErrorManager.OPEN_FAILURE);
}
}
private void calcNextRollover(final long fromTime) {
if (period == Period.NEVER) {
nextRollover = Long.MAX_VALUE;
return;
}
nextSuffix = format.format(new Date(fromTime));
final Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeInMillis(fromTime);
final Period period = this.period;
// clear out less-significant fields
switch (period) {
default:
case YEAR:
calendar.set(Calendar.MONTH, 0);
case MONTH:
calendar.set(Calendar.DAY_OF_MONTH, 0);
calendar.clear(Calendar.WEEK_OF_MONTH);
case WEEK:
if (period == Period.WEEK) {
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
} else {
calendar.clear(Calendar.DAY_OF_WEEK);
}
calendar.clear(Calendar.DAY_OF_WEEK_IN_MONTH);
case DAY:
calendar.set(Calendar.HOUR_OF_DAY, 0);
case HALF_DAY:
if (period == Period.HALF_DAY) {
calendar.set(Calendar.HOUR, 0);
} else {
//We want both HOUR_OF_DAY and (HOUR + AM_PM) to be zeroed out
//This should ensure the hour is truly zeroed out
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, 0);
}
case HOUR:
calendar.set(Calendar.MINUTE, 0);
case MINUTE:
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
// increment the relevant field
switch (period) {
case YEAR:
calendar.add(Calendar.YEAR, 1);
break;
case MONTH:
calendar.add(Calendar.MONTH, 1);
break;
case WEEK:
calendar.add(Calendar.WEEK_OF_YEAR, 1);
break;
case DAY:
calendar.add(Calendar.DAY_OF_MONTH, 1);
break;
case HALF_DAY:
calendar.add(Calendar.AM_PM, 1);
break;
case HOUR:
calendar.add(Calendar.HOUR_OF_DAY, 1);
break;
case MINUTE:
calendar.add(Calendar.MINUTE, 1);
break;
}
nextRollover = calendar.getTimeInMillis();
}
/**
* Get the configured time zone for this handler.
*
* @return the configured time zone
*/
public TimeZone getTimeZone() {
return timeZone;
}
/**
* Set the configured time zone for this handler.
*
* @param timeZone the configured time zone
*/
public void setTimeZone(final TimeZone timeZone) {
if (timeZone == null) {
throw new NullPointerException("timeZone is null");
}
this.timeZone = timeZone;
}
private static <T extends Comparable<? super T>> T min(T a, T b) {
return a.compareTo(b) <= 0 ? a : b;
}
/**
* Possible period values. Keep in strictly ascending order of magnitude.
*/
public enum Period {
MINUTE,
HOUR,
HALF_DAY,
DAY,
WEEK,
MONTH,
YEAR,
NEVER,
}
}
| lgpl-2.1 |
kluver/lenskit | lenskit-core/src/main/java/org/lenskit/data/ratings/StandardRatingVectorPDAO.java | 2905 | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2016 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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 Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.data.ratings;
import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import org.lenskit.data.dao.DataAccessObject;
import org.lenskit.data.entities.CommonAttributes;
import org.lenskit.util.IdBox;
import org.lenskit.util.io.ObjectStream;
import org.lenskit.util.io.ObjectStreams;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;
import java.util.List;
/**
* Rating vector source that extracts user ratings from the database.
*/
@ThreadSafe
public class StandardRatingVectorPDAO implements RatingVectorPDAO {
private final DataAccessObject dao;
private volatile IdBox<Long2DoubleMap> cachedValue;
/**
* Construct a rating vector source.
* @param dao The data access object.
*/
@Inject
public StandardRatingVectorPDAO(DataAccessObject dao) {
this.dao = dao;
}
@Nonnull
@Override
public Long2DoubleMap userRatingVector(long user) {
IdBox<Long2DoubleMap> cached = cachedValue;
if (cached != null && cached.getId() == user) {
return cached.getValue();
}
Long2DoubleMap map;
try (ObjectStream<Rating> stream = dao.query(Rating.class)
.withAttribute(CommonAttributes.USER_ID, user)
.stream()) {
map = Ratings.userRatingVector(stream);
}
return map;
}
@Override
public ObjectStream<IdBox<Long2DoubleMap>> streamUsers() {
ObjectStream<IdBox<List<Rating>>> stream = dao.query(Rating.class)
.groupBy(CommonAttributes.USER_ID)
.stream();
return ObjectStreams.wrap(stream.map(u -> u.mapValue(Ratings::userRatingVector)),
stream);
}
}
| lgpl-2.1 |
mcarniel/oswing | srcdemo/demo37/TestVO.java | 1296 | package demo37;
import org.openswing.swing.message.receive.java.ValueObjectImpl;
import java.math.BigDecimal;
import java.sql.Date;
/**
* <p>Title: OpenSwing Framework</p>
* <p>Description: Test Value Object.</p>
* <p>Copyright: Copyright (C) 2006 Mauro Carniel</p>
* <p> </p>
* @author Mauro Carniel
* @version 1.0
*/
public class TestVO extends ValueObjectImpl {
private String itemCode;
private String description;
private java.math.BigDecimal qty;
private java.math.BigDecimal price;
private boolean hasChildren;
public TestVO() {
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public java.math.BigDecimal getQty() {
return qty;
}
public void setQty(java.math.BigDecimal qty) {
this.qty = qty;
}
public java.math.BigDecimal getPrice() {
return price;
}
public void setPrice(java.math.BigDecimal price) {
this.price = price;
}
public boolean isHasChildren() {
return hasChildren;
}
public void setHasChildren(boolean hasChildren) {
this.hasChildren = hasChildren;
}
}
| lgpl-2.1 |
drhee/toxoMine | intermine/objectstore/main/src/org/intermine/sql/precompute/BestQuery.java | 1880 | package org.intermine.sql.precompute;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.sql.query.Query;
import java.sql.SQLException;
/**
* This object is an abstract superclass for a Best Query tracker. Queries can be added to these
* objects, and they will keep track of them.
*
* @author Matthew Wakeling
* @author Andrew Varley
*/
public abstract class BestQuery
{
/**
* Allows a Query to be added to this tracker.
*
* @param q a Query to be added to the tracker
* @throws BestQueryException when adding should stop
* @throws SQLException if error occurs in the underlying database
*/
public abstract void add(Query q) throws BestQueryException, SQLException;
/**
* Allows a Query to be added to this tracker.
*
* @param q a query String to be added to the tracker
* @throws BestQueryException when adding should stop
* @throws SQLException if error occurs in the underlying database
*/
public abstract void add(String q) throws BestQueryException, SQLException;
/**
* Gets the best Query found so far
*
* @return the best Query, or null if no Queries added to this object
* @throws SQLException if error occurs in the underlying database
*/
public abstract Query getBestQuery() throws SQLException;
/**
* Gets the best query String found so far
*
* @return the best Query, or null if no Queries added to this object
* @throws SQLException if error occurs in the underlying database
*/
public abstract String getBestQueryString() throws SQLException;
}
| lgpl-2.1 |
johnscancella/spotbugs | spotbugs-ant/src/main/java/edu/umd/cs/findbugs/anttask/ComputeBugHistoryTask.java | 4496 | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2007 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.anttask;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import org.apache.tools.ant.BuildException;
/**
* Ant task to create/update a bug history database.
*
* @author David Hovemeyer
*/
public class ComputeBugHistoryTask extends AbstractFindBugsTask {
private File outputFile;
private boolean overrideRevisionNames;
private boolean noPackageMoves;
private boolean preciseMatch;
private boolean precisePriorityMatch;
private boolean quiet;
private boolean withMessages;
private final List<DataFile> dataFileList;
public ComputeBugHistoryTask() {
super("edu.umd.cs.findbugs.workflow.Update");
dataFileList = new LinkedList<DataFile>();
setFailOnError(true);
}
public void setOutput(File arg) {
this.outputFile = arg;
}
public void setOverrideRevisionNames(boolean arg) {
this.overrideRevisionNames = arg;
}
public void setNoPackageMoves(boolean arg) {
this.noPackageMoves = arg;
}
public void setPreciseMatch(boolean arg) {
this.preciseMatch = arg;
}
public void setPrecisePriorityMatch(boolean arg) {
this.precisePriorityMatch = arg;
}
public void setQuiet(boolean arg) {
this.quiet = arg;
}
public void setWithMessages(boolean arg) {
this.withMessages = arg;
}
/**
* Called to create DataFile objects in response to nested <DataFile>
* elements.
*
* @return new DataFile object specifying the location of an input data file
*/
public DataFile createDataFile() {
DataFile dataFile = new DataFile();
dataFileList.add(dataFile);
return dataFile;
}
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.anttask.AbstractFindBugsTask#checkParameters()
*/
@Override
protected void checkParameters() {
super.checkParameters();
if (outputFile == null) {
throw new BuildException("outputFile attribute must be set", getLocation());
}
}
/*
* (non-Javadoc)
*
* @see
* edu.umd.cs.findbugs.anttask.AbstractFindBugsTask#configureFindbugsEngine
* ()
*/
@Override
protected void configureFindbugsEngine() {
addArg("-output");
addArg(outputFile.getPath());
if (overrideRevisionNames) {
addArg("-overrideRevisionNames");
}
if (noPackageMoves) {
addArg("-noPackageMoves");
}
if (preciseMatch) {
addArg("-preciseMatch");
}
if (precisePriorityMatch) {
addArg("-precisePriorityMatch");
}
if (quiet) {
addArg("-quiet");
}
if (withMessages) {
addArg("-withMessages");
}
for (DataFile dataFile : dataFileList) {
addArg(dataFile.getName());
}
}
/*
* (non-Javadoc)
*
* @see
* edu.umd.cs.findbugs.anttask.AbstractFindBugsTask#beforeExecuteJavaProcess
* ()
*/
@Override
protected void beforeExecuteJavaProcess() {
log("Running computeBugHistory...");
}
/*
* (non-Javadoc)
*
* @see
* edu.umd.cs.findbugs.anttask.AbstractFindBugsTask#afterExecuteJavaProcess
* (int)
*/
@Override
protected void afterExecuteJavaProcess(int rc) {
if (rc == 0) {
log("History database written to " + outputFile.getPath());
} else {
throw new BuildException("execution of " + getTaskName() + " failed");
}
}
}
| lgpl-2.1 |
herculeshssj/unirio-ppgi-goalservice | GoalService/serviceDiscovery/src/main/ch/epfl/qosdisc/codims/ListServicesOperator.java | 3451 | /*
* QoS Discovery Component
* Copyright (C) 2006 Sebastian Gerlach
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package ch.epfl.qosdisc.codims;
import org.apache.log4j.Logger;
import ch.epfl.codimsd.qeef.*;
import ch.epfl.codimsd.qeef.types.*;
import ch.epfl.codimsd.qeef.util.Constants;
import ch.epfl.codimsd.qeef.relational.*;
import ch.epfl.codimsd.qep.OpNode;
/**
* This operator outputs all the services we want to be working on.
*
* @author Sebastian Gerlach
*/
public class ListServicesOperator extends Acesso {
/**
* Output log for debug info.
*/
private static Logger log = Logger.getLogger(ListServicesOperator.class);
/**
* Constructor.
*
* @param id Operator id.
* @param opNode Operatore node.
*/
public ListServicesOperator(int id, OpNode opNode) {
// Call superconstructor.
super(id);
DataSourceManager dsManager = DataSourceManager.getDataSourceManager();
dataSource = (DataSource) dsManager.getDataSource(opNode.getOpTimeStamp());
metadata = null;
}
/**
* Operator cleanup code.
*/
public void close() throws Exception {
log.debug("Closing operator.");
super.close();
}
/**
* Operator startup code.
*
* @throws Exception
*/
public void open() throws Exception {
log.debug("Opening operator.");
super.open();
}
/* (non-Javadoc)
* @see ch.epfl.codimsd.qeef.Operator#getNext(int)
*/
public DataUnit getNext(int consumerID) throws Exception {
// Read next element from datasource.
instance = (dataSource).read();
if (instance == null)
return null;
// Copy the string over into our output tuple.
Tuple t = (Tuple) instance;
OracleType oracleObject = (OracleType) t.getData(0);
StringType stringType = new StringType((String)oracleObject.getObject());
Tuple newTuple = new Tuple();
newTuple.addData((Type)stringType);
return newTuple;
}
/* (non-Javadoc)
* @see ch.epfl.codimsd.qeef.Operator#setMetadata(ch.epfl.codimsd.qeef.Metadata[])
*/
// @Override
public void setMetadata(Metadata[] prMetadata) {
// This just seems to be required by CoDIMS?
log.debug("Setting metadata.");
metadata = new Metadata[1];
metadata[0] = new TupleMetadata();
try {
Column column = new Column("StringType",
Config.getDataType(Constants.STRING), 1, 0, false, 0);
metadata[0].addData(column);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/* (non-Javadoc)
* @see ch.epfl.codimsd.qeef.Operator#getMetadata(int)
*/
// @Override
// public Metadata getMetadata(int idConsumer) {
//
// // Return something.
// return new TupleMetadata();
// }
}
| lgpl-2.1 |
opennaru-dev/khan-session | khan-session-core/src/main/java/com/opennaru/khan/session/KhanSessionConfig.java | 8356 | /*
* Opennaru, Inc. http://www.opennaru.com/
*
* Copyright (C) 2014 Opennaru, Inc. and/or its affiliates.
* All rights reserved by Opennaru, Inc.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.opennaru.khan.session;
/**
* KHAN Session Configuration
*
* @author Junshik Jeon(service@opennaru.com, nameislocus@gmail.com)
*/
public class KhanSessionConfig {
// if use library mode
@Deprecated
private boolean useLibraryMode;
// namespace
private String namespace;
// exclude regular expression
private String excludeRegExp;
// session id key
private String sessionIdKey;
// cookie domain name
private String domain;
// cookie path
private String path;
// cookie secure
private boolean secure;
// cookie is httpOnly
private boolean httpOnly;
private boolean useAuthenticator;
// if allow duplicate login
private boolean allowDuplicateLogin;
private boolean invalidateDuplicateLogin;
// 중복로그인 강제 logout url
private String logoutUrl;
// Session timout minute
private Integer sessionTimeoutMin;
// Session save delay
private Integer sessionSaveDelay;
// enable MBean statistics
private boolean enableStatistics;
// enable Memory statistics
private boolean enableMemoryStatistics;
// for spring security
private boolean enableImmediateSave;
/**
* check if library mode
* @return
*/
public boolean isUseLibraryMode() {
return useLibraryMode;
}
public void setUseLibraryMode(boolean useLibraryMode) {
this.useLibraryMode = useLibraryMode;
}
/**
* return namespace
* @return
*/
public String getNamespace() {
return namespace;
}
/**
* set namespace
* @param namespace
*/
public void setNamespace(String namespace) {
this.namespace = namespace;
}
/**
* return session id key
* @return
*/
public String getSessionIdKey() {
return sessionIdKey;
}
/**
* set session id key
* @param sessionIdKey
*/
public void setSessionIdKey(String sessionIdKey) {
this.sessionIdKey = sessionIdKey;
}
/**
* exclude url pattern
* @return
*/
public String getExcludeRegExp() {
return excludeRegExp;
}
/**
* set exclude url pattern
* @param excludeRegExp
*/
public void setExcludeRegExp(String excludeRegExp) {
this.excludeRegExp = excludeRegExp;
}
/**
* get cookie domain name
* @return
*/
public String getDomain() {
return domain;
}
/**
* set cookie domain name
* @param domain
*/
public void setDomain(String domain) {
this.domain = domain;
}
/**
* get cookie path
* @return
*/
public String getPath() {
return path;
}
/**
* set cookie path
* @param path
*/
public void setPath(String path) {
this.path = path;
}
/**
* set is secure cookie
* @param secure
*/
public void setSecure(boolean secure) {
this.secure = secure;
}
/**
* is httponly cookie
* @return
*/
public boolean isHttpOnly() {
return httpOnly;
}
/**
* set httponly cookie
* @param httpOnly
*/
public void setHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
}
public boolean useAuthenticator() {
return useAuthenticator;
}
public void setUseAuthenticator(boolean useAuthenticator) {
this.useAuthenticator = useAuthenticator;
}
/**
* is allow duplicate login
* @return
*/
public boolean isAllowDuplicateLogin() {
return allowDuplicateLogin;
}
/**
* set allow duplicate login
* @param allowDuplicateLogin
*/
public void setAllowDuplicateLogin(boolean allowDuplicateLogin) {
this.allowDuplicateLogin = allowDuplicateLogin;
}
public boolean isInvalidateDuplicateLogin() {
return invalidateDuplicateLogin;
}
public void setInvalidateDuplicateLogin(boolean invalidateDuplicateLogin) {
this.invalidateDuplicateLogin = invalidateDuplicateLogin;
}
/**
* get logout url
* @return
*/
public String getLogoutUrl() {
return logoutUrl;
}
/**
* set logout url
* @param logoutUrl
*/
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
/**
* get session timeout min
* @return
*/
public Integer getSessionTimeoutMin() {
return sessionTimeoutMin;
}
/**
* set session timeout min
* @param sessionTimeoutMin
*/
public void setSessionTimeoutMin(Integer sessionTimeoutMin) {
this.sessionTimeoutMin = sessionTimeoutMin;
}
public Integer getSessionSaveDelay() {
return sessionSaveDelay;
}
public void setSessionSaveDelay(Integer sessionSaveDelay) {
this.sessionSaveDelay = sessionSaveDelay;
}
/**
* is secure
* @return
*/
public boolean isSecure() {
return secure;
}
/**
* set secure
* @param secure
*/
public void setSecure(Boolean secure) {
this.secure = secure != null && secure;
}
/**
* enable JMX statistics
* @return
*/
public boolean isEnableStatistics() {
return enableStatistics;
}
/**
* set enable JMX statistics
* @param enableStatistics
*/
public void setEnableStatistics(boolean enableStatistics) {
this.enableStatistics = enableStatistics;
}
/**
* enable memory JMX statistics
* @return
*/
public boolean isEnableMemoryStatistics() {
return enableMemoryStatistics;
}
/**
* set enable memory JMX statistics
* @param enableMemoryStatistics
*/
public void setEnableMemoryStatistics(boolean enableMemoryStatistics) {
this.enableMemoryStatistics = enableMemoryStatistics;
}
public boolean isEnableImmediateSave() {
return enableImmediateSave;
}
public void setEnableImmediateSave(boolean enableImmediateSave) {
this.enableImmediateSave = enableImmediateSave;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("KhanSessionConfig{");
sb.append("useLibraryMode=").append(useLibraryMode);
sb.append(", namespace='").append(namespace).append('\'');
sb.append(", excludeRegExp='").append(excludeRegExp).append('\'');
sb.append(", sessionIdKey='").append(sessionIdKey).append('\'');
sb.append(", domain='").append(domain).append('\'');
sb.append(", path='").append(path).append('\'');
sb.append(", secure=").append(secure);
sb.append(", httpOnly=").append(httpOnly);
sb.append(", useAuthenticator=").append(useAuthenticator);
sb.append(", allowDuplicateLogin=").append(allowDuplicateLogin);
sb.append(", logoutUrl='").append(logoutUrl).append('\'');
sb.append(", sessionTimeoutMin=").append(sessionTimeoutMin);
sb.append(", sessionSaveDelay=").append(sessionSaveDelay);
sb.append(", enableStatistics=").append(enableStatistics);
sb.append(", enableMemoryStatistics=").append(enableMemoryStatistics);
sb.append(", enableImmediateSave=").append(enableImmediateSave);
sb.append('}');
return sb.toString();
}
}
| lgpl-2.1 |
dozed/align-api-project | procalign/src/main/java/fr/inrialpes/exmo/align/impl/eval/ThresholdGraphEvaluator.java | 5069 | /*
* $Id: ThresholdGraphEvaluator.java 1608 2011-05-28 20:21:16Z euzenat $
*
* Copyright (C) INRIA, 2004-2005, 2007-2010
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package fr.inrialpes.exmo.align.impl.eval;
import org.semanticweb.owl.align.Alignment;
import org.semanticweb.owl.align.AlignmentException;
import org.semanticweb.owl.align.Cell;
import fr.inrialpes.exmo.align.impl.Namespace;
import fr.inrialpes.exmo.align.parser.SyntaxElement;
import java.util.Properties;
import java.util.Vector;
import java.io.PrintWriter;
/**
* Compute the F-measure/precision/recall at various thresholds
*
* @author Jerome Euzenat
* @version $Id: ThresholdGraphEvaluator.java 1608 2011-05-28 20:21:16Z euzenat $
*
*/
public class ThresholdGraphEvaluator extends GraphEvaluator {
private int STEP = 50;
private double opt = 0.; // Optimum recorded value
public ThresholdGraphEvaluator() {
super();
}
/**
* Compute threshold graph
*/
public Vector<Pair> eval() { // throws AlignmentException
return eval( (Properties)null );
}
/**
* Returns a list of Measure at threshold points (Pairs)
* From an ordered vector of cells with their correctness status
*
* The basic strategy would be:
* Take the alignment/(Compute P/R/Apply threshold)+
* But it is better to: take the cells in reverse order
* Compute the measures on the fly
*
*/
public Vector<Pair> eval( Properties params ) { // throws AlignmentException
points = new Vector<Pair>(STEP+1);
opt = 0.;
int nbcorrect = 0;
int nbfound = 0;
double precision = 1.;
double recall = 0.;
double fmeasure = 0.;
double prevt = cellSet.first().cell().getStrength(); // threshold for previous fellow
double prevm = fmeasure;
points.add( new Pair( 1., prevm ) ); // [T=100%]
/*
// This is the continuous version
for ( EvalCell c : cellSet ) {
nbfound++;
if ( c.correct() ) nbcorrect++;
if ( c.cell().getStrength() != prevt ) { // may record a new point
fmeasure = 2*(double)nbcorrect/(double)(nbfound+nbexpected); // alternate formula
if ( fmeasure != prevm ) {
points.add( new Pair( prevt, prevm ) );
points.add( new Pair( c.cell().getStrength(), fmeasure ) );
prevm = fmeasure;
if ( fmeasure > opt ) opt = fmeasure; // for real optimal
}
prevt = c.cell().getStrength();
}
}
fmeasure = 2*(double)nbcorrect/(double)(nbfound+nbexpected);
*/
// This is the version with increment
// Determine what the increment is
double increment = 1./(double)STEP;
//System.err.println(" INCREMENT SET "+increment );
double next = 1.;
next -= increment;
for ( EvalCell c : cellSet ) {
fmeasure = 2*(double)nbcorrect/(double)(nbfound+nbexpected); // alternate formula
if ( fmeasure > opt && c.cell().getStrength() < prevt ) {
opt = fmeasure; // for real optimal
} else { // but only when all correspondences with same strength have been processed
prevt = c.cell().getStrength();
}
while ( next >= 0.001 && c.cell().getStrength() <= next ) { // increment achieved
points.add( new Pair( next, fmeasure ) );
next -= increment;
}
nbfound++;
if ( c.correct() ) {
nbcorrect++;
}
}
fmeasure = 2*(double)nbcorrect/(double)(nbfound+nbexpected);
if ( fmeasure > opt ) opt = fmeasure; // for real optimal
// In the end, it should exhaust all the thresholds
while ( next >= 0.001 ) { // The bound is necessary for avoiding tikz problem
points.add( new Pair( next, fmeasure ) ); // same measure
next -= increment;
}
points.add( new Pair( 0., fmeasure ) ); // [T=0%]
return points;
}
/**
* This output the result
*/
public void write(PrintWriter writer) throws java.io.IOException {
writer.println("<?xml version='1.0' encoding='utf-8' standalone='yes'?>");
writer.println("<"+SyntaxElement.RDF.print()+" xmlns:"+Namespace.RDF.shortCut+"='"+Namespace.RDF.prefix+"'>");
writer.println(" <output "+SyntaxElement.RDF_ABOUT.print()+"=''>");
writeXMLMap( writer );
writer.print(" <OPTIMUM>"+opt+"</OPTIMIM>\n");
writer.print(" </output>\n</"+SyntaxElement.RDF.print()+">\n");
}
public double getGlobalResult(){ // can only be the full measure
return opt;
}
public String xlabel() { return "threshold"; }
public String ylabel() { return "fmeasure"; }
}
| lgpl-2.1 |
cj3636/TheNewJourney | src/main/java/com/thenewjourney/compat/jei/arcane/ArcaneHandler.java | 1141 | package com.thenewjourney.compat.jei.arcane;
import mezz.jei.api.recipe.IRecipeHandler;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.item.ItemStack;
public class ArcaneHandler implements IRecipeHandler<ArcaneRecipe> {
@Override
public Class<ArcaneRecipe> getRecipeClass() {
return ArcaneRecipe.class;
}
@Override
public String getRecipeCategoryUid() {
return ArcaneCategory.ArcaneFURNACE;
}
@Override
public String getRecipeCategoryUid(ArcaneRecipe recipe) {
return ArcaneCategory.ArcaneFURNACE;
}
@Override
public IRecipeWrapper getRecipeWrapper(ArcaneRecipe recipe) {
return new ArcaneWrapper(recipe);
}
@Override
public boolean isRecipeValid(ArcaneRecipe recipe) {
if (recipe.getRecipeOutput() == null) {
return false;
}
int inputCount = 0;
for (ItemStack input : recipe.recipeItems) {
if (input != null) {
inputCount++;
}
}
if (inputCount > 9) {
return false;
}
return inputCount != 0;
}
}
| lgpl-2.1 |
codehaus/drone | src/java/com/uwyn/drone/core/exceptions/LogoffErrorException.java | 563 | /*
* Copyright 2002-2004 Geert Bevin <gbevin[remove] at uwyn dot com>
* Distributed under the terms of the GNU Lesser General Public
* License, v2.1 or later
*
* $Id$
*/
package com.uwyn.drone.core.exceptions;
import com.uwyn.drone.core.Bot;
public class LogoffErrorException extends CoreException
{
private Bot mBot = null;
public LogoffErrorException(Bot bot, Throwable cause)
{
super("Error while logging off bot '"+bot.getNick()+"' from server '"+bot.getServer()+"'.", cause);
mBot = bot;
}
public Bot getBot()
{
return mBot;
}
}
| lgpl-2.1 |
jodygarnett/GeoGig | src/web/api/src/test/java/org/locationtech/geogig/web/api/commands/PullTest.java | 18191 | /* Copyright (c) 2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Johnathan Garrett (Prominent Edge) - initial implementation
*/
package org.locationtech.geogig.web.api.commands;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonValue;
import org.junit.Rule;
import org.junit.Test;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.Ref;
import org.locationtech.geogig.model.RevCommit;
import org.locationtech.geogig.model.RevFeatureBuilder;
import org.locationtech.geogig.plumbing.ResolveGeogigURI;
import org.locationtech.geogig.porcelain.CloneOp;
import org.locationtech.geogig.porcelain.CommitOp;
import org.locationtech.geogig.porcelain.RemoteAddOp;
import org.locationtech.geogig.repository.NodeRef;
import org.locationtech.geogig.repository.Remote;
import org.locationtech.geogig.repository.Repository;
import org.locationtech.geogig.web.api.AbstractWebAPICommand;
import org.locationtech.geogig.web.api.AbstractWebOpTest;
import org.locationtech.geogig.web.api.CommandSpecException;
import org.locationtech.geogig.web.api.ParameterSet;
import org.locationtech.geogig.web.api.TestContext;
import org.locationtech.geogig.web.api.TestData;
import org.locationtech.geogig.web.api.TestParams;
public class PullTest extends AbstractWebOpTest {
@Rule
public TestContext remoteTestContext = new TestContext();
@Rule
public TestContext originalTestContext = new TestContext();
@Override
protected String getRoute() {
return "pull";
}
@Override
protected Class<? extends AbstractWebAPICommand> getCommandClass() {
return Pull.class;
}
@Override
protected boolean requiresTransaction() {
return false;
}
@Test
public void testBuildParameters() {
ParameterSet options = TestParams.of("all", "true", "ref", "master", "remoteName", "origin",
"authorName", "Tester", "authorEmail", "tester@example.com");
Pull op = (Pull) buildCommand(options);
assertEquals("master", op.refSpec);
assertEquals("origin", op.remoteName);
assertEquals("Tester", op.authorName.get());
assertEquals("tester@example.com", op.authorEmail.get());
assertTrue(op.fetchAll);
}
@Test
public void testPull() throws Exception {
Repository remoteGeogig = remoteTestContext.get().getRepository();
TestData remoteTestData = new TestData(remoteGeogig);
remoteTestData.init();
remoteTestData.loadDefaultData();
Ref remoteMaster = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName(Ref.MASTER).call().get();
Ref remoteBranch1 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch1").call().get();
Ref remoteBranch2 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch2").call().get();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
Remote remote = geogig.command(RemoteAddOp.class).setName("origin")
.setURL(remoteURI.toURL().toString()).call();
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "master");
buildCommand(options).run(testContext.get());
Ref master = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName(Ref.MASTER).call().get();
Ref branch1 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch1").call().get();
Ref branch2 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch2").call().get();
assertEquals(remoteMaster.getObjectId(), master.getObjectId());
assertEquals(remoteBranch1.getObjectId(), branch1.getObjectId());
assertEquals(remoteBranch2.getObjectId(), branch2.getObjectId());
JsonObject response = getJSONResponse().getJsonObject("response");
assertTrue(response.getBoolean("success"));
JsonObject pull = response.getJsonObject("Pull");
JsonObject remoteObject = pull.getJsonObject("Fetch").getJsonObject("Remote");
assertEquals(remote.getFetchURL(), remoteObject.getString("remoteURL"));
JsonArray branch = remoteObject.getJsonArray("Branch");
String expected = "[{\"changeType\":\"ADDED_REF\",\"name\":\"branch1\",\"newValue\":\""
+ branch1.getObjectId().toString() + "\"},"
+ "{\"changeType\":\"ADDED_REF\",\"name\":\"branch2\",\"newValue\":\""
+ branch2.getObjectId().toString() + "\"},"
+ "{\"changeType\":\"ADDED_REF\",\"name\":\"master\",\"newValue\":\""
+ master.getObjectId().toString() + "\"}]";
assertTrue(TestData.jsonEquals(TestData.toJSONArray(expected), branch, false));
assertEquals(remote.getFetchURL(), pull.getString("Remote"));
assertEquals("master", pull.getString("Ref"));
assertEquals(9, pull.getInt("Added"));
assertEquals(0, pull.getInt("Removed"));
assertEquals(0, pull.getInt("Modified"));
}
@Test
public void testPullNewBranch() throws Exception {
Repository remoteGeogig = remoteTestContext.get().getRepository();
TestData remoteTestData = new TestData(remoteGeogig);
remoteTestData.init();
remoteTestData.loadDefaultData();
Ref remoteMaster = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName(Ref.MASTER).call().get();
Ref remoteBranch1 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch1").call().get();
Ref remoteBranch2 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch2").call().get();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
Remote remote = geogig.command(RemoteAddOp.class).setName("origin")
.setURL(remoteURI.toURL().toString()).call();
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "branch1:newbranch");
buildCommand(options).run(testContext.get());
Ref master = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/master").call().get();
Ref branch1 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch1").call().get();
Ref branch2 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch2").call().get();
Ref newbranch = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("newbranch").call().get();
assertEquals(remoteMaster.getObjectId(), master.getObjectId());
assertEquals(remoteBranch1.getObjectId(), branch1.getObjectId());
assertEquals(remoteBranch2.getObjectId(), branch2.getObjectId());
assertEquals(remoteBranch1.getObjectId(), newbranch.getObjectId());
JsonObject response = getJSONResponse().getJsonObject("response");
assertTrue(response.getBoolean("success"));
JsonObject pull = response.getJsonObject("Pull");
JsonObject remoteObject = pull.getJsonObject("Fetch").getJsonObject("Remote");
assertEquals(remote.getFetchURL(), remoteObject.getString("remoteURL"));
JsonArray branch = remoteObject.getJsonArray("Branch");
String expected = "[{\"changeType\":\"ADDED_REF\",\"name\":\"branch1\",\"newValue\":\""
+ branch1.getObjectId().toString() + "\"},"
+ "{\"changeType\":\"ADDED_REF\",\"name\":\"branch2\",\"newValue\":\""
+ branch2.getObjectId().toString() + "\"},"
+ "{\"changeType\":\"ADDED_REF\",\"name\":\"master\",\"newValue\":\""
+ master.getObjectId().toString() + "\"}]";
assertTrue(TestData.jsonEquals(TestData.toJSONArray(expected), branch, false));
assertEquals(remote.getFetchURL(), pull.getString("Remote"));
assertEquals("newbranch", pull.getString("Ref"));
assertEquals(6, pull.getInt("Added"));
assertEquals(0, pull.getInt("Removed"));
assertEquals(0, pull.getInt("Modified"));
}
@Test
public void testPullNoUpdates() throws Exception {
Repository remoteGeogig = remoteTestContext.get().getRepository();
TestData remoteTestData = new TestData(remoteGeogig);
remoteTestData.init();
remoteTestData.loadDefaultData();
Ref remoteMaster = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName(Ref.MASTER).call().get();
Ref remoteBranch1 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch1").call().get();
Ref remoteBranch2 = remoteGeogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("branch2").call().get();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
geogig.command(CloneOp.class).setRepositoryURL(remoteURI.toURL().toString()).call();
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "master");
buildCommand(options).run(testContext.get());
Ref master = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/master").call().get();
Ref branch1 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch1").call().get();
Ref branch2 = geogig.command(org.locationtech.geogig.plumbing.RefParse.class)
.setName("refs/remotes/origin/branch2").call().get();
assertEquals(remoteMaster.getObjectId(), master.getObjectId());
assertEquals(remoteBranch1.getObjectId(), branch1.getObjectId());
assertEquals(remoteBranch2.getObjectId(), branch2.getObjectId());
JsonObject response = getJSONResponse().getJsonObject("response");
assertTrue(response.getBoolean("success"));
JsonObject pull = response.getJsonObject("Pull");
JsonObject fetchObj = pull.getJsonObject("Fetch");
assertTrue(TestData.jsonEquals(TestData.toJSON("{}"), fetchObj, false));
}
@Test
public void testPullFromTooShallowClone() throws Exception {
Repository originalGeogig = originalTestContext.get().getRepository();
TestData originalTestData = new TestData(originalGeogig);
originalTestData.init();
originalTestData.loadDefaultData();
URI originalURI = originalGeogig.command(ResolveGeogigURI.class).call().get();
// Set up the shallow clone
Repository remoteGeogig = remoteTestContext.get().getRepository();
remoteGeogig.command(CloneOp.class).setDepth(1)
.setRepositoryURL(originalURI.toURL().toString()).call();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
geogig.command(RemoteAddOp.class).setName("origin").setURL(remoteURI.toURL().toString())
.call();
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "master");
ex.expect(CommandSpecException.class);
ex.expectMessage("Unable to pull, the remote history is shallow.");
buildCommand(options).run(testContext.get());
}
@Test
public void testPullConflicts() throws Exception {
Repository remoteGeogig = remoteTestContext.get().getRepository();
TestData remoteTestData = new TestData(remoteGeogig);
remoteTestData.init();
remoteTestData.checkout("master");
remoteTestData.insert(TestData.point1);
remoteTestData.add();
RevCommit ancestor = remoteGeogig.command(CommitOp.class).setMessage("point1").call();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
geogig.command(CloneOp.class).setRepositoryURL(remoteURI.toURL().toString()).call();
remoteTestData.insert(TestData.point1_modified);
remoteTestData.add();
RevCommit theirs = remoteGeogig.command(CommitOp.class).setMessage("modify point1").call();
ObjectId point1_id = RevFeatureBuilder.build(TestData.point1_modified).getId();
testData.remove(TestData.point1);
testData.add();
RevCommit ours = geogig.command(CommitOp.class).setMessage("remove point1").call();
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "master");
buildCommand(options).run(testContext.get());
JsonObject response = getJSONResponse().getJsonObject("response");
assertTrue(response.getBoolean("success"));
JsonObject merge = response.getJsonObject("Merge");
assertEquals(ours.getId().toString(), merge.getString("ours"));
assertEquals(ancestor.getId().toString(), merge.getString("ancestor"));
assertEquals(theirs.getId().toString(), merge.getString("theirs"));
assertEquals(1, merge.getInt("conflicts"));
JsonArray featureArray = merge.getJsonArray("Feature");
assertEquals(1, featureArray.getValuesAs(JsonValue.class).size());
JsonObject feature = featureArray.getJsonObject(0);
assertEquals("CONFLICT", feature.getString("change"));
String path = NodeRef.appendChild(TestData.pointsType.getTypeName(),
TestData.point1.getID());
assertEquals(path, feature.getString("id"));
JsonArray geometryArray = feature.getJsonArray("geometry");
assertEquals(1, geometryArray.getValuesAs(JsonValue.class).size());
String geometry = geometryArray.getString(0);
assertEquals("POINT (0 0)", geometry);
assertEquals(point1_id.toString(), feature.getString("theirvalue"));
assertEquals(ObjectId.NULL.toString(), feature.getString("ourvalue"));
}
@Test
public void testPullConflictsDifferentBranch() throws Exception {
Repository remoteGeogig = remoteTestContext.get().getRepository();
TestData remoteTestData = new TestData(remoteGeogig);
remoteTestData.init();
remoteTestData.checkout("master");
remoteTestData.insert(TestData.point1);
remoteTestData.add();
RevCommit ancestor = remoteGeogig.command(CommitOp.class).setMessage("point1").call();
Repository geogig = testContext.get().getRepository();
TestData testData = new TestData(geogig);
testData.init();
testData.checkout("master");
URI remoteURI = remoteGeogig.command(ResolveGeogigURI.class).call().get();
geogig.command(CloneOp.class).setRepositoryURL(remoteURI.toURL().toString()).call();
remoteTestData.insert(TestData.point1_modified);
remoteTestData.add();
RevCommit theirs = remoteGeogig.command(CommitOp.class).setMessage("modify point1").call();
ObjectId point1_id = RevFeatureBuilder.build(TestData.point1_modified).getId();
testData.remove(TestData.point1);
testData.add();
RevCommit ours = geogig.command(CommitOp.class).setMessage("remove point1").call();
testData.branchAndCheckout("branch1");
ParameterSet options = TestParams.of("remoteName", "origin", "ref", "master:branch1");
buildCommand(options).run(testContext.get());
JsonObject response = getJSONResponse().getJsonObject("response");
assertTrue(response.getBoolean("success"));
JsonObject merge = response.getJsonObject("Merge");
assertEquals(ours.getId().toString(), merge.getString("ours"));
assertEquals(ancestor.getId().toString(), merge.getString("ancestor"));
assertEquals(theirs.getId().toString(), merge.getString("theirs"));
assertEquals(1, merge.getInt("conflicts"));
JsonArray featureArray = merge.getJsonArray("Feature");
assertEquals(1, featureArray.getValuesAs(JsonValue.class).size());
JsonObject feature = featureArray.getJsonObject(0);
assertEquals("CONFLICT", feature.getString("change"));
String path = NodeRef.appendChild(TestData.pointsType.getTypeName(),
TestData.point1.getID());
assertEquals(path, feature.getString("id"));
JsonArray geometryArray = feature.getJsonArray("geometry");
assertEquals(1, geometryArray.getValuesAs(JsonValue.class).size());
String geometry = geometryArray.getString(0);
assertEquals("POINT (0 0)", geometry);
assertEquals(point1_id.toString(), feature.getString("theirvalue"));
assertEquals(ObjectId.NULL.toString(), feature.getString("ourvalue"));
}
}
| lgpl-2.1 |
optivo-org/fingbugs-1.3.9-optivo | src/java/edu/umd/cs/findbugs/ba/Location.java | 4434 | /*
* Bytecode Analysis Framework
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba;
import org.apache.bcel.generic.InstructionHandle;
import edu.umd.cs.findbugs.annotations.NonNull;
/**
* A class representing a location in the CFG for a method.
* Essentially, it represents a static instruction, <em>with the important caveat</em>
* that CFGs have inlined JSR subroutines, meaning that a single InstructionHandle
* in a CFG may represent several static locations. To this end, a Location
* is comprised of both an InstructionHandle and the BasicBlock that
* contains it.
* <p/>
* <p> Location objects may be compared with each other using the equals() method,
* and may be used as keys in tree and hash maps and sets.
* Note that <em>it is only valid to compare Locations produced from the same CFG</em>.
*
* @author David Hovemeyer
* @see CFG
*/
public class Location implements Comparable<Location> {
private final InstructionHandle handle;
private final BasicBlock basicBlock;
private int hash;
/**
* Constructor.
*
* @param handle the instruction
* @param basicBlock the basic block containing the instruction
*/
public Location(@NonNull InstructionHandle handle, @NonNull BasicBlock basicBlock) {
if (handle == null) throw new NullPointerException("handle cannot be null");
if (basicBlock == null) throw new NullPointerException("basicBlock cannot be null");
this.handle = handle;
this.basicBlock = basicBlock;
}
public static Location getFirstLocation(@NonNull BasicBlock basicBlock) {
InstructionHandle location = basicBlock.getFirstInstruction();
if (location == null)
return null;
return new Location(location, basicBlock);
}
public static Location getLastLocation(@NonNull BasicBlock basicBlock) {
InstructionHandle lastInstruction = basicBlock.getLastInstruction();
/*
if (lastInstruction == null)
lastInstruction = basicBlock.getExceptionThrower();
if (lastInstruction == null)
lastInstruction = basicBlock.getFirstInstruction();
*/
if (lastInstruction == null)
return null;
return new Location(lastInstruction, basicBlock);
}
/**
* Get the instruction handle.
*/
public InstructionHandle getHandle() {
return handle;
}
/**
* Get the basic block.
*/
public BasicBlock getBasicBlock() {
return basicBlock;
}
/**
* Return whether or not the Location is positioned at the
* first instruction in the basic block.
*/
public boolean isFirstInstructionInBasicBlock() {
return !basicBlock.isEmpty() && handle == basicBlock.getFirstInstruction();
}
/**
* Return whether or not the Location is positioned at the
* last instruction in the basic block.
*/
public boolean isLastInstructionInBasicBlock() {
return !basicBlock.isEmpty() && handle == basicBlock.getLastInstruction();
}
public int compareTo(Location other) {
int pos = handle.getPosition() - other.handle.getPosition();
return pos;
}
@Override
public int hashCode() {
if(hash == 0){
return hash = System.identityHashCode(basicBlock) + handle.getPosition();
}
return hash;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Location))
return false;
Location other = (Location) o;
return basicBlock == other.basicBlock && handle == other.handle;
}
@Override
public String toString() {
return handle.toString() + " in basic block " + basicBlock.getLabel();
}
/**
* @return a compact string of the form "bb:xx", where "bb" is the
* basic block number and "xx" is the bytecode offset
*/
public String toCompactString() {
return basicBlock.getLabel() + ":" + handle.getPosition();
}
}
//vim:ts=4
| lgpl-2.1 |
gado4b2/device-controllers | message-broker-common/src/main/java/com/hpe/broker/service/consumer/kafka/KafkaConsumerService.java | 5973 | package com.hpe.broker.service.consumer.kafka;
import static com.hpe.broker.utility.UtilityLogger.logExceptionStackTrace;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import com.hpe.broker.service.consumer.BrokerConsumerService;
import com.hpe.broker.service.consumer.handler.BrokerConsumerDataHandler;
/**
* @author sveera
*
*/
public class KafkaConsumerService<K, V> implements BrokerConsumerService<V> {
private final Logger logger = getLogger(getClass());
private final String kafkaBootStrapServers;
private final String keyDeSerializerClass;
private final String valueDeSerializerClass;
private final String consumerGroupId;
private final List<KafkaConsumerRunnable> kafkaConsumers = new CopyOnWriteArrayList<>();
protected final ExecutorService executorService;
public KafkaConsumerService(String kafkaBootStrapServers, String keyDeSerializerClass,
String valueDeSerializerClass, String consumerGroupId, ExecutorService executorService) {
super();
this.kafkaBootStrapServers = kafkaBootStrapServers;
this.keyDeSerializerClass = keyDeSerializerClass;
this.valueDeSerializerClass = valueDeSerializerClass;
this.consumerGroupId = consumerGroupId;
this.executorService = executorService;
}
@Override
public String getName() {
return "kafka";
}
@Override
public void startService() {
}
@Override
public void stopService() {
for (KafkaConsumerRunnable kafkaConsumerRunnable : kafkaConsumers)
kafkaConsumerRunnable.stopKafkaConsumerRunnable();
}
@Override
public void consumeData(String destination, BrokerConsumerDataHandler<V> brokerConsumerDataHandler) {
KafkaConsumerRunnable kafkaConsumerRunnable = new KafkaConsumerRunnable(destination, brokerConsumerDataHandler);
startConsumerThread(kafkaConsumerRunnable);
}
protected void startConsumerThread(KafkaConsumerRunnable kafkaConsumerRunnable) {
kafkaConsumers.add(kafkaConsumerRunnable);
logger.debug(
"Trying to start new " + KafkaConsumerRunnable.class.getSimpleName() + " : " + kafkaConsumerRunnable);
executorService.submit(kafkaConsumerRunnable);
}
protected class KafkaConsumerRunnable implements Runnable {
private final Logger logger = getLogger(getClass());
private final String auto_commit_interval_ms = "1000";
private final int polling_interval = 100;
private final String destination;
private final BrokerConsumerDataHandler<V> brokerConsumerDataHandler;
private volatile boolean isConsumerRunnable;
private KafkaConsumer<K, V> kafkaConsumer;
public KafkaConsumerRunnable(String destination, BrokerConsumerDataHandler<V> brokerConsumerDataHandler) {
this.destination = destination;
this.brokerConsumerDataHandler = brokerConsumerDataHandler;
}
@Override
public void run() {
try {
tryInstantiatingKafkaConsumer();
while (isConsumerRunnable)
startPollingForRecords();
} catch (Throwable th) {
logExceptionStackTrace(th, getClass());
} finally {
closingKafkaConsumer();
}
}
public void stopKafkaConsumerRunnable() {
isConsumerRunnable = false;
if (kafkaConsumer != null)
kafkaConsumer.wakeup();
}
private void tryInstantiatingKafkaConsumer() {
try {
initKafkaConsumer();
kafkaConsumer.subscribe(Collections.singletonList(destination));
isConsumerRunnable = true;
} catch (Exception e) {
logExceptionStackTrace(e, getClass());
throw new RuntimeException("Failed to start " + this.getClass().getSimpleName());
}
}
private void initKafkaConsumer() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
final Properties properties = new Properties();
properties.setProperty("bootstrap.servers", kafkaBootStrapServers);
properties.setProperty("group.id", consumerGroupId);
properties.setProperty("auto.commit.interval.ms", auto_commit_interval_ms);
final Deserializer<K> keySerializer = keyDeSerializerClass == null || keyDeSerializerClass.isEmpty()
? (Deserializer<K>) new StringDeserializer()
: (Deserializer<K>) Class.forName(keyDeSerializerClass).newInstance();
final Deserializer<V> valueSerializer = valueDeSerializerClass == null || valueDeSerializerClass.isEmpty()
? (Deserializer<V>) new StringDeserializer()
: (Deserializer<V>) Class.forName(valueDeSerializerClass).newInstance();
kafkaConsumer = new KafkaConsumer<>(properties, keySerializer, valueSerializer);
logger.trace("Kafka Consumer Instance been created " + kafkaConsumer);
}
protected void startPollingForRecords() {
ConsumerRecords<K, V> records = kafkaConsumer.poll(polling_interval);
for (ConsumerRecord<K, V> consumerRecord : records)
tryProcessingMessage(consumerRecord);
kafkaConsumer.commitSync();
}
private void tryProcessingMessage(ConsumerRecord<K, V> consumerRecord) {
try {
logger.trace("Received consumer record in " + this.getClass().getSimpleName() + " with value "
+ consumerRecord.toString());
brokerConsumerDataHandler.handleConsumerMessage(consumerRecord.topic(), consumerRecord.value());
} catch (Throwable e) {
logExceptionStackTrace(e, getClass());
}
}
private void closingKafkaConsumer() {
if (kafkaConsumer != null)
kafkaConsumer.close();
logger.trace("Closed " + this.toString() + " successfully.");
}
@Override
public String toString() {
return "KafkaConsumerRunnable [destination=" + destination + ", brokerConsumerDataHandler="
+ brokerConsumerDataHandler + "]";
}
}
}
| lgpl-2.1 |
whdc/ieo-beast | src/dr/app/beauti/BeautiFrame.java | 34941 | /*
* BeautiFrame.java
*
* (c) 2002-2005 BEAST Development Core Team
*
* This package may be distributed under the
* Lesser Gnu Public Licence (LGPL)
*/
package dr.app.beauti;
import dr.app.beauti.ancestralStatesPanel.AncestralStatesPanel;
import dr.app.beauti.clockModelsPanel.OldClockModelsPanel;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.components.ancestralstates.AncestralStatesComponentFactory;
import dr.app.beauti.components.continuous.ContinuousComponentFactory;
import dr.app.beauti.components.discrete.DiscreteTraitsComponentFactory;
import dr.app.beauti.components.dollo.DolloComponentFactory;
import dr.app.beauti.components.hpm.HierarchicalModelComponentFactory;
import dr.app.beauti.components.sequenceerror.SequenceErrorModelComponentFactory;
import dr.app.beauti.components.tipdatesampling.TipDateSamplingComponentFactory;
import dr.app.beauti.datapanel.DataPanel;
import dr.app.beauti.generator.BeastGenerator;
import dr.app.beauti.generator.Generator;
import dr.app.beauti.mcmcpanel.MCMCPanel;
import dr.app.beauti.operatorspanel.OperatorsPanel;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.PartitionTreePrior;
import dr.app.beauti.options.STARBEASTOptions;
import dr.app.beauti.options.TraitData;
import dr.app.beauti.priorsPanel.DefaultPriorDialog;
import dr.app.beauti.priorsPanel.PriorsPanel;
import dr.app.beauti.siteModelsPanel.SiteModelsPanel;
import dr.app.beauti.taxonsetspanel.SpeciesSetPanel;
import dr.app.beauti.taxonsetspanel.TaxonSetPanel;
import dr.app.beauti.tipdatepanel.TipDatesPanel;
import dr.app.beauti.traitspanel.TraitsPanel;
import dr.app.beauti.treespanel.TreesPanel;
import dr.app.beauti.util.BEAUTiImporter;
import dr.app.beauti.util.TextUtil;
import dr.app.gui.FileDrop;
import dr.app.util.OSType;
import dr.app.util.Utils;
import dr.evolution.io.Importer.ImportException;
import dr.evolution.io.NexusImporter.MissingBlockException;
import jam.framework.DocumentFrame;
import jam.framework.Exportable;
import jam.util.IconUtils;
import org.jdom.JDOMException;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.BorderUIResource;
import java.awt.*;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.io.*;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: BeautiFrame.java,v 1.22 2006/09/09 16:07:06 rambaut Exp $
*/
public class BeautiFrame extends DocumentFrame {
private static final long serialVersionUID = 2114148696789612509L;
public final static String DATA_PARTITIONS = "Partitions";
public final static String TAXON_SETS = "Taxa";
public final static String TIP_DATES = "Tips";
public final static String TRAITS = "Traits";
public final static String SITE_MODELS = "Sites";
public final static String CLOCK_MODELS = "Clocks";
public final static String TREES = "Trees";
public final static String ANCESTRAL_STATES = "States";
public final static String PRIORS = "Priors";
public final static String OPERATORS = "Operators";
public final static String MCMC = "MCMC";
private BeautiOptions options;
private BeastGenerator generator;
private final ComponentFactory[] components;
public final JTabbedPane tabbedPane = new JTabbedPane();
public final JLabel statusLabel = new JLabel();
private DataPanel dataPanel;
private TipDatesPanel tipDatesPanel;
private TraitsPanel traitsPanel;
private TaxonSetPanel taxonSetPanel;
private SpeciesSetPanel speciesSetPanel;
private SiteModelsPanel siteModelsPanel;
private AncestralStatesPanel ancestralStatesPanel;
private OldClockModelsPanel clockModelsPanel;
private TreesPanel treesPanel;
private PriorsPanel priorsPanel;
private OperatorsPanel operatorsPanel;
private MCMCPanel mcmcPanel;
private BeautiPanel currentPanel;
private JFileChooser importChooser; // make JFileChooser chooser remember previous path
private JFileChooser exportChooser; // make JFileChooser chooser remember previous path
final Icon gearIcon = IconUtils.getIcon(this.getClass(), "images/gear.png");
public BeautiFrame(String title) {
super();
setTitle(title);
// Prevent the application to close in requestClose()
// after a user cancel or a failure in beast file generation
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// getOpenAction().setEnabled(false);
// getSaveAction().setEnabled(false);
getFindAction().setEnabled(false);
getZoomWindowAction().setEnabled(false);
components = new ComponentFactory[] {
AncestralStatesComponentFactory.INSTANCE,
ContinuousComponentFactory.INSTANCE,
DiscreteTraitsComponentFactory.INSTANCE,
// DnDsComponentFactory.INSTANCE,
DolloComponentFactory.INSTANCE,
HierarchicalModelComponentFactory.INSTANCE,
SequenceErrorModelComponentFactory.INSTANCE,
TipDateSamplingComponentFactory.INSTANCE
};
options = new BeautiOptions(components);
generator = new BeastGenerator(options, components);
this.getContentPane().addHierarchyBoundsListener(new HierarchyBoundsListener() {
public void ancestorMoved(HierarchyEvent e) {
}
public void ancestorResized(HierarchyEvent e) {
setStatusMessage();
}
});
}
public void initializeComponents() {
dataPanel = new DataPanel(this, getImportAction(), getDeleteAction()/*, getImportTraitsAction()*/);
tipDatesPanel = new TipDatesPanel(this);
traitsPanel = new TraitsPanel(this, dataPanel, getImportTraitsAction());
taxonSetPanel = new TaxonSetPanel(this);
speciesSetPanel = new SpeciesSetPanel(this);
siteModelsPanel = new SiteModelsPanel(this, getDeleteAction());
ancestralStatesPanel = new AncestralStatesPanel(this);
clockModelsPanel = new OldClockModelsPanel(this);
// oldTreesPanel = new OldTreesPanel(this);
treesPanel = new TreesPanel(this, getDeleteAction());
// speciesTreesPanel = new SpeciesTreesPanel(this);
priorsPanel = new PriorsPanel(this, false);
operatorsPanel = new OperatorsPanel(this);
mcmcPanel = new MCMCPanel(this);
int index = 0;
tabbedPane.addTab(DATA_PARTITIONS, dataPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Import sequence alignments, organize data partitions,<br>" +
"link models between partitions and select *BEAST</html>");
tabbedPane.addTab(TAXON_SETS, taxonSetPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Create and edit sets of taxa which can be used to <br>" +
"define times of most recent common ancestors and <br>" +
"to keep groups monophyletic.</html>");
// tabbedPane.addTab("Species Sets", speciesSetPanel);
tabbedPane.addTab(TIP_DATES, tipDatesPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Specify sampling dates of tips for use in temporal <br>" +
"analyses of measurably evolving populations.</html>");
tabbedPane.addTab(TRAITS, traitsPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Import and organize continuous and discrete traits <br>" +
"for taxa, convert them into data partitions for evolutionary<br>" +
"analysis.</html>");
tabbedPane.addTab(SITE_MODELS, siteModelsPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Select evolutionary models to be used for each data <br>" +
"partition including substitution models, codon partitioning<br>" +
"and trait evolution models.</html>");
tabbedPane.addTab(CLOCK_MODELS, clockModelsPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Select relaxed molecular clock models to be used across <br>" +
"the tree. Specify sampling of rates.</html>");
tabbedPane.addTab(TREES, treesPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Select the priors on trees including coalescent models<br>" +
"birth-death speciation models and the *BEAST gene tree,<br>" +
"species tree options.</html>");
tabbedPane.addTab(ANCESTRAL_STATES, ancestralStatesPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Select options for sampling ancestral states at specific<br>" +
"or all common ancestors, models of counting state changes<br>" +
"and models of sequencing error for data partitions.</html>");
tabbedPane.addTab(PRIORS, priorsPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Specify prior probability distributions on each and every<br>" +
"parameter of the current model.</html>");
tabbedPane.addTab(OPERATORS, operatorsPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Select and adjust the menu of operators that will be used<br>" +
"to propose changes to the parameters. Switch off operators<br>" +
"on certain parameters to fix them to initial values.</html>");
tabbedPane.addTab(MCMC, mcmcPanel);
tabbedPane.setToolTipTextAt(index++, "<html>" +
"Specify the details of MCMC sampling. This includes chain<br>" +
"length, sampling frequencies, log file names and more.</html>");
for (int i = 1; i < tabbedPane.getTabCount(); i++) {
tabbedPane.setEnabledAt(i, false);
}
currentPanel = (BeautiPanel) tabbedPane.getSelectedComponent();
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
BeautiPanel selectedPanel = (BeautiPanel) tabbedPane.getSelectedComponent();
if (selectedPanel == dataPanel) {
dataPanel.selectionChanged();
} else {
getDeleteAction().setEnabled(false);
}
currentPanel.getOptions(options);
setAllOptions();
currentPanel = selectedPanel;
}
});
JPanel basePanel = new JPanel(new BorderLayout(6, 6));
basePanel.setBorder(new BorderUIResource.EmptyBorderUIResource(new java.awt.Insets(12, 12, 12, 12)));
// basePanel.setPreferredSize(new java.awt.Dimension(800, 600));
getExportAction().setEnabled(false);
JButton generateButton = new JButton(getExportAction());
generateButton.putClientProperty("JButton.buttonType", "roundRect");
JPanel panel2 = new JPanel(new BorderLayout(6, 6));
panel2.add(statusLabel, BorderLayout.WEST);
panel2.add(generateButton, BorderLayout.EAST);
panel2.setMinimumSize(new java.awt.Dimension(10, 10));
basePanel.add(tabbedPane, BorderLayout.CENTER);
basePanel.add(panel2, BorderLayout.SOUTH);
add(basePanel, BorderLayout.CENTER);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
// System.out.println("Screen width = " + d.width);
// System.out.println("Screen height = " + d.height);
if (d.width < 1000 || d.height < 700) {
setSize(new java.awt.Dimension(700, 550));
} else {
setSize(new java.awt.Dimension(1024, 768));
}
if (OSType.isMac()) {
setMinimumSize(new java.awt.Dimension(640, 480));
}
setAllOptions();
// make JFileChooser chooser remember previous path
exportChooser = new JFileChooser(Utils.getCWD());
exportChooser.setFileFilter(new FileNameExtensionFilter("BEAST XML File", "xml", "beast"));
exportChooser.setDialogTitle("Generate BEAST XML File...");
importChooser = new JFileChooser(Utils.getCWD());
importChooser.setMultiSelectionEnabled(true);
importChooser.setFileFilter(new FileNameExtensionFilter(
"Microsatellite (tab-delimited *.txt) Files", "txt"));
importChooser.setFileFilter(new FileNameExtensionFilter(
"NEXUS (*.nex) & BEAST (*.xml) Files", "nex", "nexus", "nx", "xml", "beast", "fa", "fasta", "afa"));
importChooser.setDialogTitle("Import Aligment...");
Color focusColor = UIManager.getColor("Focus.color");
Border focusBorder = BorderFactory.createMatteBorder(2, 2, 2, 2, focusColor);
dataPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
new FileDrop(null, dataPanel, focusBorder, new FileDrop.Listener() {
public void filesDropped(java.io.File[] files) {
importFiles(files);
} // end filesDropped
}); // end FileDrop.Listener
}
/**
* set all the options for all panels
*/
public void setAllOptions() {
try {
dataPanel.setOptions(options);
tipDatesPanel.setOptions(options);
traitsPanel.setOptions(options);
if (options.useStarBEAST) {
speciesSetPanel.setOptions(options);
} else {
taxonSetPanel.setOptions(options);
}
siteModelsPanel.setOptions(options);
clockModelsPanel.setOptions(options);
treesPanel.setOptions(options);
ancestralStatesPanel.setOptions(options);
priorsPanel.setOptions(options);
operatorsPanel.setOptions(options);
mcmcPanel.setOptions(options);
setStatusMessage();
} catch (IllegalArgumentException illegEx) {
JOptionPane.showMessageDialog(this, illegEx.getMessage(),
"Illegal Argument Exception", JOptionPane.ERROR_MESSAGE);
}
// enable/disable the other tabs and generate option depending on whether any
// data has been loaded.
boolean enabled = options.getDataPartitions().size() > 0;
for (int i = 1; i < tabbedPane.getTabCount(); i++) {
tabbedPane.setEnabledAt(i, enabled);
}
getExportAction().setEnabled(enabled);
}
/**
* get all the options for all panels
*/
private void getAllOptions() {
try {
dataPanel.getOptions(options);
tipDatesPanel.getOptions(options);
traitsPanel.getOptions(options);
if (options.useStarBEAST) {
speciesSetPanel.getOptions(options);
} else {
taxonSetPanel.getOptions(options);
}
siteModelsPanel.getOptions(options);
clockModelsPanel.getOptions(options);
treesPanel.getOptions(options);
ancestralStatesPanel.getOptions(options);
priorsPanel.getOptions(options);
operatorsPanel.getOptions(options);
mcmcPanel.getOptions(options);
} catch (IllegalArgumentException illegEx) {
JOptionPane.showMessageDialog(this, illegEx.getMessage(),
"Illegal Argument Exception", JOptionPane.ERROR_MESSAGE);
}
}
public void doSelectAll() {
if (currentPanel == dataPanel) {
dataPanel.selectAll();
}
}
public final void dataSelectionChanged(boolean isSelected) {
getDeleteAction().setEnabled(isSelected);
}
public final void modelSelectionChanged(boolean isSelected) {
getDeleteAction().setEnabled(isSelected);
}
public void doDelete() {
if (tabbedPane.getSelectedComponent() == dataPanel) {
dataPanel.removeSelection();
// } else if (tabbedPane.getSelectedComponent() == modelsPanel) {
// modelsPanel.delete();
// } else if (tabbedPane.getSelectedComponent() == treesPanel) {
// treesPanel.delete();
} else {
throw new RuntimeException("Delete should only be accessable from the Data and Models panels");
}
setStatusMessage();
}
public boolean requestClose() {
if (isDirty() && options.hasData()) {
int option = JOptionPane.showConfirmDialog(this,
"You have made changes but have not generated\n" +
"a BEAST XML file. Do you wish to generate\n" +
"before closing this window?",
"Unused changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
return doGenerate();
} else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.DEFAULT_OPTION) {
return false;
}
return true;
}
return true;
}
public void doApplyTemplate() {
FileDialog dialog = new FileDialog(this,
"Apply Template",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
readFromFile(file);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "Unable to open template file: File not found",
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to read template file: " + ioe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
}
}
}
protected boolean readFromFile(File file) throws IOException {
FileInputStream fileIn =
new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
try {
options = (BeautiOptions) in.readObject();
} catch (ClassNotFoundException cnfe) {
JOptionPane.showMessageDialog(this, "Unable to read BEAUti file: " + cnfe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
cnfe.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return false;
}
in.close();
fileIn.close();
generator = new BeastGenerator(options, components);
return true;
}
public String getDefaultFileName() {
return options.fileNameStem + ".beauti";
}
protected boolean writeToFile(File file) throws IOException {
OutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(options);
out.close();
fileOut.close();
return true;
}
public final void doImport() {
int returnVal = importChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File[] files = importChooser.getSelectedFiles();
importFiles(files);
tabbedPane.setSelectedComponent(dataPanel);
}
}
private void importFiles(File[] files) {
for (File file : files) {
if (file == null || file.getName().equals("")) {
JOptionPane.showMessageDialog(this, "Invalid file name",
"Invalid file name", JOptionPane.ERROR_MESSAGE);
} else {
try {
BEAUTiImporter beautiImporter = new BEAUTiImporter(this, options);
beautiImporter.importFromFile(file);
setDirty();
// } catch (FileNotFoundException fnfe) {
// JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
// "Unable to open file", JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "File I/O Error unable to read file: " + ioe.getMessage(),
"Unable to read file", JOptionPane.ERROR_MESSAGE);
ioe.printStackTrace();
// there may be other files in the list so don't return
// return;
} catch (MissingBlockException ex) {
JOptionPane.showMessageDialog(this, "TAXON, DATA or CHARACTERS block is missing in Nexus file: " + ex,
"Missing Block in Nexus File",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
} catch (ImportException ime) {
JOptionPane.showMessageDialog(this, "Error parsing imported file: " + ime,
"Error reading file",
JOptionPane.ERROR_MESSAGE);
ime.printStackTrace();
} catch (JDOMException jde) {
JOptionPane.showMessageDialog(this, "Error parsing imported file: " + jde,
"Error reading file",
JOptionPane.ERROR_MESSAGE);
jde.printStackTrace();
// } catch (IllegalArgumentException illegEx) {
// JOptionPane.showMessageDialog(this, illegEx.getMessage(),
// "Illegal Argument Exception", JOptionPane.ERROR_MESSAGE);
//
// } catch (Exception ex) {
// JOptionPane.showMessageDialog(this, "Fatal exception: " + ex,
// "Error reading file",
// JOptionPane.ERROR_MESSAGE);
// ex.printStackTrace();
// return;
}
}
}
if (!options.hasIdenticalTaxa()) {
setAllOptions(); // need this to refresh panels otherwise it will throw exception
dataPanel.selectAll();
dataPanel.unlinkTrees();
}
setAllOptions();
}
public final boolean doImportTraits() {
if (options.taxonList != null) { // validation of check empty taxonList
FileDialog dialog = new FileDialog(this,
"Import Traits File...",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() != null) {
final File file = new File(dialog.getDirectory(), dialog.getFile());
try {
BEAUTiImporter beautiImporter = new BEAUTiImporter(this, options);
beautiImporter.importTraits(file);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
return false;
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
return false;
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Fatal exception: " + ex,
"Error reading file",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
return false;
}
} else {
return false;
}
traitsPanel.fireTraitsChanged();
setAllOptions();
tabbedPane.setSelectedComponent(traitsPanel);
return true;
} else {
JOptionPane.showMessageDialog(this, "No taxa loaded yet, please import Alignment file.",
"No taxa loaded", JOptionPane.ERROR_MESSAGE);
return false;
}
}
public boolean validateTraitName(String traitName) {
// check that the name is valid
if (traitName.trim().length() == 0) {
Toolkit.getDefaultToolkit().beep();
return false;
}
// disallow a trait called 'date'
if (traitName.equalsIgnoreCase("date")) {
JOptionPane.showMessageDialog(this,
"This trait name has a special meaning. Use the 'Tip Date' panel\n" +
" to set dates for taxa.",
"Reserved trait name",
JOptionPane.WARNING_MESSAGE);
return false;
}
if (options.useStarBEAST && traitName.equalsIgnoreCase(TraitData.TRAIT_SPECIES)) {
JOptionPane.showMessageDialog(this,
"This trait name is already in used to denote species\n" +
"for *BEAST. Please select a different name.",
"Reserved trait name",
JOptionPane.WARNING_MESSAGE);
return false;
}
// check that the trait name doesn't exist
if (options.traitExists(traitName)) {
int option = JOptionPane.showConfirmDialog(this,
"A trait of this name already exists. Do you wish to replace\n" +
"it with this new trait? This may result in the loss or change\n" +
"in trait values for the taxa.",
"Overwrite trait?",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.NO_OPTION) {
return false;
}
}
return true;
}
/**
* Attempts to set up starBEAST - returns true if successful
* @param useStarBEAST
* @return
*/
public boolean setupStarBEAST(boolean useStarBEAST) {
if (useStarBEAST) {
if (!options.traitExists(TraitData.TRAIT_SPECIES)) {
if (!traitsPanel.addTrait(
"<html><p>" +
"StarBEAST requires a trait to give species designations<br>" +
"for each taxon. Create or import a discrete trait<br>" +
"labelled 'species'.</p></html>",
TraitData.TRAIT_SPECIES,
true /* isSpeciesTrait */
)) {
return false;
}
} else if (options.getTraitPartitions(options.getTrait(TraitData.TRAIT_SPECIES)).size() > 0) {
int option = JOptionPane.showConfirmDialog(this,
"The trait named '" + TraitData.TRAIT_SPECIES + "', used to denote species in *BEAST, is\n" +
"already in use as a data partition. Do you wish to continue?",
"Species trait already in use",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (option == JOptionPane.NO_OPTION) {
return false;
}
}
dataPanel.selectAll();
dataPanel.unlinkAll();
options.starBEASTOptions = new STARBEASTOptions(options);
options.fileNameStem = "StarBEASTLog";
tabbedPane.removeTabAt(1);
tabbedPane.insertTab("Species Sets", null, speciesSetPanel, null, 1);
} else { // remove species
options.fileNameStem = MCMCPanel.DEFAULT_FILE_NAME_STEM;
tabbedPane.removeTabAt(1);
tabbedPane.insertTab("Taxon Sets", null, taxonSetPanel, null, 1);
}
options.useStarBEAST = useStarBEAST;
treesPanel.updatePriorPanelForSpeciesAnalysis();
setStatusMessage();
return true;
}
public void updateDiscreteTraitAnalysis() {
setStatusMessage();
}
public void setupEBSP() {
dataPanel.selectAll();
dataPanel.unlinkAll();
setAllOptions();
}
public PartitionTreePrior getCurrentPartitionTreePrior() {
treesPanel.setOptions(options); // need this to refresh the currentTreeModel
return treesPanel.currentTreeModel.getPartitionTreePrior();
}
public void setStatusMessage() {
int width = this.getWidth() - 260; // minus generate button size
if (width < 100) width = 100; // prevent too narrow
String tw = TextUtil.wrapText(options.statusMessage(), statusLabel, width);
// System.out.println(this.getWidth() + " " + tw);
statusLabel.setText(tw);
}
public final boolean doGenerate() {
try {
generator.checkOptions();
} catch (Generator.GeneratorException ge) {
JOptionPane.showMessageDialog(this, ge.getMessage(), "Invalid BEAUti setting : ",
JOptionPane.ERROR_MESSAGE);
if (ge.getSwitchToPanel() != null) {
switchToPanel(ge.getSwitchToPanel());
}
return false;
}
DefaultPriorDialog defaultPriorDialog = new DefaultPriorDialog(this);
if (!defaultPriorDialog.showDialog(options)) {
return false;
}
// offer stem as default
exportChooser.setSelectedFile(new File(options.fileNameStem + ".xml"));
final int returnVal = exportChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = exportChooser.getSelectedFile();
int n = JOptionPane.YES_OPTION;
if (file.exists()) {
n = JOptionPane.showConfirmDialog(this, file.getName(),
"Overwrite the existing file?", JOptionPane.YES_NO_OPTION);
}
if (n == JOptionPane.YES_OPTION) {
try {
getAllOptions();
generator.generateXML(file);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to generate file due to I/O issue: " + ioe.getMessage(),
"Unable to generate file", JOptionPane.ERROR_MESSAGE);
return false;
} catch (Generator.GeneratorException e) {
JOptionPane.showMessageDialog(this, "The BEAST XML is incomplete because :\n" + e.getMessage(),
"The BEAST XML is incomplete", JOptionPane.ERROR_MESSAGE);
return false;
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unable to generate file: " + e.getMessage(),
"Unable to generate file", JOptionPane.ERROR_MESSAGE);
return false;
}
} else {
doGenerate();
}
}
clearDirty();
return true;
}
public void switchToPanel(String panelName) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (tabbedPane.getTitleAt(i).equals(panelName)) {
tabbedPane.setSelectedIndex(i);
break;
}
}
}
public JComponent getExportableComponent() {
JComponent exportable = null;
Component comp = tabbedPane.getSelectedComponent();
if (comp instanceof Exportable) {
exportable = ((Exportable) comp).getExportableComponent();
} else if (comp instanceof JComponent) {
exportable = (JComponent) comp;
}
return exportable;
}
// public boolean doSave() {
// return doSaveAs();
// }
//
// public boolean doSaveAs() {
// FileDialog dialog = new FileDialog(this,
// "Save Template As...",
// FileDialog.SAVE);
//
// dialog.setVisible(true);
// if (dialog.getFile() == null) {
// // the dialog was cancelled...
// return false;
// }
//
// File file = new File(dialog.getDirectory(), dialog.getFile());
//
// try {
// if (writeToFile(file)) {
//
// clearDirty();
// }
// } catch (IOException ioe) {
// JOptionPane.showMessageDialog(this, "Unable to save file: " + ioe,
// "Unable to save file",
// JOptionPane.ERROR_MESSAGE);
// }
//
// return true;
// }
// public Action getOpenAction() {
// return openTemplateAction;
// }
//
// private final AbstractAction openTemplateAction = new AbstractAction("Apply Template...") {
// private static final long serialVersionUID = 2450459627280385426L;
//
// public void actionPerformed(ActionEvent ae) {
// doApplyTemplate();
// }
// };
// public Action getSaveAction() {
// return saveAsAction;
// }
//
// public Action getSaveAsAction() {
// return saveAsAction;
// }
//
// private final AbstractAction saveAsAction = new AbstractAction("Save Template As...") {
// private static final long serialVersionUID = 2424923366448459342L;
//
// public void actionPerformed(ActionEvent ae) {
// doSaveAs();
// }
// };
public Action getImportAction() {
return importAlignmentAction;
}
protected AbstractAction importAlignmentAction = new AbstractAction("Import Data...") {
private static final long serialVersionUID = 3217702096314745005L;
public void actionPerformed(java.awt.event.ActionEvent ae) {
doImport();
}
};
public Action getImportTraitsAction() {
return importTraitsAction;
}
protected AbstractAction importTraitsAction = new AbstractAction("Import Traits") {
private static final long serialVersionUID = 3217702096314745005L;
public void actionPerformed(java.awt.event.ActionEvent ae) {
doImportTraits();
}
};
public Action getExportAction() {
return generateAction;
}
protected AbstractAction generateAction = new AbstractAction("Generate BEAST File...", gearIcon) {
private static final long serialVersionUID = -5329102618630268783L;
public void actionPerformed(java.awt.event.ActionEvent ae) {
doGenerate();
}
};
}
| lgpl-2.1 |
codice/imaging-nitf | render/src/main/java/org/codice/imaging/nitf/render/ImageMask.java | 7602 | /*
* Copyright (c) Codice Foundation
*
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or 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. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*
*/
package org.codice.imaging.nitf.render;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.stream.ImageInputStream;
import org.codice.imaging.nitf.core.image.ImageMode;
import org.codice.imaging.nitf.core.image.ImageSegment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Representation of the image mask.
*
* In NITF, there are two distinct image mask aspects - the concept that a block
* might be missing, and the concept that a pixel value might indicate "no
* data".
*
* Image masking is similar for the block, pixel and row interleve image modes.
* Image masking for band-sequential images is handled slightly differently.
*/
public final class ImageMask {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageMask.class);
private ImageSegment mImageSegment = null;
private int[][] bmrnbndm = null;
private final List<Integer> tmrnbndm = new ArrayList<>();
private int tpxcd = -1;
private static final int BLOCK_NOT_RECORDED = 0xFFFFFFFF;
/**
* Create an image mask based on reading from an image segment and associated stream.
*
* @param imageSegment the image segment
* @param imageStream the associated image stream (data)
* @throws IOException if image mask parsing fails
*/
public ImageMask(final ImageSegment imageSegment, final ImageInputStream imageStream) throws IOException {
mImageSegment = imageSegment;
readImageMask(imageStream);
}
/**
* Create an image mask based on a regular number of bytes per block.
*
* This is essentially a way to build an image mask for images that don't have one, but where the block layout is
* predictable (i.e. there is no compression).
*
* @param imageSegment the image segment that specifies the image characteristics
*/
public ImageMask(final ImageSegment imageSegment) {
mImageSegment = imageSegment;
bmrnbndm = new int[mImageSegment.getNumberOfBlocksPerRow() * mImageSegment.getNumberOfBlocksPerColumn()][mImageSegment.getNumBands()];
int numBandsToRead = 1;
if (mImageSegment.getImageMode() == ImageMode.BANDSEQUENTIAL) {
numBandsToRead = mImageSegment.getNumBands();
}
int bytesPerPixel = (int) mImageSegment.getNumberOfBytesPerBlock();
int blockCounter = 0;
for (int m = 0; m < numBandsToRead; ++m) {
for (int n = 0; n < mImageSegment.getNumberOfBlocksPerRow() * mImageSegment.getNumberOfBlocksPerColumn(); ++n) {
bmrnbndm[n][m] = bytesPerPixel * blockCounter;
blockCounter++;
}
}
}
private void readImageMask(final ImageInputStream imageInputStream) throws IOException {
int imdatoff = imageInputStream.readInt();
int bmrlnth = imageInputStream.readShort();
int tmrlnth = imageInputStream.readShort();
int tpxcdlnth = imageInputStream.readShort();
LOGGER.debug(String.format("Blocked image data offset: 0x%08x", imdatoff));
LOGGER.debug(String.format("Block mask record length: 0x%04x", bmrlnth));
LOGGER.debug(String.format("Pad Pixel Mask Record Length: 0x%04x", tmrlnth));
LOGGER.debug(String.format("Pad Output pixel code length: 0x%04x", tpxcdlnth));
if (tpxcdlnth > 0) {
tpxcd = 0;
int numBytesToRead = (tpxcdlnth + Byte.SIZE - 1) / Byte.SIZE;
LOGGER.debug("Reading TPXCD at length: {}", numBytesToRead);
int bandBits = (int) imageInputStream.readBits(numBytesToRead * Byte.SIZE);
for (int i = 0; i < mImageSegment.getNumBands(); ++i) {
tpxcd |= (bandBits << (Byte.SIZE * i));
}
LOGGER.debug(String.format("Pad Output pixel code : 0x%08x", tpxcd));
}
int numBandsToRead = 1;
if (mImageSegment.getImageMode() == ImageMode.BANDSEQUENTIAL) {
numBandsToRead = mImageSegment.getNumBands();
}
if (bmrlnth > 0) {
bmrnbndm = new int[mImageSegment.getNumberOfBlocksPerRow() * mImageSegment.getNumberOfBlocksPerColumn()][mImageSegment.getNumBands()];
for (int m = 0; m < numBandsToRead; ++m) {
for (int n = 0; n < mImageSegment.getNumberOfBlocksPerRow() * mImageSegment.getNumberOfBlocksPerColumn(); ++n) {
bmrnbndm[n][m] = imageInputStream.readInt();
LOGGER.debug(String.format("mask blocks (band %d) %d: 0x%08x", m, n, bmrnbndm[n][m]));
}
}
}
if (tmrlnth > 0) {
for (int m = 0; m < numBandsToRead; ++m) {
for (int n = 0; n < mImageSegment.getNumberOfBlocksPerRow() * mImageSegment.getNumberOfBlocksPerColumn(); ++n) {
int val = imageInputStream.readInt();
tmrnbndm.add(val);
LOGGER.debug(String.format("mask pixel (band %d) %d: 0x%08x", m, n, val));
}
}
}
}
/**
* Test if the specified block is not actually recorded in the file.
*
* This is always false if the image compression is not a masked variant.
*
* Image blocks are counted in row-major, column-minor order (e.g. if you
* have three blocks across, and two blocks down, the block numbers are 0,
* 1, 2 for the first row, and then 3, 4, 5 for the second row).
*
* @param blockNumber the block number to check for masking.
* @param bandNumber the band to check for masking (only used for Band
* Sequential).
* @return true if the block is masked (not recorded in the file), otherwise
* false.
*/
public boolean isMaskedBlock(final int blockNumber, final int bandNumber) {
if (bmrnbndm == null) {
return false;
}
if (blockNumber >= bmrnbndm.length || bandNumber >= bmrnbndm[blockNumber].length) {
return false;
}
return (BLOCK_NOT_RECORDED == bmrnbndm[blockNumber][bandNumber]);
}
/**
* Test if the specified pixel value indicates "no data".
*
* Pad pixels are typically rendered transparent, and should not be included
* in image calculations (e.g. statistics, averaging, exploitation).
*
* @param value the pixel value to test.
* @return true if this is a pad ("no data") pixel value, otherwise false.
*/
public boolean isPadPixel(final int value) {
if (tpxcd == -1) {
return false;
}
return (tpxcd == value);
}
/**
* Check whether this image mask has valid per-pixel masking.
*
* If this is false, isPadPixel() will always return false.
*
* @return true if there is valid per-pixel masking, otherwise false
*/
public boolean hasPixelMasks() {
return (tpxcd != -1);
}
}
| lgpl-2.1 |
cacheonix/cacheonix-core | 3rdparty/hibernate-3.2/test/org/hibernate/test/propertyref/inheritence/joined/Person.java | 767 | //$Id: Person.java 10921 2006-12-05 14:39:12Z steve.ebersole@jboss.com $
package org.hibernate.test.propertyref.inheritence.joined;
/**
* @author gavin
*/
public class Person {
private Long id;
private String name;
private BankAccount bankAccount;
/**
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
public BankAccount getBankAccount() {
return bankAccount;
}
public void setBankAccount(BankAccount bankAccount) {
this.bankAccount = bankAccount;
}
}
| lgpl-2.1 |
hal/core | gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/NewManagerWizard.java | 2974 | package org.jboss.as.console.client.shared.subsys.jca;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.shared.subsys.Baseadress;
import org.jboss.as.console.client.shared.subsys.jca.model.JcaWorkmanager;
import org.jboss.ballroom.client.widgets.forms.Form;
import org.jboss.ballroom.client.widgets.forms.FormValidation;
import org.jboss.ballroom.client.widgets.forms.TextBoxItem;
import org.jboss.ballroom.client.widgets.window.DialogueOptions;
import org.jboss.ballroom.client.widgets.window.WindowContentBuilder;
import org.jboss.dmr.client.ModelNode;
/**
* @author Heiko Braun
* @date 12/1/11
*/
public class NewManagerWizard {
private JcaPresenter presenter;
public NewManagerWizard(JcaPresenter jcaPresenter) {
this.presenter = jcaPresenter;
}
Widget asWidget() {
VerticalPanel layout = new VerticalPanel();
layout.setStyleName("window-content");
final Form<JcaWorkmanager> form = new Form(JcaWorkmanager.class);
TextBoxItem nameField = new TextBoxItem("name", Console.CONSTANTS.common_label_name());
form.setFields(nameField);
DialogueOptions options = new DialogueOptions(
// save
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
JcaWorkmanager manager = form.getUpdatedEntity();
FormValidation validation = form.validate();
if(validation.hasErrors())
return;
presenter.createNewManager(manager);
}
},
// cancel
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.closeDialoge();
}
}
);
// ----------------------------------------
Widget formWidget = form.asWidget();
final FormHelpPanel helpPanel = new FormHelpPanel(
new FormHelpPanel.AddressCallback() {
@Override
public ModelNode getAddress() {
ModelNode address = new ModelNode();
address.set(Baseadress.get());
address.add("subsystem", "jca");
address.add("workmanager", "*");
return address;
}
}, form
);
layout.add(helpPanel.asWidget());
layout.add(formWidget);
return new WindowContentBuilder(layout, options).build();
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringListEntity.java | 1575 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.envers.test.entities.collection;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.IndexColumn;
import org.hibernate.envers.Audited;
/**
* @author Adam Warski (adam at warski dot org)
*/
@Entity
public class StringListEntity {
@Id
@GeneratedValue
private Integer id;
@Audited
@ElementCollection
@IndexColumn(name = "list_index")
private List<String> strings;
public StringListEntity() {
strings = new ArrayList<String>();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof StringListEntity) ) {
return false;
}
StringListEntity that = (StringListEntity) o;
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
public int hashCode() {
return (id != null ? id.hashCode() : 0);
}
public String toString() {
return "SLE(id = " + id + ", strings = " + strings + ")";
}
} | lgpl-2.1 |
cytoscape/cytoscape-impl | core-task-impl/src/main/java/org/cytoscape/task/internal/utils/CoreImplDocumentationConstants.java | 2501 | package org.cytoscape.task.internal.utils;
public final class CoreImplDocumentationConstants {
/**
* See org.cytoscape.task.internal.table.AbstractTableDataTask.getNamespace(String)
*/
public static final String COLUMN_NAMESPACE_LONG_DESCRIPTION = "Node, Edge, and Network objects support the ```default```, ```local```, and ```hidden``` namespaces. Root networks also support the ```shared``` namespace. Custom namespaces may be specified by Apps.";
public static final String COLUMN_NAMESPACE_EXAMPLE_STRING = "default";
/**
* See
*
* org.cytoscape.task.internal.utils.ColumnListTunable.getColumnList(CyTable)
* org.cytoscape.task.internal.utils.ColumnValueTunable.getColumnList(CyTable)
*
*/
public static final String COLUMN_LIST_LONG_DESCRIPTION = "A list of column names, separated by commas.";
public static final String COLUMN_LIST_EXAMPLE_STRING ="name,Column B";
/**
* See org.cytoscape.task.internal.networkobjects.AbstractGetTask#getNode(CyNetwork, String)
*/
public static final String NODE_LONG_DESCRIPTION = "Selects a node by name, or, if the parameter has the prefix ```suid:```, selects a node by SUID.";
/**
* See org.cytoscape.task.internal.networkobjects.AbstractGetTask#getEdge(CyNetwork, String)
*/
public static final String EDGE_LONG_DESCRIPTION = "Selects an edge by name, or, if the parameter has the prefix ```suid:```, selects an edge by SUID.";
/**
* See org.cytoscape.task.internal.utils.DataUtils.getCSV(String)
*/
public static final String VALUE_LIST_LONG_DESCRIPTION = "A list of values separated by commas.";
/**
* See
*
* org.cytoscape.task.internal.networkobjects.GetEdgePropertiesTask.run(TaskMonitor)
* org.cytoscape.task.internal.networkobjects.GetNetworkPropertiesTask.run(TaskMonitor)
* org.cytoscape.task.internal.networkobjects.GetNodePropertiesTask.run(TaskMonitor)
* org.cytoscape.task.internal.networkobjects.SetEdgePropertiesTask.run(TaskMonitor)
* org.cytoscape.task.internal.networkobjects.SetNetworkPropertiesTask.run(TaskMonitor)
* org.cytoscape.task.internal.networkobjects.SetNodePropertiesTask.run(TaskMonitor)
*/
public static final String PROPERTY_LIST_LONG_DESCRIPTION = "A list of property names separated by commas. Refer to the 'list properties' command avalable for node, edge and network namespaces.";
/**
* Renaming is the equivalent of a set/PUT, and doesn't need to return anything.
*/
public static final String RENAME_EXAMPLE_JSON = "{}";
}
| lgpl-2.1 |
fjalvingh/domui | to.etc.domui/src/main/java/to/etc/domui/subinjector/ISubPageInjector.java | 360 | package to.etc.domui.subinjector;
import org.eclipse.jdt.annotation.NonNull;
import to.etc.domui.dom.html.SubPage;
/**
* A single thingy doing some injection task in a SubPage.
*
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on 4-12-18.
*/
public interface ISubPageInjector {
void inject(@NonNull SubPage page) throws Exception;
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/jimple/toolkits/pointer/nativemethods/NativeMethodClass.java | 1885 | package soot.jimple.toolkits.pointer.nativemethods;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* 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%
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.jimple.toolkits.pointer.representations.ReferenceVariable;
import soot.jimple.toolkits.pointer.util.NativeHelper;
public abstract class NativeMethodClass {
private static final Logger logger = LoggerFactory.getLogger(NativeMethodClass.class);
private static final boolean DEBUG = false;
protected NativeHelper helper;
public NativeMethodClass(NativeHelper helper) {
this.helper = helper;
}
/*
* If a native method has no side effect, call this method. Currently, it does nothing.
*/
public static void defaultMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar,
ReferenceVariable params[]) {
if (DEBUG) {
logger.debug("No side effects : " + method.toString());
}
}
/* To be implemented by individual classes */
public abstract void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar,
ReferenceVariable params[]);
}
| lgpl-2.1 |
kluver/lenskit | lenskit-svd/src/main/java/org/lenskit/mf/BPR/TrainingPairGenerator.java | 1524 | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2016 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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 Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.mf.BPR;
/**
* Class that operates over training events and generates batches of training
* pairs (defined as a user and a pair of items where the user has expressed
* a preference for one item over another.
*
* This interface makes no constraints over the properties of the training
* batches.
*/
public interface TrainingPairGenerator {
/**
* @return something that can be iterated over to get the next batch of training pairs.
*/
Iterable<? extends TrainingItemPair> nextBatch();
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libformula/src/main/java/org/pentaho/reporting/libraries/formula/function/information/NaFunction.java | 1986 | /*
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2006 - 2017 Hitachi Vantara and Contributors. All rights reserved.
*/
package org.pentaho.reporting.libraries.formula.function.information;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
import org.pentaho.reporting.libraries.formula.function.Function;
import org.pentaho.reporting.libraries.formula.function.ParameterCallback;
import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
/**
* This function class represents the constant error NA.
*
* @author Cedric Pronzato
*/
public class NaFunction implements Function {
private static final long serialVersionUID = 3433794709691209411L;
public NaFunction() {
}
public TypeValuePair evaluate( final FormulaContext context, final ParameterCallback parameters )
throws EvaluationException {
if ( parameters.getParameterCount() != 0 ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_ARGUMENTS_VALUE );
}
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_NA_VALUE );
}
public String getCanonicalName() {
return "NA";
}
}
| lgpl-2.1 |
kumar-physics/BioJava | biojava3-alignment/src/test/java/org/biojava3/alignment/TestDNAAlignment.java | 4385 | /**
* BioJava development code
*
* This code may be freely distributed and modified under the terms of the GNU
* Lesser General Public Licence. This should be distributed with the code. If
* you do not have a copy, see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
* Created on Oct 5, 2011
* Created by Andreas Prlic
*
* @since 3.0.2
*/
package org.biojava3.alignment;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import junit.framework.TestCase;
import org.biojava3.alignment.Alignments.PairwiseSequenceAlignerType;
import org.biojava3.alignment.template.Profile;
import org.biojava3.alignment.template.SequencePair;
import org.biojava3.alignment.template.SubstitutionMatrix;
import org.biojava3.core.sequence.DNASequence;
import org.biojava3.core.sequence.compound.AmbiguityDNACompoundSet;
import org.biojava3.core.sequence.compound.DNACompoundSet;
import org.biojava3.core.sequence.compound.NucleotideCompound;
import org.biojava3.core.sequence.io.FastaReaderHelper;
import org.biojava3.core.util.ConcurrencyTools;
public class TestDNAAlignment extends TestCase {
public void testDNAAlignment() {
try {
List<DNASequence> lst = getDNAFASTAFile();
Profile<DNASequence, NucleotideCompound> profile = Alignments.getMultipleSequenceAlignment(lst);
assertTrue(profile.getSize() == 10);
assertTrue(profile.getAlignedSequence(1).getSequenceAsString().length() > 50);
// here how to print the MSA:
//System.out.printf("MSA:%n%s%n", profile);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
ConcurrencyTools.shutdown();
}
private static List<DNASequence> getDNAFASTAFile() throws Exception {
InputStream inStream = TestDNAAlignment.class.getResourceAsStream(String.format("/dna-fasta.txt"));
LinkedHashMap<String, DNASequence> fastas = FastaReaderHelper.readFastaDNASequence(inStream);
List<DNASequence> sequences = new ArrayList<DNASequence>();
for (String key : fastas.keySet()) {
DNASequence seq = fastas.get(key);
sequences.add(seq);
}
return sequences;
}
/**
* @author brandstaetter
*/
public void testDNAMultipleAlignmentWithMixedCompoundSets() {
DNASequence target = new DNASequence("ACTGACGTGTAGCTGACTGA", DNACompoundSet.getDNACompoundSet());
DNASequence query = new DNASequence("ACTGACGTGTAGCTGACTGTA", AmbiguityDNACompoundSet.getDNACompoundSet());
List<DNASequence> lst = new ArrayList<DNASequence>();
lst.add(target);
lst.add(query);
try {
@SuppressWarnings("unused")
Profile<DNASequence, NucleotideCompound> profile = Alignments.getMultipleSequenceAlignment(lst);
fail("Alignments.getMultipleSequenceAlignment(lst) expected exception with differing compound sets");
} catch (IllegalArgumentException ex) {
// expected exception
}
}
/**
* @author brandstaetter
*/
public void testDNAPairwiseAlignmentWithMixedCompoundSets() {
DNASequence target = new DNASequence("ACTGACGTGTAGCTGACTGA", DNACompoundSet.getDNACompoundSet());
DNASequence query = new DNASequence("ACTGACGTGTAGCTGACTGT", AmbiguityDNACompoundSet.getDNACompoundSet());
SubstitutionMatrix<NucleotideCompound> matrix = SubstitutionMatrixHelper.getNuc4_4();
SimpleGapPenalty gapP = new SimpleGapPenalty();
gapP.setOpenPenalty((short) 5);
gapP.setExtensionPenalty((short) 2);
try {
@SuppressWarnings("unused")
SequencePair<DNASequence, NucleotideCompound> psa = Alignments.getPairwiseAlignment(query, target, PairwiseSequenceAlignerType.LOCAL, gapP, matrix);
fail("Alignments.getPairwiseAlignment() expected exception with differing compound sets");
} catch (IllegalArgumentException ex) {
// expected exception
}
}
}
| lgpl-2.1 |
pquiring/jfcraft | src/base/jfcraft/entity/EnderChest.java | 3225 | package jfcraft.entity;
/** Ender Chest entity
*
* @author pquiring
*/
import javaforce.gl.*;
import static javaforce.gl.GL.*;
import jfcraft.data.*;
import jfcraft.item.*;
import jfcraft.opengl.*;
public class EnderChest extends BlockEntity {
public float lidAngle;
public RenderDest dest; //can not be static since chest can be damaged
public static Model model;
//render assets
private static TextureMap texture;
protected static String textureName;
public EnderChest() {
id = Entities.ENDER_CHEST;
}
public String getName() {
return "ENDER_CHEST";
}
public RenderDest getDest() {
return dest;
}
public void init(World world) {
super.init(world);
dest = new RenderDest(parts.length);
isBlock = true;
}
public void initStatic() {
super.initStatic();
textureName = "entity/chest/ender";
model = loadModel("chest");
}
public void initStaticGL() {
super.initStaticGL();
texture = Textures.getTexture(textureName, 0);
}
public void initInstance() {
super.initInstance();
}
private static String parts[] = {"CONTAINER", "LID", "LATCH"};
public void buildBuffers(RenderDest dest, RenderData data) {
dest.resetAll();
//transfer data into dest
for(int a=0;a<parts.length;a++) {
RenderBuffers buf = dest.getBuffers(a);
Object3 obj = model.getObject(parts[a]);
buf.addVertex(obj.vpl.toArray());
buf.addPoly(obj.vil.toArray());
int cnt = obj.vpl.size();
for(int b=0;b<cnt;b++) {
buf.addDefault();
}
if (obj.maps.size() == 1) {
//latch doesn't crack
UVMap map = obj.getUVMap("normal");
buf.addTextureCoords(map.uvl.toArray());
} else {
//container & lid
UVMap map1 = obj.getUVMap("normal");
float uv1[] = map1.uvl.toArray();
if (data.crack == -1) {
buf.addTextureCoords(uv1);
} else {
UVMap map2 = obj.getUVMap("crack");
float uv2[] = map2.uvl.toArray();
buf.adjustCrack(uv2, data.crack);
buf.addTextureCoords(uv1, uv2);
}
}
buf.org = obj.org;
buf.type = obj.type;
}
}
public void bindTexture() {
texture.bind();
}
public void copyBuffers() {
dest.copyBuffers();
}
public void setMatrixModel(int bodyPart, RenderBuffers buf) {
mat.setIdentity();
mat.addRotate(-ang.y, 0, 1, 0);
switch (bodyPart) {
case 0: //container
break;
case 1: //lid
case 2: //lock
mat.addTranslate2(buf.org.x, buf.org.y, buf.org.z);
mat.addRotate2(lidAngle, 1, 0, 0);
mat.addTranslate2(-buf.org.x, -buf.org.y, -buf.org.z);
break;
}
mat.addTranslate(pos.x, pos.y, pos.z);
if (scale != 1.0f) {
mat.addScale(scale, scale, scale);
}
glUniformMatrix4fv(Static.uniformMatrixModel, 1, GL_FALSE, mat.m); //model matrix
}
public void render() {
for(int a=0;a<dest.count();a++) {
RenderBuffers buf = dest.getBuffers(a);
setMatrixModel(a, buf);
buf.bindBuffers();
buf.render();
}
glUniformMatrix4fv(Static.uniformMatrixModel, 1, GL_FALSE, Static.identity.m); //model matrix
}
}
| lgpl-2.1 |
geotools/geotools | modules/unsupported/swt/src/main/java/org/geotools/swt/tool/AbstractZoomTool.java | 2295 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.swt.tool;
import org.eclipse.swt.SWT;
/**
* Abstract base class for the zoom-in and zoom-out tools. Provides getter / setter methods for the
* zoom increment.
*
* @author Michael Bedward
* @since 2.6
*/
public abstract class AbstractZoomTool extends CursorTool {
/** The default zoom increment */
public static final double DEFAULT_ZOOM_FACTOR = 1.5;
/** The working zoom increment */
protected double zoom;
/**
* Constructs a new abstract zoom tool. To activate the tool only on certain mouse events
* provide a single mask, e.g. {@link SWT#BUTTON1}, or a combination of multiple SWT-masks.
*
* @param triggerButtonMask Mouse button which triggers the tool's activation or {@value
* #ANY_BUTTON} if the tool is to be triggered by any button
*/
public AbstractZoomTool(int triggerButtonMask) {
super(triggerButtonMask);
setZoom(DEFAULT_ZOOM_FACTOR);
}
/** Constructs a new abstract zoom tool which is triggered by any mouse button. */
public AbstractZoomTool() {
this(CursorTool.ANY_BUTTON);
}
/**
* Get the current areal zoom increment.
*
* @return the current zoom increment as a double
*/
public double getZoom() {
return zoom;
}
/**
* Set the zoom increment
*
* @param newZoom the new zoom increment; values <= 1.0 will be ignored
* @return the previous zoom increment
*/
public double setZoom(double newZoom) {
double old = zoom;
if (newZoom > 1.0d) {
zoom = newZoom;
}
return old;
}
}
| lgpl-2.1 |
VitosPchela/xpst | xPSTLib/src/org/clearsighted/tutorbase/emscript/exprtree/CondNode.java | 1454 | /*
Copyright (c) Clearsighted 2006-08 stephen@clearsighted.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.clearsighted.tutorbase.emscript.exprtree;
import java.util.HashMap;
import org.clearsighted.tutorengine.GoalNode;
import org.clearsighted.tutorengine.types.Operations;
import org.clearsighted.tutorengine.types.Operations.Op;
public class CondNode extends ExprNode
{
private Op type;
public CondNode(Op type, ExprNode l, ExprNode r)
{
this.type = type;
this.leftChild = l;
this.rightChild = r;
}
@Override
public Object eval(ExprEnv ee,HashMap<String, GoalNode> gns) throws ExprException
{
Object lev = leftChild.eval(ee,gns), rev = rightChild.eval(ee,gns);
return Operations.doOp(type, lev, rev,gns);
}
}
| lgpl-2.1 |
amikryukov/jagger | webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/Trends.java | 53305 | package com.griddynamics.jagger.webclient.client.trends;
import ca.nanometrics.gflot.client.*;
import ca.nanometrics.gflot.client.options.*;
import ca.nanometrics.gflot.client.options.Range;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.*;
import com.griddynamics.jagger.webclient.client.*;
import com.griddynamics.jagger.webclient.client.components.MetricPanel;
import com.griddynamics.jagger.webclient.client.components.SessionPlotPanel;
import com.griddynamics.jagger.webclient.client.components.SummaryPanel;
import com.griddynamics.jagger.webclient.client.data.*;
import com.griddynamics.jagger.webclient.client.dto.*;
import com.griddynamics.jagger.webclient.client.handler.ShowCurrentValueHoverListener;
import com.griddynamics.jagger.webclient.client.handler.ShowTaskDetailsListener;
import com.griddynamics.jagger.webclient.client.mvp.JaggerPlaceHistoryMapper;
import com.griddynamics.jagger.webclient.client.mvp.NameTokens;
import com.griddynamics.jagger.webclient.client.resources.JaggerResources;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import java.util.*;
/**
* @author "Artem Kirillov" (akirillov@griddynamics.com)
* @since 5/28/12
*/
public class Trends extends DefaultActivity {
interface TrendsUiBinder extends UiBinder<Widget, Trends> {
}
private static TrendsUiBinder uiBinder = GWT.create(TrendsUiBinder.class);
private static final int MAX_PLOT_COUNT = 30;
@UiField
TabLayoutPanel mainTabPanel;
@UiField
HTMLPanel plotPanel;
@UiField(provided = true)
DataGrid<SessionDataDto> sessionsDataGrid;
@UiField(provided = true)
CellTable<TaskDataDto> testDataGrid;
@UiField(provided = true)
SimplePager sessionsPager;
@UiField(provided = true)
CellTree taskDetailsTree;
@UiField
MetricPanel metricPanel;
@UiField
ScrollPanel scrollPanelTrends;
@UiField
ScrollPanel scrollPanelMetrics;
@UiField
HTMLPanel plotTrendsPanel;
@UiField
SummaryPanel summaryPanel;
@UiField
VerticalPanel sessionScopePlotList;
SessionPlotPanel sessionPlotPanel;
@UiField
TextBox sessionIdsTextBox;
private Timer stopTypingSessionIdsTimer;
@UiField
DateBox sessionsFrom;
@UiField
DateBox sessionsTo;
@UiField
Panel trendsDetails;
@UiField
SplitLayoutPanel settingsPanel;
@UiField
DeckPanel testsMetricsPanel;
@UiHandler("uncheckSessionsButton")
void handleUncheckSessionsButtonClick(ClickEvent e) {
MultiSelectionModel model = (MultiSelectionModel<?>) sessionsDataGrid.getSelectionModel();
model.clear();
}
@UiHandler("showCheckedSessionsButton")
void handleShowCheckedSessionsButtonClick(ClickEvent e) {
Set<SessionDataDto> sessionDataDtoSet = ((MultiSelectionModel<SessionDataDto>) sessionsDataGrid.getSelectionModel()).getSelectedSet();
filterSessions(sessionDataDtoSet);
}
@UiHandler("clearSessionFiltersButton")
void handleClearSessionFiltersButtonClick(ClickEvent e) {
sessionsTo.setValue(null, true);
sessionsFrom.setValue(null, true);
sessionIdsTextBox.setText(null);
stopTypingSessionIdsTimer.schedule(10);
}
@UiHandler("getHyperlink")
void getHyperlink(ClickEvent event){
MultiSelectionModel<SessionDataDto> sessionModel = (MultiSelectionModel)sessionsDataGrid.getSelectionModel();
MultiSelectionModel<TaskDataDto> testModel = (MultiSelectionModel)testDataGrid.getSelectionModel();
Set<SessionDataDto> sessions = sessionModel.getSelectedSet();
Set<TaskDataDto> tests = testModel.getSelectedSet();
Set<MetricNameDto> metrics = metricPanel.getSelected();
TaskDataTreeViewModel taskDataTreeViewModel = (TaskDataTreeViewModel) taskDetailsTree.getTreeViewModel();
Set<PlotNameDto> trends = taskDataTreeViewModel.getSelectionModel().getSelectedSet();
HashSet<String> sessionsIds = new HashSet<String>();
HashSet<TestsMetrics> testsMetricses = new HashSet<TestsMetrics>(tests.size());
HashMap<String, TestsMetrics> map = new HashMap<String, TestsMetrics>(tests.size());
for (SessionDataDto session : sessions){
sessionsIds.add(session.getSessionId());
}
for (TaskDataDto taskDataDto : tests){
TestsMetrics testsMetrics = new TestsMetrics(taskDataDto.getTaskName(), new HashSet<String>(), new HashSet<String>());
testsMetricses.add(testsMetrics);
map.put(taskDataDto.getTaskName(), testsMetrics);
}
for (MetricNameDto metricNameDto : metrics){
map.get(metricNameDto.getTests().getTaskName()).getMetrics().add(metricNameDto.getName());
}
for (PlotNameDto plotNameDto : trends){
map.get(plotNameDto.getTest().getTaskName()).getTrends().add(plotNameDto.getPlotName());
}
TrendsPlace newPlace = new TrendsPlace(
mainTabPanel.getSelectedIndex() == 0 ? NameTokens.SUMMARY :
mainTabPanel.getSelectedIndex() == 1 ? NameTokens.TRENDS : NameTokens.METRICS
);
newPlace.setSelectedSessionIds(sessionsIds);
newPlace.setSelectedTestsMetrics(testsMetricses);
newPlace.setSessionTrends(sessionPlotPanel.getSelected());
String linkText = Window.Location.getHost()+Window.Location.getQueryString()+"/#"+new JaggerPlaceHistoryMapper().getToken(newPlace);
linkText = URL.encode(linkText);
//create a dialog for copy link
final DialogBox dialog = new DialogBox(false, true);
dialog.setText("Share link");
dialog.setModal(true);
dialog.setAutoHideEnabled(true);
dialog.setPopupPosition(event.getClientX(), event.getClientY());
final TextArea textArea = new TextArea();
textArea.setText(linkText);
textArea.setWidth("300px");
textArea.setHeight("40px");
//select text
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
textArea.setVisible(true);
textArea.setFocus(true);
textArea.selectAll();
}
});
dialog.add(textArea);
dialog.show();
}
private final Map<String, Set<MarkingDto>> markingsMap = new HashMap<String, Set<MarkingDto>>();
private FlowPanel loadIndicator;
private final SessionDataAsyncDataProvider sessionDataProvider = new SessionDataAsyncDataProvider();
private final SessionDataForSessionIdsAsyncProvider sessionDataForSessionIdsAsyncProvider = new SessionDataForSessionIdsAsyncProvider();
private final SessionDataForDatePeriodAsyncProvider sessionDataForDatePeriodAsyncProvider = new SessionDataForDatePeriodAsyncProvider();
@UiField
Widget widget;
public Trends(JaggerResources resources) {
super(resources);
createWidget();
}
private TrendsPlace place;
private boolean selectTests = false;
// cash for chosen metric spike for jfg-418
MetricFullData chosenMetrics = new MetricFullData();
//tells if trends plot should be redraw
private boolean hasChanged = false;
public void updatePlace(TrendsPlace place){
if (this.place != null)
return;
this.place = place;
final TrendsPlace finalPlace = this.place;
if (place.getSelectedSessionIds().isEmpty()){
sessionsDataGrid.getSelectionModel().addSelectionChangeHandler(new SessionSelectChangeHandler());
selectTests = true;
testDataGrid.getSelectionModel().addSelectionChangeHandler(new TestSelectChangeHandler());
TaskDataTreeViewModel viewModel = (TaskDataTreeViewModel)taskDetailsTree.getTreeViewModel();
viewModel.getSelectionModel().addSelectionChangeHandler(new TaskPlotSelectionChangedHandler());
metricPanel.addSelectionListener(new MetricsSelectionChangedHandler());
chooseTab(place.getToken());
return;
}
SessionDataService.Async.getInstance().getBySessionIds(0, place.getSelectedSessionIds().size(), place.getSelectedSessionIds(), new AsyncCallback<PagedSessionDataDto>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(PagedSessionDataDto result) {
for (SessionDataDto session : result.getSessionDataDtoList()){
sessionsDataGrid.getSelectionModel().setSelected(session, true);
}
sessionsDataGrid.getSelectionModel().addSelectionChangeHandler(new SessionSelectChangeHandler());
sessionsDataGrid.getSelectionModel().setSelected(result.getSessionDataDtoList().iterator().next(), true);
chooseTab(finalPlace.getToken());
}
});
History.newItem(NameTokens.EMPTY);
}
private void filterSessions(Set<SessionDataDto> sessionDataDtoSet) {
if (sessionDataDtoSet == null || sessionDataDtoSet.isEmpty()) {
sessionIdsTextBox.setText(null);
stopTypingSessionIdsTimer.schedule(10);
return;
}
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (SessionDataDto sessionDataDto : sessionDataDtoSet) {
if (!first) {
builder.append("/");
}
builder.append(sessionDataDto.getSessionId());
first = false;
}
sessionIdsTextBox.setText(builder.toString());
stopTypingSessionIdsTimer.schedule(10);
}
@Override
protected Widget initializeWidget() {
return widget;
}
private void createWidget() {
setupTestDataGrid();
setupSessionDataGrid();
setupTestDetailsTree();
setupPager();
setupLoadIndicator();
uiBinder.createAndBindUi(this);
setupTabPanel();
setupSessionNumberTextBox();
setupSessionsDateRange();
setupSettingsPanel();
}
/**
* Field to hold number of sessions that were chosen.
* spike for rendering metrics plots
*/
private ArrayList<Long> chosenSessions = new ArrayList<Long>();
private SimplePlot createPlot(final String id, Markings markings, String xAxisLabel, double yMinimum, boolean isMetric) {
PlotOptions plotOptions = new PlotOptions();
plotOptions.setZoomOptions(new ZoomOptions().setAmount(1.02));
plotOptions.setGlobalSeriesOptions(new GlobalSeriesOptions()
.setLineSeriesOptions(new LineSeriesOptions().setLineWidth(1).setShow(true).setFill(0.1))
.setPointsOptions(new PointsSeriesOptions().setRadius(1).setShow(true)).setShadowSize(0d));
plotOptions.setPanOptions(new PanOptions().setInteractive(true));
if (isMetric) {
plotOptions.addXAxisOptions(new AxisOptions().setZoomRange(true).setTickDecimals(0)
.setTickFormatter(new TickFormatter() {
@Override
public String formatTickValue(double tickValue, Axis axis) {
if (tickValue >= 0 && tickValue < chosenSessions.size())
return String.valueOf(chosenSessions.get((int) tickValue));
else
return "";
}
}));
} else {
plotOptions.addXAxisOptions(new AxisOptions().setZoomRange(true).setMinimum(0));
}
plotOptions.addYAxisOptions(new AxisOptions().setZoomRange(false).setMinimum(yMinimum));
plotOptions.setLegendOptions(new LegendOptions().setNumOfColumns(2));
if (markings == null) {
// Make the grid hoverable
plotOptions.setGridOptions(new GridOptions().setHoverable(true));
} else {
// Make the grid hoverable and add markings
plotOptions.setGridOptions(new GridOptions().setHoverable(true).setMarkings(markings).setClickable(true));
}
// create the plot
SimplePlot plot = new SimplePlot(plotOptions);
plot.setHeight(200);
plot.setWidth("100%");
final PopupPanel popup = new PopupPanel();
popup.addStyleName(getResources().css().infoPanel());
final HTML popupPanelContent = new HTML();
popup.add(popupPanelContent);
// add hover listener
if (isMetric) {
plot.addHoverListener(new ShowCurrentValueHoverListener(popup, popupPanelContent, xAxisLabel, chosenSessions), false);
} else {
plot.addHoverListener(new ShowCurrentValueHoverListener(popup, popupPanelContent, xAxisLabel, null), false);
}
if (!isMetric && markings != null && markingsMap != null && !markingsMap.isEmpty()) {
final PopupPanel taskInfoPanel = new PopupPanel();
taskInfoPanel.setWidth("200px");
taskInfoPanel.addStyleName(getResources().css().infoPanel());
final HTML taskInfoPanelContent = new HTML();
taskInfoPanel.add(taskInfoPanelContent);
taskInfoPanel.setAutoHideEnabled(true);
plot.addClickListener(new ShowTaskDetailsListener(id, markingsMap, taskInfoPanel, 200, taskInfoPanelContent), false);
}
return plot;
}
private void setupSettingsPanel(){
SplitLayoutPanel root = (SplitLayoutPanel) widget;
root.setWidgetToggleDisplayAllowed(settingsPanel, true);
testsMetricsPanel.showWidget(0);
sessionPlotPanel = new SessionPlotPanel(new SessionScopePlotCheckBoxClickHandler(), plotPanel);
sessionScopePlotList.add(sessionPlotPanel);
}
private void setupTabPanel(){
mainTabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
int selected = event.getSelectedItem();
switch (selected) {
case 0: onSummaryTabSelected();
break;
case 1: onTrendsTabSelected();
break;
case 2: onMetricsTabSelected();
default:
}
}
});
}
private void onSummaryTabSelected() {
testsMetricsPanel.showWidget(0);
if (summaryPanel.getSessionComparisonPanel() != null) {
if (chosenMetrics.getRecordList().isEmpty()) {
summaryPanel.getSessionComparisonPanel().getGrid().setData(
summaryPanel.getSessionComparisonPanel().getEmptyListGrid()
);
} else {
summaryPanel.getSessionComparisonPanel().getGrid().setData(
chosenMetrics.getRecordList()
);
}
}
}
private void onTrendsTabSelected() {
testsMetricsPanel.showWidget(0);
mainTabPanel.forceLayout();
if (!chosenMetrics.getMetrics().isEmpty() && hasChanged) {
plotTrendsPanel.clear();
for(Map.Entry<String, MetricDto> entry : chosenMetrics.getMetrics().entrySet()) {
renderPlots(
plotTrendsPanel,
Arrays.asList(entry.getValue().getPlotSeriesDto()),
entry.getKey(),
entry.getValue().getPlotSeriesDto().getYAxisMin(),
true
);
}
scrollPanelTrends.scrollToBottom();
hasChanged = false;
}
}
private void onMetricsTabSelected() {
testsMetricsPanel.showWidget(1);
}
private void chooseTab(String token) {
if (NameTokens.SUMMARY.equals(token)) {
mainTabPanel.selectTab(0);
} else if (NameTokens.TRENDS.equals(token)) {
mainTabPanel.selectTab(1);
} else {
mainTabPanel.selectTab(2);
}
}
private void setupSessionDataGrid() {
sessionsDataGrid = new DataGrid<SessionDataDto>();
sessionsDataGrid.setPageSize(15);
sessionsDataGrid.setEmptyTableWidget(new Label("No Sessions"));
// Add a selection model so we can select cells.
final SelectionModel<SessionDataDto> selectionModel = new MultiSelectionModel<SessionDataDto>(new ProvidesKey<SessionDataDto>() {
@Override
public Object getKey(SessionDataDto item) {
return item.getSessionId();
}
});
sessionsDataGrid.setSelectionModel(selectionModel, DefaultSelectionEventManager.<SessionDataDto>createCheckboxManager());
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call dataGrid.setSelectionEnabled(true) to enable mouse selection.
Column<SessionDataDto, Boolean> checkColumn =
new Column<SessionDataDto, Boolean>(new CheckboxCell(true, false)) {
@Override
public Boolean getValue(SessionDataDto object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
sessionsDataGrid.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
sessionsDataGrid.setColumnWidth(checkColumn, 40, Style.Unit.PX);
sessionsDataGrid.addColumn(new TextColumn<SessionDataDto>() {
@Override
public String getValue(SessionDataDto object) {
return object.getName();
}
}, "Name");
sessionsDataGrid.addColumn(new TextColumn<SessionDataDto>() {
@Override
public String getValue(SessionDataDto object) {
return object.getStartDate();
}
}, "Start Date");
sessionsDataGrid.addColumn(new TextColumn<SessionDataDto>() {
@Override
public String getValue(SessionDataDto object) {
return object.getEndDate();
}
}, "End Date");
sessionDataProvider.addDataDisplay(sessionsDataGrid);
}
private void setupTestDataGrid(){
testDataGrid = new CellTable<TaskDataDto>();
testDataGrid.setWidth("500px");
testDataGrid.setEmptyTableWidget(new Label("No Tests"));
// Add a selection model so we can select cells.
final SelectionModel<TaskDataDto> selectionModel = new MultiSelectionModel<TaskDataDto>(new ProvidesKey<TaskDataDto>() {
@Override
public Object getKey(TaskDataDto item) {
return item.getTaskName();
}
});
testDataGrid.setSelectionModel(selectionModel, DefaultSelectionEventManager.<TaskDataDto>createCheckboxManager());
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call dataGrid.setSelectionEnabled(true) to enable mouse selection.
Column<TaskDataDto, Boolean> checkColumn =
new Column<TaskDataDto, Boolean>(new CheckboxCell(true, false)) {
@Override
public Boolean getValue(TaskDataDto object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
testDataGrid.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
testDataGrid.setColumnWidth(checkColumn, 40, Style.Unit.PX);
testDataGrid.addColumn(new TextColumn<TaskDataDto>() {
@Override
public String getValue(TaskDataDto object) {
return object.getTaskName();
}
}, "Tests");
testDataGrid.setRowData(Collections.EMPTY_LIST);
}
private void setupPager() {
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
sessionsPager = new SimplePager(SimplePager.TextLocation.CENTER, pagerResources, false, 0, true);
sessionsPager.setDisplay(sessionsDataGrid);
}
private void setupTestDetailsTree() {
CellTree.Resources res = GWT.create(CellTree.BasicResources.class);
final MultiSelectionModel<PlotNameDto> selectionModel = new MultiSelectionModel<PlotNameDto>();
taskDetailsTree = new CellTree(new TaskDataTreeViewModel(selectionModel, getResources()), null, res);
taskDetailsTree.addStyleName(getResources().css().taskDetailsTree());
}
private void setupLoadIndicator() {
ImageResource imageResource = getResources().getLoadIndicator();
Image image = new Image(imageResource);
loadIndicator = new FlowPanel();
loadIndicator.addStyleName(getResources().css().centered());
loadIndicator.add(image);
}
private void setupSessionNumberTextBox() {
stopTypingSessionIdsTimer = new Timer() {
@Override
public void run() {
final String currentContent = sessionIdsTextBox.getText().trim();
// If session ID text box is empty then load all sessions
if (currentContent == null || currentContent.isEmpty()) {
sessionDataProvider.addDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForSessionIdsAsyncProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
return;
}
Set<String> sessionIds = new HashSet<String>();
if (currentContent.contains(",") || currentContent.contains(";") || currentContent.contains("/")) {
sessionIds.addAll(Arrays.asList(currentContent.split("\\s*[,;/]\\s*")));
} else {
sessionIds.add(currentContent);
}
sessionDataForSessionIdsAsyncProvider.setSessionIds(sessionIds);
sessionDataProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForDatePeriodAsyncProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForSessionIdsAsyncProvider.addDataDisplayIfNotExists(sessionsDataGrid);
}
};
sessionIdsTextBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
sessionsFrom.setValue(null);
sessionsTo.setValue(null);
stopTypingSessionIdsTimer.schedule(500);
}
});
}
private void setupSessionsDateRange() {
DateTimeFormat format = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.YEAR_MONTH_NUM_DAY);
sessionsFrom.setFormat(new DateBox.DefaultFormat(format));
sessionsTo.setFormat(new DateBox.DefaultFormat(format));
sessionsFrom.getTextBox().addValueChangeHandler(new EmptyDateBoxValueChangePropagator(sessionsFrom));
sessionsTo.getTextBox().addValueChangeHandler(new EmptyDateBoxValueChangePropagator(sessionsTo));
final ValueChangeHandler<Date> valueChangeHandler = new ValueChangeHandler<Date>() {
@Override
public void onValueChange(ValueChangeEvent<Date> dateValueChangeEvent) {
sessionIdsTextBox.setValue(null);
Date fromDate = sessionsFrom.getValue();
Date toDate = sessionsTo.getValue();
if (fromDate == null || toDate == null) {
sessionDataProvider.addDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForDatePeriodAsyncProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
return;
}
sessionDataForDatePeriodAsyncProvider.setDateRange(fromDate, toDate);
sessionDataProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForSessionIdsAsyncProvider.removeDataDisplayIfNotExists(sessionsDataGrid);
sessionDataForDatePeriodAsyncProvider.addDataDisplayIfNotExists(sessionsDataGrid);
}
};
sessionsTo.addValueChangeHandler(valueChangeHandler);
sessionsFrom.addValueChangeHandler(valueChangeHandler);
}
private boolean isMaxPlotCountReached() {
return plotPanel.getWidgetCount() >= MAX_PLOT_COUNT;
}
private void renderPlots(HTMLPanel panel, List<PlotSeriesDto> plotSeriesDtoList, String id) {
renderPlots(panel, plotSeriesDtoList, id, 0, false);
}
private void renderPlots(HTMLPanel panel, List<PlotSeriesDto> plotSeriesDtoList, String id, double yMinimum, boolean isMetric) {
panel.add(loadIndicator);
SimplePlot redrawingPlot = null;
VerticalPanel plotGroupPanel = new VerticalPanel();
plotGroupPanel.setWidth("100%");
plotGroupPanel.getElement().setId(id);
for (PlotSeriesDto plotSeriesDto : plotSeriesDtoList) {
Markings markings = null;
if (plotSeriesDto.getMarkingSeries() != null) {
markings = new Markings();
for (MarkingDto plotDatasetDto : plotSeriesDto.getMarkingSeries()) {
double x = plotDatasetDto.getValue();
markings.addMarking(new Marking().setX(new Range(x, x)).setLineWidth(1).setColor(plotDatasetDto.getColor()));
}
markingsMap.put(id, new TreeSet<MarkingDto>(plotSeriesDto.getMarkingSeries()));
}
final SimplePlot plot = createPlot(id, markings, plotSeriesDto.getXAxisLabel(), yMinimum, isMetric);
redrawingPlot = plot;
PlotModel plotModel = plot.getModel();
for (PlotDatasetDto plotDatasetDto : plotSeriesDto.getPlotSeries()) {
SeriesHandler handler = plotModel.addSeries(plotDatasetDto.getLegend(), plotDatasetDto.getColor());
// Populate plot with data
for (PointDto pointDto : plotDatasetDto.getPlotData()) {
handler.add(new DataPoint(pointDto.getX(), pointDto.getY()));
}
}
// Add X axis label
Label xLabel = new Label(plotSeriesDto.getXAxisLabel());
xLabel.addStyleName(getResources().css().xAxisLabel());
Label plotHeader = new Label(plotSeriesDto.getPlotHeader());
plotHeader.addStyleName(getResources().css().plotHeader());
Label plotLegend = new Label("PLOT LEGEND");
plotLegend.addStyleName(getResources().css().plotLegend());
VerticalPanel vp = new VerticalPanel();
vp.setWidth("100%");
Label panLeftLabel = new Label();
panLeftLabel.addStyleName(getResources().css().panLabel());
panLeftLabel.getElement().appendChild(new Image(getResources().getArrowLeft()).getElement());
panLeftLabel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
plot.pan(new Pan().setLeft(-100));
}
});
Label panRightLabel = new Label();
panRightLabel.addStyleName(getResources().css().panLabel());
panRightLabel.getElement().appendChild(new Image(getResources().getArrowRight()).getElement());
panRightLabel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
plot.pan(new Pan().setLeft(100));
}
});
Label zoomInLabel = new Label("Zoom In");
zoomInLabel.addStyleName(getResources().css().zoomLabel());
zoomInLabel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
plot.zoom();
}
});
Label zoomOutLabel = new Label("Zoom Out");
zoomOutLabel.addStyleName(getResources().css().zoomLabel());
zoomOutLabel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
plot.zoomOut();
}
});
FlowPanel zoomPanel = new FlowPanel();
zoomPanel.addStyleName(getResources().css().zoomPanel());
zoomPanel.add(panLeftLabel);
zoomPanel.add(panRightLabel);
zoomPanel.add(zoomInLabel);
zoomPanel.add(zoomOutLabel);
vp.add(plotHeader);
vp.add(zoomPanel);
vp.add(plot);
vp.add(xLabel);
// Will be added if there is need it
//vp.add(plotLegend);
plotGroupPanel.add(vp);
}
int loadingId = panel.getWidgetCount() - 1;
panel.remove(loadingId);
panel.add(plotGroupPanel);
// Redraw plot
if (redrawingPlot != null) {
redrawingPlot.redraw();
}
}
//=================================//
//==========Nested Classes=========//
//=================================//
/**
* Handles select session event
*/
private class TestSelectChangeHandler implements SelectionChangeEvent.Handler{
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Set<TaskDataDto> selected = ((MultiSelectionModel<TaskDataDto>) event.getSource()).getSelectedSet();
Set<SessionDataDto> selectedSessions = ((MultiSelectionModel<SessionDataDto>)sessionsDataGrid.getSelectionModel()).getSelectedSet();
List<TaskDataDto> result = new ArrayList<TaskDataDto>(selected.size());
result.addAll(selected);
TaskDataTreeViewModel taskDataTreeViewModel = (TaskDataTreeViewModel) taskDetailsTree.getTreeViewModel();
MultiSelectionModel<PlotNameDto> plotNameSelectionModel = taskDataTreeViewModel.getSelectionModel();
// Clear plots display
plotPanel.clear();
plotTrendsPanel.clear();
chosenMetrics.clear();
// Clear task scope plot selection model
plotNameSelectionModel.clear();
// Clear session scope plot list
sessionPlotPanel.clearPlots();
// Clear markings dto map
markingsMap.clear();
taskDataTreeViewModel.clear();
taskDataTreeViewModel.populateTaskList(result);
// Populate available plots tree level for each task for selected session
for (TaskDataDto taskDataDto : result) {
taskDataTreeViewModel.getPlotNameDataProviders().put
(taskDataDto, new TaskPlotNamesAsyncDataProvider(taskDataDto, summaryPanel.getSessionIds()));
}
summaryPanel.updateTests(selected);
metricPanel.updateTests(selected);
if (!selectTests){
selectTests = true;
Set<MetricNameDto> metricsToSelect = new HashSet<MetricNameDto>();
Set<PlotNameDto> trendsToSelect = new HashSet<PlotNameDto>();
for (TaskDataDto taskDataDto : result){
for (TestsMetrics testMetric : place.getSelectedTestsMetrics()){
if (testMetric.getTestName().equals(taskDataDto.getTaskName())){
//add metrics
for (String metricName : testMetric.getMetrics()){
MetricNameDto meticDto = new MetricNameDto();
meticDto.setName(metricName);
meticDto.setTests(taskDataDto);
metricsToSelect.add(meticDto);
}
//add plots
for (String trendsName : testMetric.getTrends()){
PlotNameDto plotNameDto = new PlotNameDto(taskDataDto, trendsName);
trendsToSelect.add(plotNameDto);
}
}
}
}
MetricNameDto fireMetric = null;
if (!metricsToSelect.isEmpty())
fireMetric = metricsToSelect.iterator().next();
for (MetricNameDto metric : metricsToSelect){
metricPanel.setSelected(metric);
}
metricPanel.addSelectionListener(new MetricsSelectionChangedHandler());
if (fireMetric != null)
metricPanel.setSelected(fireMetric);
PlotNameDto firePlot = null;
if (!trendsToSelect.isEmpty())
firePlot = trendsToSelect.iterator().next();
for (PlotNameDto plotNameDto : trendsToSelect){
taskDataTreeViewModel.getSelectionModel().setSelected(plotNameDto, true);
}
taskDataTreeViewModel.getSelectionModel().addSelectionChangeHandler(new TaskPlotSelectionChangedHandler());
if (firePlot != null)
taskDataTreeViewModel.getSelectionModel().setSelected(firePlot, true);
}else{
if (selectedSessions.size() == 1){
final SessionDataDto session = selectedSessions.iterator().next();
PlotProviderService.Async.getInstance().getSessionScopePlotList(session.getSessionId(),new AsyncCallback<Set<String>>() {
@Override
public void onFailure(Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onSuccess(Set<String> strings) {
sessionPlotPanel.update(session.getSessionId(), strings);
}
});
}
}
}
}
private class SessionSelectChangeHandler implements SelectionChangeEvent.Handler {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
// Currently selection model for sessions is a single selection model
Set<SessionDataDto> selected = ((MultiSelectionModel<SessionDataDto>) event.getSource()).getSelectedSet();
TaskDataTreeViewModel taskDataTreeViewModel = (TaskDataTreeViewModel) taskDetailsTree.getTreeViewModel();
MultiSelectionModel<PlotNameDto> plotNameSelectionModel = taskDataTreeViewModel.getSelectionModel();
//Refresh summary
summaryPanel.updateSessions(selected);
// Clear plots display
plotPanel.clear();
plotTrendsPanel.clear();
chosenMetrics.clear();
// Clear task scope plot selection model
plotNameSelectionModel.clear();
//clearPlots session plots
sessionPlotPanel.clearPlots();
// Clear markings dto map
markingsMap.clear();
taskDataTreeViewModel.clear();
metricPanel.updateTests(Collections.EMPTY_SET);
testDataGrid.setRowData(Collections.EMPTY_LIST);
if (selected.size() == 1) {
// If selected single session clearPlots plot display, clearPlots plot selection and fetch all data for given session
final String sessionId = selected.iterator().next().getSessionId();
// Populate task scope session list
TaskDataService.Async.getInstance().getTaskDataForSession(sessionId, new AsyncCallback<List<TaskDataDto>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(List<TaskDataDto> result) {
updateTests(result);
}
});
} else if (selected.size() > 1) {
// If selected several sessions
chosenSessions.clear();
final Set<String> sessionIds = new HashSet<String>();
for (SessionDataDto sessionDataDto : selected) {
sessionIds.add(sessionDataDto.getSessionId());
chosenSessions.add(Long.valueOf(sessionDataDto.getSessionId()));
Collections.sort(chosenSessions);
}
TaskDataService.Async.getInstance().getTaskDataForSessions(sessionIds, new AsyncCallback<List<TaskDataDto>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(List<TaskDataDto> result) {
updateTests(result);
}
});
}
}
}
private void updateTests(List<TaskDataDto> tests){
Set<SessionDataDto> selected = ((MultiSelectionModel<SessionDataDto>) sessionsDataGrid.getSelectionModel()).getSelectedSet();
if (selected.size() == 1){
final String sessionId = selected.iterator().next().getSessionId();
if (!selectTests){
PlotProviderService.Async.getInstance().getSessionScopePlotList(sessionId,
new AsyncCallback<Set<String>>() {
@Override
public void onFailure(Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onSuccess(Set<String> strings) {
sessionPlotPanel.update(sessionId, strings);
sessionPlotPanel.setSelected(place.getSessionTrends());
}
});
}else{
PlotProviderService.Async.getInstance().getSessionScopePlotList(sessionId,new AsyncCallback<Set<String>>() {
@Override
public void onFailure(Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onSuccess(Set<String> strings) {
sessionPlotPanel.update(sessionId, strings);
}
});
}
}
if (tests.isEmpty()) {
return;
}
MultiSelectionModel model = (MultiSelectionModel)testDataGrid.getSelectionModel();
model.clear();
testDataGrid.redraw();
testDataGrid.setRowData(tests);
if (!selectTests){
TaskDataDto selectObject = null;
Set<TestsMetrics> testsMetrics = place.getSelectedTestsMetrics();
for (TaskDataDto taskDataDto : tests){
for (TestsMetrics testMetric : testsMetrics){
if (testMetric.getTestName().equals(taskDataDto.getTaskName())){
if (selectObject == null) selectObject = taskDataDto;
model.setSelected(taskDataDto, true);
}
}
}
model.addSelectionChangeHandler(new TestSelectChangeHandler());
//fire event
if (selectObject != null){
model.setSelected(selectObject, true);
}else{
//nothing to select
selectTests = true;
}
}
}
/**
* Handles metrics change
*/
private class MetricsSelectionChangedHandler extends PlotsServingBase implements SelectionChangeEvent.Handler {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
hasChanged = true;
if (summaryPanel.getSessionComparisonPanel() == null) {
plotTrendsPanel.clear();
chosenMetrics.clear();
return;
}
Set<MetricNameDto> metrics = metricPanel.getSelected();
final ListGridRecord[] emptyData = summaryPanel.getSessionComparisonPanel().getEmptyListGrid();
if (metrics.isEmpty()) {
// Remove plots from display which were unchecked
chosenMetrics.clear();
plotTrendsPanel.clear();
if (mainTabPanel.getSelectedIndex() == 0) {
onSummaryTabSelected();
}
} else {
//Generate all id of plots which should be displayed
Set<String> selectedMetricsIds = new HashSet<String>();
for (MetricNameDto plotNameDto : metrics) {
selectedMetricsIds.add(generateMetricPlotId(plotNameDto));
}
// Remove plots from display which were unchecked
HashSet<String> metricIdsSet = new HashSet<String>(chosenMetrics.getMetrics().keySet());
for (String plotId : metricIdsSet) {
if (!selectedMetricsIds.contains(plotId)) {
chosenMetrics.getMetrics().remove(plotId);
}
}
final ArrayList<MetricNameDto> notLoaded = new ArrayList<MetricNameDto>();
final ArrayList<MetricDto> loaded = new ArrayList<MetricDto>();
for (MetricNameDto metricName : metrics){
if (!summaryPanel.getCachedMetrics().containsKey(metricName)){
notLoaded.add(metricName);
}else{
MetricDto metric = summaryPanel.getCachedMetrics().get(metricName);
loaded.add(metric);
}
}
MetricDataService.Async.getInstance().getMetrics(notLoaded, new AsyncCallback<List<MetricDto>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(List<MetricDto> result) {
loaded.addAll(result);
MetricRankingProvider.sortMetrics(loaded);
RecordList recordList = new RecordList();
recordList.addList(emptyData);
for (MetricDto metric : loaded){
summaryPanel.getCachedMetrics().put(metric.getMetricName(), metric);
recordList.add(summaryPanel.getSessionComparisonPanel().generateRecord(metric));
}
chosenMetrics.setRecordList(recordList);
renderMetricPlots(loaded);
if (mainTabPanel.getSelectedIndex() == 0) {
onSummaryTabSelected();
}
}
});
}
}
private void renderMetricPlots(List<MetricDto> result) {
for (MetricDto metric : result) {
if (isMaxPlotCountReached()) {
Window.alert("You are reached max count of plot on display");
break;
}
// Generate DOM id for plot
final String id = generateMetricPlotId(metric.getMetricName());
if (!chosenMetrics.getMetrics().containsKey(id)) {
chosenMetrics.getMetrics().put(id, metric);
}
// If plot has already displayed, then pass it
if (plotTrendsPanel.getElementById(id) != null) {
continue;
}
}
if (mainTabPanel.getSelectedIndex() == 1) {
onTrendsTabSelected();
}
}
}
/**
* Handles specific plot of task selection
*/
private class TaskPlotSelectionChangedHandler extends PlotsServingBase implements SelectionChangeEvent.Handler {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Set<PlotNameDto> selected = ((MultiSelectionModel<PlotNameDto>) event.getSource()).getSelectedSet();
final Set<SessionDataDto> selectedSessions = ((MultiSelectionModel<SessionDataDto>) sessionsDataGrid.getSelectionModel()).getSelectedSet();
if (selected.isEmpty()) {
// Remove plots from display which were unchecked
for (int i = 0; i < plotPanel.getWidgetCount(); i++) {
Widget widget = plotPanel.getWidget(i);
String widgetId = widget.getElement().getId();
if (isTaskScopePlotId(widgetId) || isCrossSessionsTaskScopePlotId(widgetId)) {
plotPanel.remove(i);
break;
}
}
} else if (selectedSessions.size() == 1) {
// Generate all id of plots which should be displayed
Set<String> selectedTaskIds = new HashSet<String>();
for (PlotNameDto plotNameDto : selected) {
selectedTaskIds.add(generateTaskScopePlotId(plotNameDto));
}
// Remove plots from display which were unchecked
for (int i = 0; i < plotPanel.getWidgetCount(); i++) {
Widget widget = plotPanel.getWidget(i);
String widgetId = widget.getElement().getId();
if (!isTaskScopePlotId(widgetId) || selectedTaskIds.contains(widgetId)) {
continue;
}
// Remove plot
plotPanel.remove(i);
}
PlotProviderService.Async.getInstance().getPlotDatas(selected, new AsyncCallback<Map<PlotNameDto, List<PlotSeriesDto>>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(Map<PlotNameDto, List<PlotSeriesDto>> result) {
for (PlotNameDto plotNameDto : result.keySet()){
if (isMaxPlotCountReached()) {
Window.alert("You are reached max count of plot on display");
break;
}
// Generate DOM id for plot
final String id = generateTaskScopePlotId(plotNameDto);
// If plot has already displayed, then pass it
if (plotPanel.getElementById(id) != null) {
continue;
}
renderPlots(plotPanel, result.get(plotNameDto), id);
scrollPanelMetrics.scrollToBottom();
}
}
});
} else {
// Generate all id of plots which should be displayed
Set<String> selectedTaskIds = new HashSet<String>();
for (PlotNameDto plotNameDto : selected) {
selectedTaskIds.add(generateCrossSessionsTaskScopePlotId(plotNameDto));
}
// Remove plots from display which were unchecked
for (int i = 0; i < plotPanel.getWidgetCount(); i++) {
Widget widget = plotPanel.getWidget(i);
String widgetId = widget.getElement().getId();
if (!isCrossSessionsTaskScopePlotId(widgetId) || selectedTaskIds.contains(widgetId)) {
continue;
}
// Remove plot
plotPanel.remove(i);
}
// Creating plots and displaying theirs
PlotProviderService.Async.getInstance().getPlotDatas(selected, new AsyncCallback<Map<PlotNameDto,List<PlotSeriesDto>>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
@Override
public void onSuccess(Map<PlotNameDto, List<PlotSeriesDto>> result) {
for (PlotNameDto plotNameDto : result.keySet()){
if (isMaxPlotCountReached()) {
Window.alert("You are reached max count of plot on display");
break;
}
// Generate DOM id for plot
final String id = generateCrossSessionsTaskScopePlotId(plotNameDto);
// If plot has already displayed, then pass it
if (plotPanel.getElementById(id) != null) {
continue;
}
renderPlots(plotPanel, result.get(plotNameDto), id);
scrollPanelMetrics.scrollToBottom();
}
}
});
}
}
}
/**
* Handles clicks on session scope plot checkboxes
*/
private class SessionScopePlotCheckBoxClickHandler extends PlotsServingBase implements ValueChangeHandler<Boolean> {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
final CheckBox source = (CheckBox) event.getSource();
final String sessionId = extractEntityIdFromDomId(source.getElement().getId());
final String plotName = source.getText();
final String id = generateSessionScopePlotId(sessionId, plotName);
// If checkbox is checked
if (source.getValue()) {
plotPanel.add(loadIndicator);
scrollPanelMetrics.scrollToBottom();
final int loadingId = plotPanel.getWidgetCount() - 1;
PlotProviderService.Async.getInstance().getSessionScopePlotData(sessionId, plotName, new AsyncCallback<List<PlotSeriesDto>>() {
@Override
public void onFailure(Throwable caught) {
plotPanel.remove(loadingId);
Window.alert("Error is occurred during server request processing (Session scope plot data fetching for " + plotName + ")");
}
@Override
public void onSuccess(List<PlotSeriesDto> result) {
plotPanel.remove(loadingId);
if (result.isEmpty()) {
Window.alert("There are no data found for " + plotName);
}
renderPlots(plotPanel, result, id);
scrollPanelMetrics.scrollToBottom();
}
});
} else {
// Remove plots from display which were unchecked
for (int i = 0; i < plotPanel.getWidgetCount(); i++) {
Widget widget = plotPanel.getWidget(i);
if (id.equals(widget.getElement().getId())) {
// Remove plot
plotPanel.remove(i);
break;
}
}
}
}
}
}
| lgpl-2.1 |
niithub/angelonline | util/src/main/java/com/njbd/ao/exception/LoginMismatchException.java | 359 | package com.njbd.ao.exception;
import com.njbd.ao.enums.ErrorCode;
public class LoginMismatchException extends APIRuntimeException {
public LoginMismatchException() {
super(ErrorCode.LOGIN_MISMATCH.getCode(), ErrorCode.LOGIN_MISMATCH.getMsg());
}
public LoginMismatchException(int code, String msg) {
super(code, msg);
}
}
| lgpl-2.1 |
kumar-physics/BioJava | biojava3-genome/src/main/java/org/biojava3/genome/uniprot/UniprotToFasta.java | 3766 | package org.biojava3.genome.uniprot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.biojava3.core.sequence.AccessionID;
import org.biojava3.core.sequence.ProteinSequence;
import org.biojava3.core.sequence.io.FastaWriterHelper;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Scooter
*/
public class UniprotToFasta {
public static void main( String[] args ){
try{
String uniprotDatFileName = "uniprot_trembl_fungi.dat";
String fastaFileName = "uniprot__trembel_fungi.faa";
UniprotToFasta uniprotToFasta = new UniprotToFasta();
uniprotToFasta.process(uniprotDatFileName, fastaFileName);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Convert a Uniprot sequence file to a fasta file. Allows you to download all sequence data for a species
* and convert to fasta to be used in a blast database
* @param uniprotDatFileName
* @param fastaFileName
* @throws Exception
*/
public void process( String uniprotDatFileName,String fastaFileName ) throws Exception{
FileReader fr = new FileReader(uniprotDatFileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String id = "";
StringBuffer sequence = new StringBuffer();
ArrayList<ProteinSequence> seqCodingRegionsList = new ArrayList<ProteinSequence>();
int count = 0;
HashMap<String,String> uniqueGenes = new HashMap<String,String>();
HashMap<String,String> uniqueSpecies = new HashMap<String,String>();
while(line != null){
if(line.startsWith("ID")){
String[] data = line.split(" ");
id = data[3];
}else if(line.startsWith("SQ")){
line = br.readLine();
while(!line.startsWith("//")){
for(int i = 0; i < line.length(); i++){
char aa = line.charAt(i);
if((aa >= 'A' && aa <= 'Z') || (aa >= 'a' && aa <= 'z' )){
sequence.append(aa);
}
}
line = br.readLine();
}
// System.out.println(">" + id);
// System.out.println(sequence.toString());
ProteinSequence seq = new ProteinSequence(sequence.toString() );
seq.setAccession(new AccessionID(id));
seqCodingRegionsList.add(seq);
sequence = new StringBuffer();
count++;
if(count % 100 == 0)
System.out.println(count);
String[] parts = id.split("_");
uniqueGenes.put(parts[0], "");
uniqueSpecies.put(parts[1],"");
}
line = br.readLine();
}
// System.out.println("Unique Genes=" + uniqueGenes.size());
// System.out.println("Unique Species=" + uniqueSpecies.size());
// System.out.println("Total sequences=" + seqCodingRegionsList.size());
FastaWriterHelper.writeProteinSequence(new File(fastaFileName), seqCodingRegionsList);
br.close();
fr.close();
// System.out.println(uniqueGenes.keySet());
// System.out.println("====================");
// System.out.println(uniqueSpecies.keySet());
}
}
| lgpl-2.1 |
jdpadrnos/MinecraftForge | src/main/java/net/minecraftforge/fluids/capability/ItemFluidContainer.java | 1897 | /*
* Minecraft Forge
* Copyright (c) 2016.
*
* 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 version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fluids.capability;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.IFluidContainerItem;
import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStack;
/**
* A simple fluid container, to replace the functionality of {@link FluidContainerRegistry) and {@link IFluidContainerItem}.
* This fluid container may be set so that is can only completely filled or empty. (binary)
* It may also be set so that it gets consumed when it is drained. (consumable)
*/
public class ItemFluidContainer extends Item
{
protected final int capacity;
/**
* @param capacity The maximum capacity of this fluid container.
*/
public ItemFluidContainer(int capacity)
{
this.capacity = capacity;
}
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt)
{
return new FluidHandlerItemStack(stack, capacity);
}
}
| lgpl-2.1 |
geotools/geotools | modules/library/coverage/src/main/java/org/geotools/coverage/processing/operation/SubsampleAverage.java | 1526 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2006-2008, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.coverage.processing.operation;
import org.geotools.coverage.processing.BaseScaleOperationJAI;
/**
* This operation is simply a wrapper for the JAI SubsampleAverage operation which allows me to
* arbitrarily scale a rendered image while smoothing it out.
*
* @author Simone Giannecchini, GeoSolutions.
* @version $Id: SubsampleAverage.java 23157 2006-12-01 01:29:53Z
* desruisseaSubsampleAveragedCoverageator.SubsampleAverageDescriptor
* @since 2.3
* @see javax.media.jai.operator.SubsampleAverageDescriptor
*/
public class SubsampleAverage extends BaseScaleOperationJAI {
/** Serial number for interoperability with different versions. */
private static final long serialVersionUID = 1L;
/** Constructs a default {@code "SubsampleAverage"} operation. */
public SubsampleAverage() {
super("SubsampleAverage");
}
}
| lgpl-2.1 |
DiceNyan/DreamEcon_InventoryAdditionals | src/main/java/su/jfdev/skymine/inventorymoney/ClientMessageHandler.java | 675 | package su.jfdev.skymine.inventorymoney;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
* Created by Jamefrus on 21.08.2015.
*/
@SideOnly(Side.CLIENT)
public class ClientMessageHandler implements IMessageHandler<ResponseMessage,IMessage> {
@Override
public IMessage onMessage(ResponseMessage message, MessageContext ctx) {
if(ctx.side == Side.CLIENT){
ClientProxy.money = message.money;
}
return null;
}
}
| lgpl-2.1 |
Romenig/ivprog2 | src/usp/ime/line/ivprog/view/editor/codeblocks/CodeBaseGUI.java | 1567 | package usp.ime.line.ivprog.view.editor.codeblocks;
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import usp.ime.line.ivprog.IVProg2;
import usp.ime.line.ivprog.view.editor.IVPFunctionBody;
import usp.ime.line.ivprog.view.utils.GripArea;
import usp.ime.line.ivprog.view.utils.RoundedJPanel;
public abstract class CodeBaseGUI extends RoundedJPanel {
private static final long serialVersionUID = 1L;
protected JPanel compositePanel = new JPanel();
protected IVPFunctionBody escope = null;
protected JComponent ivpContainer = null;
private JPanel gripArea = new JPanel();
protected int indexAtContainer = -1;
public CodeBaseGUI() {
setLayout(new BorderLayout());
initGripArea();
initCompositePanel();
addMouseListener(IVProg2.getMouseListener());
}
private void initCompositePanel() {
compositePanel.setBorder(new EmptyBorder(2, 0, 2, 2));
compositePanel.setOpaque(false);
compositePanel.setLayout(new BorderLayout(0, 0));
add(compositePanel, BorderLayout.CENTER);
}
private void initGripArea() {
GripArea grip = new GripArea();
gripArea.setLayout(new BorderLayout());
gripArea.add(grip, BorderLayout.CENTER);
gripArea.setBorder(new EmptyBorder(0, 2, 2, 2));
gripArea.add(grip, BorderLayout.CENTER);
gripArea.setOpaque(false);
add(gripArea, BorderLayout.WEST);
}
}
| lgpl-2.1 |
mtommila/apfloat | apfloat/src/main/java/org/apfloat/internal/AbstractDataStorageBuilder.java | 4565 | /*
* MIT License
*
* Copyright (c) 2002-2021 Mikko Tommila
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.apfloat.internal;
import org.apfloat.ApfloatContext;
import org.apfloat.ApfloatRuntimeException;
import org.apfloat.spi.DataStorageBuilder;
import org.apfloat.spi.DataStorage;
/**
* Abstract base class for a data storage creation strategy.
* Depending on the implementation-specific element size, the
* requested data length and threshold values configured in the
* current {@link ApfloatContext}, different types of data storages
* are created.
*
* @since 1.7.0
* @version 1.8.2
* @author Mikko Tommila
*/
public abstract class AbstractDataStorageBuilder
implements DataStorageBuilder
{
/**
* Subclass constructor.
*/
protected AbstractDataStorageBuilder()
{
}
@Override
public DataStorage createDataStorage(long size)
throws ApfloatRuntimeException
{
ApfloatContext ctx = ApfloatContext.getContext();
// Sizes are in bytes
if (size <= ctx.getMemoryThreshold() && size <= getMaxCachedSize())
{
return createCachedDataStorage();
}
else
{
return createNonCachedDataStorage();
}
}
@Override
public DataStorage createCachedDataStorage(long size)
throws ApfloatRuntimeException
{
ApfloatContext ctx = ApfloatContext.getContext();
// Sizes are in bytes
if (size <= ctx.getMaxMemoryBlockSize() && size <= getMaxCachedSize())
{
// Use memory data storage if it can fit in memory
return createCachedDataStorage();
}
else
{
// If it can't fit in memory then still have to use disk data storage
return createNonCachedDataStorage();
}
}
@Override
public DataStorage createDataStorage(DataStorage dataStorage)
throws ApfloatRuntimeException
{
if (isCached(dataStorage))
{
long size = dataStorage.getSize();
ApfloatContext ctx = ApfloatContext.getContext();
// Sizes are in bytes
if (size > ctx.getMemoryThreshold())
{
// If it is a memory data storage and should be moved to disk then do so
DataStorage tmp = createNonCachedDataStorage();
tmp.copyFrom(dataStorage);
dataStorage = tmp;
}
}
return dataStorage;
}
/**
* Get the maximum cached data storage size.
*
* @return The maximum cached data storage size.
*/
protected abstract long getMaxCachedSize();
/**
* Create a cached data storage.
*
* @return A new cached data storage.
*/
protected abstract DataStorage createCachedDataStorage()
throws ApfloatRuntimeException;
/**
* Create a non-cached data storage.
*
* @return A new non-cached data storage.
*/
protected abstract DataStorage createNonCachedDataStorage()
throws ApfloatRuntimeException;
/**
* Test if the data storage is of cached type.
*
* @param dataStorage The data storage.
*
* @return If the data storage is cached.
*/
protected abstract boolean isCached(DataStorage dataStorage)
throws ApfloatRuntimeException;
}
| lgpl-2.1 |
apetresc/JFreeChart | src/test/java/org/jfree/chart/imagemap/junit/ImageMapPackageTests.java | 3000 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2009, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -------------------------
* ImageMapPackageTests.java
* -------------------------
* (C) Copyright 2007-2009, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Dec-2007 : Version 1 (DG);
* 25-Mar-2009 : Added DynamicDriveToolTipTagFragmentGeneratorTests,
* ImageMapUtilitiesTests and
* OverLIBToolTipTagFragmentGeneratorTests (DG);
*
*/
package org.jfree.chart.imagemap.junit;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* A collection of tests for the org.jfree.chart.imagemap package.
* <P>
* These tests can be run using JUnit (http://www.junit.org).
*/
public class ImageMapPackageTests extends TestCase {
/**
* Returns a test suite to the JUnit test runner.
*
* @return The test suite.
*/
public static Test suite() {
TestSuite suite = new TestSuite("org.jfree.chart.imagemap");
suite.addTestSuite(DynamicDriveToolTipTagFragmentGeneratorTests.class);
suite.addTestSuite(ImageMapUtilitiesTests.class);
suite.addTestSuite(OverLIBToolTipTagFragmentGeneratorTests.class);
suite.addTestSuite(StandardToolTipTagFragmentGeneratorTests.class);
suite.addTestSuite(StandardURLTagFragmentGeneratorTests.class);
return suite;
}
/**
* Constructs the test suite.
*
* @param name the suite name.
*/
public ImageMapPackageTests(String name) {
super(name);
}
/**
* Runs the test suite using JUnit's text-based runner.
*
* @param args ignored.
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
| lgpl-2.1 |
aloubyansky/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/HostControllerService.java | 16778 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.host.controller;
import static java.security.AccessController.doPrivileged;
import static org.jboss.as.controller.AbstractControllerService.EXECUTOR_CAPABILITY;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jboss.as.controller.CapabilityRegistry;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.domain.http.server.ConsoleAvailabilityService;
import org.jboss.as.host.controller.logging.HostControllerLogger;
import org.jboss.as.remoting.HttpListenerRegistryService;
import org.jboss.as.remoting.management.ManagementRemotingServices;
import org.jboss.as.server.BootstrapListener;
import org.jboss.as.server.FutureServiceContainer;
import org.jboss.as.server.Services;
import org.jboss.as.server.logging.ServerLogger;
import org.jboss.as.version.ProductConfig;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.service.ValueService;
import org.jboss.msc.value.ImmediateValue;
import org.jboss.msc.value.InjectedValue;
import org.jboss.msc.value.Value;
import org.jboss.threads.AsyncFuture;
import org.jboss.threads.EnhancedQueueExecutor;
import org.jboss.threads.JBossThreadFactory;
/**
* The root service for a HostController process.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public class HostControllerService implements Service<AsyncFuture<ServiceContainer>> {
public static final ServiceName HC_SERVICE_NAME = ServiceName.JBOSS.append("host", "controller");
/** @deprecated Use the org.wildfly.management.executor capability */
@Deprecated
public static final ServiceName HC_EXECUTOR_SERVICE_NAME = HC_SERVICE_NAME.append("executor");
public static final ServiceName HC_SCHEDULED_EXECUTOR_SERVICE_NAME = HC_SERVICE_NAME.append("scheduled", "executor");
private final ThreadGroup threadGroup = new ThreadGroup("Host Controller Service Threads");
private final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<JBossThreadFactory>() {
public JBossThreadFactory run() {
return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, "%G - %t", null, null);
}
});
private final HostControllerEnvironment environment;
private final HostRunningModeControl runningModeControl;
private final ControlledProcessState processState;
private final String authCode;
private final CapabilityRegistry capabilityRegistry;
private volatile FutureServiceContainer futureContainer;
private volatile long startTime;
public HostControllerService(final HostControllerEnvironment environment, final HostRunningModeControl runningModeControl,
final String authCode, final ControlledProcessState processState, FutureServiceContainer futureContainer) {
this.environment = environment;
this.runningModeControl = runningModeControl;
this.authCode = authCode;
this.processState = processState;
this.startTime = environment.getStartTime();
this.futureContainer = futureContainer;
this.capabilityRegistry = new CapabilityRegistry(false);
}
public HostControllerService(final HostControllerEnvironment environment, final HostRunningModeControl runningModeControl,
final String authCode, final ControlledProcessState processState) {
this(environment, runningModeControl, authCode, processState, new FutureServiceContainer());
}
@Override
public void start(StartContext context) throws StartException {
//Moved to AbstractControllerService.start()
// processState.setStarting();
final ProductConfig config = environment.getProductConfig();
final String prettyVersion = config.getPrettyVersionString();
ServerLogger.AS_ROOT_LOGGER.serverStarting(prettyVersion);
if (System.getSecurityManager() != null) {
ServerLogger.AS_ROOT_LOGGER.securityManagerEnabled();
}
if (ServerLogger.CONFIG_LOGGER.isDebugEnabled()) {
final Properties properties = System.getProperties();
final StringBuilder b = new StringBuilder(8192);
b.append("Configured system properties:");
for (String property : new TreeSet<String>(properties.stringPropertyNames())) {
String propVal = property.toLowerCase(Locale.ROOT).contains("password") ? "<redacted>" : properties.getProperty(property, "<undefined>");
if (property.toLowerCase(Locale.ROOT).equals("sun.java.command") && !propVal.isEmpty()) {
Pattern pattern = Pattern.compile("(-D(?:[^ ])+=)((?:[^ ])+)");
Matcher matcher = pattern.matcher(propVal);
StringBuffer sb = new StringBuffer(propVal.length());
while (matcher.find()) {
if (matcher.group(1).contains("password")) {
matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(1) + "<redacted>"));
}
}
matcher.appendTail(sb);
propVal = sb.toString();
}
b.append("\n\t").append(property).append(" = ").append(propVal);
}
ServerLogger.CONFIG_LOGGER.debug(b);
ServerLogger.CONFIG_LOGGER.debugf("VM Arguments: %s", getVMArguments());
if (ServerLogger.CONFIG_LOGGER.isTraceEnabled()) {
b.setLength(0);
final Map<String, String> env = System.getenv();
b.append("Configured system environment:");
for (String key : new TreeSet<String>(env.keySet())) {
String envVal = key.toLowerCase(Locale.ROOT).contains("password") ? "<redacted>" : env.get(key);
b.append("\n\t").append(key).append(" = ").append(envVal);
}
ServerLogger.CONFIG_LOGGER.trace(b);
}
}
final ServiceTarget serviceTarget = context.getChildTarget();
final ServiceController<?> myController = context.getController();
final ServiceContainer serviceContainer = myController.getServiceContainer();
long startTime = this.startTime;
if (startTime == -1) {
startTime = System.currentTimeMillis();
} else {
this.startTime = -1;
}
final BootstrapListener bootstrapListener = new BootstrapListener(serviceContainer, startTime, serviceTarget, futureContainer, prettyVersion + " (Host Controller)", environment.getDomainTempDir());
bootstrapListener.getStabilityMonitor().addController(myController);
// The first default services are registered before the bootstrap operations are executed.
// Install the process controller client
// if this is running embedded, then processcontroller is a noop, this can be extended later.
final ProcessType processType = environment.getProcessType();
if (processType == ProcessType.EMBEDDED_HOST_CONTROLLER) {
final ProcessControllerConnectionServiceNoop processControllerClient = new ProcessControllerConnectionServiceNoop(environment, authCode);
serviceTarget.addService(ProcessControllerConnectionServiceNoop.SERVICE_NAME, processControllerClient).install();
} else {
final ProcessControllerConnectionService processControllerClient = new ProcessControllerConnectionService(environment, authCode);
serviceTarget.addService(ProcessControllerConnectionService.SERVICE_NAME, processControllerClient).install();
}
// Executor Services
final HostControllerExecutorService executorService = new HostControllerExecutorService(threadFactory);
serviceTarget.addService(EXECUTOR_CAPABILITY.getCapabilityServiceName(), executorService)
.addAliases(HC_EXECUTOR_SERVICE_NAME, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now
.install();
final HostControllerScheduledExecutorService scheduledExecutorService = new HostControllerScheduledExecutorService(threadFactory);
serviceTarget.addService(HC_SCHEDULED_EXECUTOR_SERVICE_NAME, scheduledExecutorService)
.addDependency(EXECUTOR_CAPABILITY.getCapabilityServiceName(), ExecutorService.class, scheduledExecutorService.executorInjector)
.install();
// Install required path services. (Only install those identified as required)
HostPathManagerService hostPathManagerService = new HostPathManagerService(capabilityRegistry);
HostPathManagerService.addService(serviceTarget, hostPathManagerService, environment);
HttpListenerRegistryService.install(serviceTarget);
// Add product config service
final Value<ProductConfig> productConfigValue = new ImmediateValue<ProductConfig>(config);
serviceTarget.addService(Services.JBOSS_PRODUCT_CONFIG_SERVICE, new ValueService<ProductConfig>(productConfigValue))
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
ConsoleAvailabilityService.addService(serviceTarget, bootstrapListener::logAdminConsole);
DomainModelControllerService.addService(serviceTarget, environment, runningModeControl, processState,
bootstrapListener, hostPathManagerService, capabilityRegistry, threadGroup);
}
@Override
public void stop(StopContext context) {
String prettyVersion = environment.getProductConfig().getPrettyVersionString();
//Moved to AbstractControllerService.stop()
//processState.setStopping();
ServerLogger.AS_ROOT_LOGGER.serverStopped(prettyVersion, Integer.valueOf((int) (context.getElapsedTime() / 1000000L)));
BootstrapListener.deleteStartupMarker(environment.getDomainTempDir());
}
@Override
public AsyncFuture<ServiceContainer> getValue() throws IllegalStateException, IllegalArgumentException {
return futureContainer;
}
public HostControllerEnvironment getEnvironment() {
return environment;
}
private String getVMArguments() {
final StringBuilder result = new StringBuilder(1024);
final RuntimeMXBean rmBean = ManagementFactory.getRuntimeMXBean();
final List<String> inputArguments = rmBean.getInputArguments();
for (String arg : inputArguments) {
result.append(arg).append(" ");
}
return result.toString();
}
static final class HostControllerExecutorService implements Service<ExecutorService> {
final ThreadFactory threadFactory;
private ExecutorService executorService;
private HostControllerExecutorService(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
if (EnhancedQueueExecutor.DISABLE_HINT) {
executorService = new ThreadPoolExecutor(1, Integer.MAX_VALUE,
5L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
} else {
executorService = new EnhancedQueueExecutor.Builder()
.setCorePoolSize(1)
.setMaximumPoolSize(4096)
.setKeepAliveTime(5L, TimeUnit.SECONDS)
.setThreadFactory(threadFactory)
.build();
}
}
@Override
public synchronized void stop(final StopContext context) {
Thread executorShutdown = new Thread(new Runnable() {
@Override
public void run() {
boolean interrupted = false;
try {
executorService.shutdown();
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
interrupted = true;
} finally {
try {
List<Runnable> tasks = executorService.shutdownNow();
executorService = null;
if (!interrupted) {
for (Runnable task : tasks) {
HostControllerLogger.ROOT_LOGGER.debugf("%s -- Discarding unexecuted task %s", getClass().getSimpleName(), task);
}
}
} finally {
context.complete();
}
}
}
}, "HostController ExecutorService Shutdown Thread");
executorShutdown.start();
context.asynchronous();
}
@Override
public synchronized ExecutorService getValue() throws IllegalStateException {
return executorService;
}
}
static final class HostControllerScheduledExecutorService implements Service<ScheduledExecutorService> {
private final ThreadFactory threadFactory;
private ScheduledThreadPoolExecutor scheduledExecutorService;
private final InjectedValue<ExecutorService> executorInjector = new InjectedValue<>();
private HostControllerScheduledExecutorService(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
scheduledExecutorService = new ScheduledThreadPoolExecutor(4 , threadFactory);
scheduledExecutorService.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}
@Override
public synchronized void stop(final StopContext context) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
scheduledExecutorService.shutdown();
} finally {
scheduledExecutorService = null;
context.complete();
}
}
};
try {
executorInjector.getValue().execute(r);
} catch (RejectedExecutionException e) {
r.run();
} finally {
context.asynchronous();
}
}
@Override
public synchronized ScheduledExecutorService getValue() throws IllegalStateException {
return scheduledExecutorService;
}
}
}
| lgpl-2.1 |
skyvers/wildcat | skyve-ext/src/main/java/org/skyve/impl/persistence/hibernate/HibernateBizQL.java | 2401 | package org.skyve.impl.persistence.hibernate;
import java.util.List;
import org.hibernate.query.Query;
import org.skyve.domain.Bean;
import org.skyve.impl.persistence.AbstractBizQL;
import org.skyve.persistence.AutoClosingIterable;
import org.skyve.persistence.BizQL;
import org.skyve.impl.persistence.hibernate.AbstractHibernatePersistence;
import org.skyve.impl.persistence.hibernate.HibernateQueryDelegate;
public class HibernateBizQL extends AbstractBizQL {
private HibernateQueryDelegate delegate;
public HibernateBizQL(String query,
AbstractHibernatePersistence persistence) {
super(query);
delegate = new HibernateQueryDelegate(persistence);
}
@Override
public <T extends Bean> List<T> beanResults() {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.list(query, true, true, false);
}
@Override
public <T extends Bean> AutoClosingIterable<T> beanIterable() {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.iterate(query, true, true, false);
}
@Override
public <T extends Bean> List<T> projectedResults() {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.list(query, false, false, false);
}
@Override
public <T extends Bean> AutoClosingIterable<T> projectedIterable() {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.iterate(query, false, false, false);
}
@Override
public <T> List<T> scalarResults(Class<T> type) {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.list(query, true, true, false);
}
@Override
public <T> AutoClosingIterable<T> scalarIterable(Class<T> type) {
Query<T> query = delegate.createHibernateQuery(this);
return delegate.iterate(query, true, true, false);
}
@Override
public List<Object[]> tupleResults() {
Query<Object[]> query = delegate.createHibernateQuery(this);
return delegate.list(query, true, false, true);
}
@Override
public AutoClosingIterable<Object[]> tupleIterable() {
Query<Object[]> query = delegate.createHibernateQuery(this);
return delegate.iterate(query, true, false, true);
}
@Override
public int execute() {
return delegate.execute(this);
}
@Override
public BizQL setFirstResult(int first) {
delegate.setFirstResult(first);
return this;
}
@Override
public BizQL setMaxResults(int max) {
delegate.setMaxResults(max);
return this;
}
}
| lgpl-2.1 |
rambabu0006/onesevenhome | core-model/src/main/java/com/salesmanager/core/model/customer/WallPaperPortfolio.java | 3719 | package com.salesmanager.core.model.customer;
import java.math.BigDecimal;
import java.util.Date;
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.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import com.salesmanager.core.constants.SchemaConstant;
import com.salesmanager.core.model.catalog.product.price.FinalPrice;
import com.salesmanager.core.model.generic.SalesManagerEntity;
import com.salesmanager.core.model.services.Services;
@Entity
@Table(name = "WALLPAPER_PORTFOLIO", schema=SchemaConstant.SALESMANAGER_SCHEMA)
public class WallPaperPortfolio extends SalesManagerEntity<Long, WallPaperPortfolio> {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "WALLPAPER_PORTFOLIO_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@Temporal(TemporalType.DATE)
@Column(name="CREATE_DATE")
private Date createDate;
@ManyToOne(targetEntity = Customer.class)
@JoinColumn(name = "WALLPAPER_ID", nullable = false)
private Customer customer;
@Column (name ="PORTFOLIO_NAME", length=200)
private String portfolioName;
@Column (name ="IMAGE_URL", length=200)
private String imageURL;
@Column(name = "PRICE")
private BigDecimal price;
@Column (name ="SIZE", length=50)
private String size;
@Column (name ="THICKNESS", length=50)
private String thickness;
@Column (name ="BRAND", length=50)
private String brand;
@Column (name ="ADMIN_APPROVE_STATUS", length=5)
private String status = "N";
@Column (name ="SERVICE_CHARGES")
private BigDecimal serviceCharges;
@Transient
private Integer quantity = new Integer(0);
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getPortfolioName() {
return portfolioName;
}
public void setPortfolioName(String portfolioName) {
this.portfolioName = portfolioName;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getThickness() {
return thickness;
}
public void setThickness(String thickness) {
this.thickness = thickness;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public BigDecimal getServiceCharges() {
return serviceCharges;
}
public void setServiceCharges(BigDecimal serviceCharges) {
this.serviceCharges = serviceCharges;
}
}
| lgpl-2.1 |
SimonKagstrom/cibyl | syscalls/softfloat/implementation/__asinf_helper.java | 139 | public static int __asinf_helper(int _a)
{
float a = Float.intBitsToFloat(_a);
return Float.floatToIntBits( (float)mMath.asin(a) );
}
| lgpl-2.1 |
jsmithe/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_7_0/models/Variable_impl_ari_1_7_0.java | 1118 | package ch.loway.oss.ari4java.generated.ari_1_7_0.models;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Feb 04 15:23:09 CET 2017
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**********************************************************
* The value of a channel variable
*
* Defined in file: asterisk.json
* Generated by: Model
*********************************************************/
public class Variable_impl_ari_1_7_0 implements Variable, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** The value of the variable requested */
private String value;
public String getValue() {
return value;
}
@JsonDeserialize( as=String.class )
public void setValue(String val ) {
value = val;
}
/** No missing signatures from interface */
}
| lgpl-3.0 |
haisamido/SFDaaS | src/org/orekit/time/TDBScale.java | 2874 | /* Copyright 2002-2010 CS Communication & Systèmes
* Licensed to CS Communication & Syst�mes (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.time;
import org.orekit.utils.Constants;
/** Barycentric Dynamic Time.
* <p>Time used to take account of time dilation when calculating orbits of planets,
* asteroids, comets and interplanetary spacecraft in the Solar system. It was based
* on a Dynamical time scale but was not well defined and not rigorously correct as
* a relativistic time scale. It was subsequently deprecated in favour of
* Barycentric Coordinate Time (TCB), but at the 2006 General Assembly of the
* International Astronomical Union TDB was rehabilitated by making it a specific
* fixed linear transformation of TCB.</p>
* <p>By convention, TDB = TT + 0.001658 sin(g) + 0.000014 sin(2g)seconds
* where g = 357.53 + 0.9856003 (JD - 2451545) degrees.</p>
* @author Aude Privat
* @version $Revision:1665 $ $Date:2008-06-11 12:12:59 +0200 (mer., 11 juin 2008) $
*/
public class TDBScale implements TimeScale {
/** Serializable UID. */
private static final long serialVersionUID = -4138483908215161856L;
/** Package private constructor for the factory.
*/
TDBScale() {
}
/** {@inheritDoc} */
public double offsetFromTAI(final AbsoluteDate date) {
final double dtDays = date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY;
final double g = Math.toRadians(357.53 + 0.9856003 * dtDays);
return TimeScalesFactory.getTT().offsetFromTAI(date) + (0.001658 * Math.sin(g) + 0.000014 * Math.sin(2 * g));
}
/** {@inheritDoc} */
public double offsetToTAI(final DateComponents date, final TimeComponents time) {
final AbsoluteDate reference = new AbsoluteDate(date, time, TimeScalesFactory.getTAI());
double offset = 0;
for (int i = 0; i < 3; i++) {
offset = -offsetFromTAI(reference.shiftedBy(offset));
}
return offset;
}
/** {@inheritDoc} */
public String getName() {
return "TDB";
}
/** {@inheritDoc} */
public String toString() {
return getName();
}
}
| lgpl-3.0 |
Unknow0/kyhtanil | server/src/main/java/unknow/kyhtanil/server/system/ProjectileSystem.java | 1563 | package unknow.kyhtanil.server.system;
import java.util.function.IntPredicate;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.systems.IteratingSystem;
import com.artemis.utils.IntBag;
import unknow.kyhtanil.common.component.Position;
import unknow.kyhtanil.common.component.StatShared;
import unknow.kyhtanil.server.component.Projectile;
import unknow.kyhtanil.server.manager.LocalizedManager;
import unknow.kyhtanil.server.manager.UUIDManager;
/**
* manage projectile life time and on hit effect
*
* @author unknow
*/
public class ProjectileSystem extends IteratingSystem {
private LocalizedManager locManager;
private UUIDManager uuid;
private ComponentMapper<Projectile> projectile;
private ComponentMapper<Position> position;
private ComponentMapper<StatShared> mobInfo;
private IntPredicate c = e -> mobInfo.has(e);
/**
* create new ProjectileSystem
*/
public ProjectileSystem() {
super(Aspect.all(Projectile.class, Position.class));
}
@Override
protected void process(int e) {
Projectile proj = projectile.get(e);
Position p = position.get(e);
Integer src = uuid.getEntity(proj.source);
if (src == null) {
world.delete(e);
return;
}
IntBag potential = locManager.get(p.x, p.y, 50, c); // TODO width & collision
for (int i = 0; i < potential.size(); i++) {
int t = potential.get(i);
if (t == src.intValue())
continue;
if (p.distance(position.get(t)) < 16) {
if (proj.onHit != null)
proj.onHit.accept(t);
world.delete(e);
return;
}
}
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/ListDelRqTypeDescriptor.java | 7540 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: ListDelRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.ListDelRqType;
/**
* Class ListDelRqTypeDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $
*/
public class ListDelRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ListDelRqTypeDescriptor() {
super();
_xmlName = "ListDelRqType";
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _requestID
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ListDelRqType target = (ListDelRqType) object;
return target.getRequestID();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ListDelRqType target = (ListDelRqType) object;
target.setRequestID( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _requestID
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _listDel
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.ListDel.class, "_listDel", "-error-if-this-is-used-", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ListDelRqType target = (ListDelRqType) object;
return target.getListDel();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ListDelRqType target = (ListDelRqType) object;
target.setListDel( (org.chocolate_milk.model.ListDel) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.chocolate_milk.model.ListDel();
}
};
desc.setSchemaType("org.chocolate_milk.model.ListDel");
desc.setHandler(handler);
desc.setContainer(true);
desc.setClassDescriptor(new org.chocolate_milk.model.descriptors.ListDelDescriptor());
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _listDel
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.ListDelRqType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
jjettenn/molgenis | molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/datatypeediting/EnumAttributeTypeUpdateTest.java | 6296 | package org.molgenis.integrationtest.platform.datatypeediting;
import org.molgenis.data.meta.AttributeType;
import org.molgenis.data.validation.MolgenisValidationException;
import org.molgenis.integrationtest.platform.PlatformITConfig;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.*;
import static org.molgenis.data.meta.AttributeType.*;
import static org.testng.Assert.*;
@ContextConfiguration(classes = { PlatformITConfig.class })
public class EnumAttributeTypeUpdateTest extends AbstractAttributeTypeUpdateTest
{
@BeforeClass
private void setup()
{
super.setup(ENUM, STRING);
}
@AfterMethod
private void afterMethod()
{
super.afterMethod(ENUM);
}
@AfterClass
public void afterClass()
{
super.afterClass();
}
@DataProvider(name = "validConversionData")
public Object[][] validConversionData()
{
return new Object[][] { { "1", STRING, "1" }, { "1", TEXT, "1" }, { "1", INT, 1 }, { "1", LONG, 1L } };
}
/**
* Valid conversion cases for ENUM to:
* STRING, TEXT, INT, LONG
*
* @param valueToConvert The value that will be converted
* @param typeToConvertTo The type to convert to
* @param convertedValue The expected value after converting the type
*/
@Test(dataProvider = "validConversionData")
public void testValidConversion(String valueToConvert, AttributeType typeToConvertTo, Object convertedValue)
{
testTypeConversion(valueToConvert, typeToConvertTo);
// Assert if conversion was successful
assertEquals(getActualDataType(), typeToConvertTo);
assertEquals(getActualValue(), convertedValue);
}
@DataProvider(name = "invalidConversionTestCases")
public Object[][] invalidConversionTestCases()
{
return new Object[][] { { "2b", INT, MolgenisValidationException.class,
"Value [2b] of this entity attribute is not of type [INT or LONG]." },
{ "2b", LONG, MolgenisValidationException.class,
"Value [2b] of this entity attribute is not of type [INT or LONG]." },
{ "1", DECIMAL, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [DECIMAL] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", XREF, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [XREF] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", CATEGORICAL, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [CATEGORICAL] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", DATE, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [DATE] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", DATE_TIME, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [DATE_TIME] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", MREF, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [MREF] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", CATEGORICAL_MREF, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [CATEGORICAL_MREF] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", EMAIL, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [EMAIL] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", HTML, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [HTML] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", HYPERLINK, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [HYPERLINK] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", COMPOUND, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [COMPOUND] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", FILE, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [FILE] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", BOOL, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [BOOL] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1b", STRING, MolgenisValidationException.class,
"Invalid [enum] value [1b] for attribute [mainAttribute] of entity [null] with type [MAIN_ENTITY]. Value must be one of [1, 2b, abc]" },
{ "1", SCRIPT, MolgenisValidationException.class,
"Attribute data type update from [ENUM] to [SCRIPT] not allowed, allowed types are [INT, LONG, STRING, TEXT]" },
{ "1", ONE_TO_MANY, MolgenisValidationException.class,
"Invalid [xref] value [] for attribute [Referenced entity] of entity [mainAttribute] with type [sys_md_Attribute]. Offended expression: $('refEntityType').isNull().and($('type').matches(/^(categorical|categoricalmref|file|mref|onetomany|xref)$/).not()).or($('refEntityType').isNull().not().and($('type').matches(/^(categorical|categoricalmref|file|mref|onetomany|xref)$/))).value().Invalid [xref] value [] for attribute [Mapped by] of entity [mainAttribute] with type [sys_md_Attribute]. Offended expression: $('mappedBy').isNull().and($('type').eq('onetomany').not()).or($('mappedBy').isNull().not().and($('type').eq('onetomany'))).value()" } };
}
/**
* Invalid conversions cases for ENUM to:
* INT, LONG, DECIMAL, XREF, CATEGORICAL, DATE, DATE_TIME, MREF, CATEGORICAL_MREF, EMAIL, HTML, HYPERLINK, COMPOUND, FILE, BOOL, STRING, SCRIPT, ONE_TO_MANY
*
* @param valueToConvert The value that will be converted
* @param typeToConvertTo The type to convert to
* @param exceptionClass The expected class of the exception that will be thrown
* @param exceptionMessage The expected exception message
*/
@Test(dataProvider = "invalidConversionTestCases")
public void testInvalidConversion(String valueToConvert, AttributeType typeToConvertTo, Class exceptionClass,
String exceptionMessage)
{
try
{
testTypeConversion(valueToConvert, typeToConvertTo);
fail("Conversion should have failed");
}
catch (Exception exception)
{
assertTrue(exception.getClass().isAssignableFrom(exceptionClass));
assertEquals(exception.getMessage(), exceptionMessage);
}
}
}
| lgpl-3.0 |
Ja-ake/Common-Chicken-Runtime-Engine | CCRE_Igneous_cRIO/src/java/io/ObjectInputStream.java | 1533 | /*
* Copyright 2014 Colby Skeggs.
*
* This file is part of the CCRE, the Common Chicken Runtime Engine.
*
* The CCRE 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.
*
* The CCRE 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 the CCRE. If not, see <http://www.gnu.org/licenses/>.
*/
package java.io;
/**
* This is a not-really-implemented implementation of java.io.ObjectInputStream.
* Don't use this. It is used when Retrotranslator downgrades the code to 1.3,
* because 1.3 doesn't have ObjectInputStream. It doesn't have any functionality
* because serialization doesn't work like this in 1.3.
*
* @see java.io.ObjectInputStream
* @author skeggsc
*/
public class ObjectInputStream {
/**
* A faked method for the downgrade version of ObjectInputStream.
*
* @throws IOException (faked)
* @throws ClassNotFoundException (faked)
*/
public void defaultReadObject() throws IOException, ClassNotFoundException {
throw new RuntimeException("ObjectInputStreams are unusable when downgraded!");
}
}
| lgpl-3.0 |
SonarOpenCommunity/sonar-cxx | cxx-sensors/src/main/java/org/sonar/cxx/sensors/tests/dotnet/CxxUnitTestResultsImportSensor.java | 4956 | /*
* C++ Community Plugin (cxx plugin)
* Copyright (C) 2010-2022 SonarOpenCommunity
* http://github.com/SonarOpenCommunity/sonar-cxx
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.cxx.sensors.tests.dotnet;
// origin https://github.com/SonarSource/sonar-dotnet-tests-library/
// SonarQube .NET Tests Library
// Copyright (C) 2014-2017 SonarSource SA
// mailto:info AT sonarsource DOT com
import java.io.File;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.scanner.sensor.ProjectSensor;
public class CxxUnitTestResultsImportSensor implements ProjectSensor {
private final WildcardPatternFileProvider wildcardPatternFileProvider
= new WildcardPatternFileProvider(new File("."), File.separator);
private final CxxUnitTestResultsAggregator unitTestResultsAggregator;
private SensorContext context;
public CxxUnitTestResultsImportSensor(CxxUnitTestResultsAggregator unitTestResultsAggregator) {
this.unitTestResultsAggregator = unitTestResultsAggregator;
}
public static List<PropertyDefinition> properties() {
var category = "CXX External Analyzers";
return Collections.unmodifiableList(Arrays.asList(
PropertyDefinition.builder(UnitTestConfiguration.VISUAL_STUDIO_TEST_RESULTS_PROPERTY_KEY)
.multiValues(true)
.name("VSTest Report(s)")
.description(
"Paths to VSTest reports. Multiple paths may be comma-delimited, or included via wildcards."
+ " Note that while measures such as the number of tests are displayed at project level, no drilldown"
+ " is available."
+ " In the SonarQube UI, enter one entry per field."
)
.category(category)
.subCategory("Visual C++")
.onQualifiers(Qualifiers.PROJECT)
.build(),
PropertyDefinition.builder(UnitTestConfiguration.NUNIT_TEST_RESULTS_PROPERTY_KEY)
.multiValues(true)
.name("NUnit Report(s)")
.description(
"Paths to NUnit execution reports. Multiple paths may be comma-delimited, or included via wildcards."
+ " Note that while measures such as the number of tests are displayed at project level, no drilldown"
+ " is available."
+ " In the SonarQube UI, enter one entry per field."
)
.category(category)
.subCategory("NUnit")
.onQualifiers(Qualifiers.PROJECT)
.build()
));
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("CXX VSTest/NUnit Test report import")
.onlyWhenConfiguration(conf -> new UnitTestConfiguration(conf).hasUnitTestResultsProperty())
.onlyOnLanguages("cxx", "cpp", "c++", "c");
}
@Override
public void execute(SensorContext context) {
this.context = context;
analyze(new UnitTestResults(), new UnitTestConfiguration(context.config()));
}
public void analyze(UnitTestResults unitTestResults, UnitTestConfiguration unitTestConf) {
var aggregatedResults = unitTestResultsAggregator.aggregate(wildcardPatternFileProvider,
unitTestResults, unitTestConf);
if (aggregatedResults != null) {
saveMetric(CoreMetrics.TESTS, aggregatedResults.tests());
saveMetric(CoreMetrics.TEST_ERRORS, aggregatedResults.errors());
saveMetric(CoreMetrics.TEST_FAILURES, aggregatedResults.failures());
saveMetric(CoreMetrics.SKIPPED_TESTS, aggregatedResults.skipped());
Long executionTime = aggregatedResults.executionTime();
if (executionTime != null) {
saveMetric(CoreMetrics.TEST_EXECUTION_TIME, executionTime);
}
}
}
private <T extends Serializable> void saveMetric(Metric<T> metric, T value) {
context.<T>newMeasure()
.withValue(value)
.forMetric(metric)
.on(context.project())
.save();
}
}
| lgpl-3.0 |
cismet/watergis-client | src/main/java/de/cismet/cismap/custom/attributerule/QpRuleSet.java | 16703 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cismap.custom.attributerule;
import Sirius.navigator.connection.SessionManager;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import org.apache.log4j.Logger;
import org.deegree.datatypes.Types;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import de.cismet.cids.custom.watergis.server.search.RemoveUnnusedRoute;
import de.cismet.cids.server.search.CidsServerSearch;
import de.cismet.cismap.cidslayer.CidsLayer;
import de.cismet.cismap.cidslayer.CidsLayerFeature;
import de.cismet.cismap.cidslayer.CidsLayerFeatureFilter;
import de.cismet.cismap.cidslayer.CidsLayerReferencedComboEditor;
import de.cismet.cismap.commons.features.Feature;
import de.cismet.cismap.commons.features.FeatureServiceFeature;
import de.cismet.cismap.commons.featureservice.FeatureServiceAttribute;
import de.cismet.cismap.commons.gui.attributetable.DateCellEditor;
import de.cismet.cismap.commons.gui.attributetable.FeatureCreator;
import de.cismet.cismap.commons.gui.attributetable.SimpleAttributeTableModel;
import de.cismet.cismap.commons.gui.piccolo.FeatureAnnotationSymbol;
import de.cismet.cismap.commons.rasterservice.MapService;
import de.cismet.cismap.commons.util.SelectionManager;
import de.cismet.cismap.linearreferencing.RouteTableCellEditor;
import de.cismet.cismap.linearreferencing.StationTableCellEditor;
import de.cismet.watergis.broker.AppBroker;
import de.cismet.watergis.gui.actions.gaf.ReportAction;
import de.cismet.watergis.gui.panels.GafProf;
import de.cismet.watergis.utils.AbstractCidsLayerListCellRenderer;
import de.cismet.watergis.utils.LinkTableCellRenderer;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class QpRuleSet extends WatergisDefaultRuleSet {
//~ Static fields/initializers ---------------------------------------------
private static final org.apache.log4j.Logger LOG = Logger.getLogger(QpRuleSet.class);
public static final BufferedImage ARROW;
public static final BufferedImage SELECTED_ARROW;
static {
try {
final URL arrowUrl = QpRuleSet.class.getResource(
"/de/cismet/watergis/res/icons16/angle.png");
ARROW = ImageIO.read(arrowUrl);
final URL arrowSelectedUrl = QpRuleSet.class.getResource(
"/de/cismet/watergis/res/icons16/angleSelected.png");
SELECTED_ARROW = ImageIO.read(arrowSelectedUrl);
// ARROW_NULL = new FeatureAnnotationSymbol(new ImageIcon(
// "/de/cismet/cids/custom/objecteditors/wrrl_db_mv/angle_null.png").getImage());
} catch (Exception ex) {
LOG.fatal(ex, ex);
throw new RuntimeException(ex);
}
}
//~ Instance initializers --------------------------------------------------
{
final DateType date = new DateType(false, true);
typeMap.put("geom", new Geom(true, false));
typeMap.put("ww_gr", new Catalogue("k_ww_gr", true, true, new Numeric(4, 0, false, false)));
typeMap.put("ba_cd", new Varchar(50, false, false));
typeMap.put("ba_st", new Numeric(10, 2, false, false));
typeMap.put("la_cd", new Numeric(20, 0, false, false));
typeMap.put("la_st", new Numeric(10, 2, false, false));
typeMap.put("l_st", new Catalogue("k_l_st", true, true, new Varchar(10, false, false)));
typeMap.put("re", new Numeric(11, 2, true, false));
typeMap.put("ho", new Numeric(10, 2, true, false));
typeMap.put("qp_nr", new Numeric(20, 0, true, false));
typeMap.put("upl_name", new Varchar(50, true, false));
typeMap.put("upl_datum", new Varchar(10, true, false));
typeMap.put("upl_zeit", new Varchar(8, true, false));
typeMap.put("aufn_name", new Varchar(50, false, true));
typeMap.put("aufn_datum", date);
typeMap.put("aufn_zeit", new Time(false, true));
typeMap.put("freigabe", new Catalogue("k_freigabe", true, true, new Varchar(10, false, false)));
typeMap.put("titel", new Varchar(250, false, true));
typeMap.put("beschreib", new Varchar(250, false, true));
typeMap.put("bemerkung", new Varchar(250, false, true));
typeMap.put("fis_g_date", new DateTime(false, false));
typeMap.put("fis_g_user", new Varchar(50, false, false));
}
//~ Methods ----------------------------------------------------------------
@Override
public boolean isColumnEditable(final String columnName) {
if (columnName.equals("ww_gr")) {
return AppBroker.getInstance().getOwner().equalsIgnoreCase("Administratoren");
} else {
// Sonderfall ba_st und ba_st sollen nicht bearbeitbar sein
return !columnName.equals("fis_g_user") && !columnName.equals("fis_g_date")
&& !columnName.equals("geom") && !columnName.equals("id")
&& !columnName.equals("ho") && !columnName.equals("re") && !columnName.equals("qp_nr")
&& !columnName.equals("la_st") && !columnName.equals("la_cd")
&& !columnName.equals("upl_name") && !columnName.equals("upl_datum")
&& !columnName.equals("upl_zeit") && !columnName.equals("ba_cd") && !columnName.equals("ba_st");
}
}
@Override
public Object afterEdit(final FeatureServiceFeature feature,
final String column,
final int row,
final Object oldValue,
final Object newValue) {
idOfCurrentlyCheckedFeature = feature.getId();
if (column.equals("aufn_datum")) {
if ((newValue != null) && (newValue instanceof Date)) {
final Date d = (Date)newValue;
// d.year = year - 1900
if ((d.getYear() < 0) || d.after(new Date())) {
showMessage("Es sind nur Datumseingaben zwischen dem 01.01.1900 und heute erlaubt", column);
return oldValue;
}
if ((d.getYear() >= 0) && (d.getYear() < 50)) {
if (
!showSecurityQuestion(
"Wert außerhalb Standardbereich (01.01.1950 .. heute) --> verwenden ?",
column,
newValue)) {
return oldValue;
}
}
}
}
return super.afterEdit(feature, column, row, oldValue, newValue);
}
@Override
public TableCellRenderer getCellRenderer(final String columnName) {
if (columnName.equals("qp_nr")) {
return new LinkTableCellRenderer(JLabel.RIGHT);
} else {
return super.getCellRenderer(columnName);
}
}
@Override
public TableCellEditor getCellEditor(final String columnName) {
if (columnName.equals("ba_cd")) {
final RouteTableCellEditor editor = new RouteTableCellEditor("dlm25w.fg_ba", "ba_st", false);
final String filterString = getRouteFilter();
if (filterString != null) {
editor.setRouteQuery(filterString);
}
return editor;
} else if (columnName.equals("ba_st")) {
return new StationTableCellEditor(columnName);
} else if (columnName.equals("ww_gr")) {
CidsLayerFeatureFilter filter = null;
if (!AppBroker.getInstance().getOwner().equalsIgnoreCase("Administratoren")) {
final String userName = AppBroker.getInstance().getOwner();
filter = new CidsLayerFeatureFilter() {
@Override
public boolean accept(final CidsLayerFeature bean) {
if (bean == null) {
return false;
}
return bean.getProperty("owner").equals(userName);
}
};
} else {
filter = new WwGrAdminFilter();
}
return new CidsLayerReferencedComboEditor(new FeatureServiceAttribute(
"ww_gr",
String.valueOf(Types.INTEGER),
true),
filter);
} else if (columnName.equals("l_st")) {
final CidsLayerFeatureFilter filter = createCidsLayerFeatureFilter("qp");
final CidsLayerReferencedComboEditor editor = new CidsLayerReferencedComboEditor(
new FeatureServiceAttribute(
columnName,
String.valueOf(Types.VARCHAR),
true),
filter);
editor.setNullable(true);
editor.setListRenderer(new AbstractCidsLayerListCellRenderer() {
@Override
protected String toString(final CidsLayerFeature bean) {
return bean.getProperty("l_st") + " - " + bean.getProperty("name");
}
});
return editor;
} else if (columnName.equals("freigabe")) {
final CidsLayerFeatureFilter filter = createCidsLayerFeatureFilter("qp");
final CidsLayerReferencedComboEditor editor = new CidsLayerReferencedComboEditor(
new FeatureServiceAttribute(
columnName,
String.valueOf(Types.VARCHAR),
true),
filter);
editor.setNullable(true);
editor.setListRenderer(new AbstractCidsLayerListCellRenderer() {
@Override
protected String toString(final CidsLayerFeature bean) {
return bean.getProperty("freigabe") + " - " + bean.getProperty("name");
}
});
return editor;
} else if (columnName.equals("ba_st")) {
return new StationTableCellEditor(columnName);
} else if (columnName.equals("aufn_datum")) {
return new DateCellEditor();
} else {
return null;
}
}
@Override
public void beforeSave(final FeatureServiceFeature feature) {
adjustFisGDateAndFisGUser(feature);
}
@Override
public void afterSave(final TableModel model) {
if (model instanceof SimpleAttributeTableModel) {
final List<FeatureServiceFeature> removedFeatures = ((SimpleAttributeTableModel)model).getRemovedFeature();
if ((removedFeatures != null) && !removedFeatures.isEmpty()) {
final List<Feature> selectedFeaturesToRemove = new ArrayList<Feature>();
for (final FeatureServiceFeature feature : removedFeatures) {
final List<Feature> selectedFeatures = SelectionManager.getInstance().getSelectedFeatures();
for (final Feature f : selectedFeatures) {
if (f instanceof CidsLayerFeature) {
final CidsLayerFeature clf = (CidsLayerFeature)f;
if ((clf.getProperty("qp_nr") != null) && (feature.getProperty("qp_nr") != null)) {
final Integer selectedFeatureBaCd = (Integer)(clf.getProperty("qp_nr"));
final Integer deletedFeatureBaCd = (Integer)(feature.getProperty("qp_nr"));
if (selectedFeatureBaCd.equals(deletedFeatureBaCd)) {
selectedFeaturesToRemove.add(f);
}
}
}
}
}
if (!selectedFeaturesToRemove.isEmpty()) {
SelectionManager.getInstance().removeSelectedFeatures(selectedFeaturesToRemove);
}
}
}
}
@Override
public String[] getAdditionalFieldNames() {
return new String[] { "re", "ho" };
}
@Override
public int getIndexOfAdditionalFieldName(final String name) {
if (name.equals("re")) {
return 8;
} else if (name.equals("ho")) {
return 9;
} else {
return super.getIndexOfAdditionalFieldName(name);
}
}
@Override
public Object getAdditionalFieldValue(final java.lang.String propertyName, final FeatureServiceFeature feature) {
Double value = null;
final Geometry geom = feature.getGeometry();
if (geom instanceof Point) {
if (propertyName.equals("re")) {
value = ((Point)geom).getX();
} else if (propertyName.equals("ho")) {
value = ((Point)geom).getY();
}
}
return value;
}
@Override
public String getAdditionalFieldFormula(final String propertyName) {
if (propertyName.equals("re")) {
return "st_x(geom)";
} else if (propertyName.equals("ho")) {
return "st_y(geom)";
}
return null;
}
@Override
public Class getAdditionalFieldClass(final int index) {
return Double.class;
}
@Override
public FeatureCreator getFeatureCreator() {
return null;
}
@Override
public Map<String, Object> getDefaultValues() {
final Map properties = new HashMap();
if ((AppBroker.getInstance().getOwnWwGr() != null)) {
properties.put("ww_gr", AppBroker.getInstance().getOwnWwGr());
} else {
properties.put("ww_gr", AppBroker.getInstance().getNiemandWwGr());
}
return properties;
}
@Override
public boolean isCatThree() {
return true;
}
@Override
public void mouseClicked(final FeatureServiceFeature feature,
final String columnName,
final Object value,
final int clickCount) {
if (columnName.equals("qp_nr")) {
if ((value instanceof Integer) && (clickCount == 1) && (feature instanceof CidsLayerFeature)) {
// if (DownloadManagerDialog.showAskingForUserTitle(AppBroker.getInstance().getRootWindow())) {
// final String jobname = DownloadManagerDialog.getJobname();
// final CidsLayerFeature cidsFeature = (CidsLayerFeature)feature;
// final String filename = value.toString();
// final String extension = ".pdf";
//
// DownloadManager.instance().add(new QpDownload(
// filename,
// extension,
// jobname,
// null,
// cidsFeature));
// }
final ReportAction action = new ReportAction();
action.actionPerformed(null);
}
}
}
@Override
public FeatureAnnotationSymbol getPointAnnotationSymbol(final FeatureServiceFeature feature) {
final FeatureAnnotationSymbol symb;
if ((GafProf.selectedFeature != null) && (GafProf.selectedFeature.getId() == feature.getId())) {
symb = new FeatureAnnotationSymbol(SELECTED_ARROW);
} else {
symb = new FeatureAnnotationSymbol(ARROW);
}
symb.setSweetSpotX(0.5);
symb.setSweetSpotY(0.5);
return symb;
}
@Override
public boolean hasCustomExportFeaturesMethod() {
return true;
}
@Override
public void exportFeatures() {
AppBroker.getInstance().getGafExport().actionPerformed(null);
}
@Override
public boolean hasCustomPrintFeaturesMethod() {
return true;
}
@Override
public void printFeatures() {
AppBroker.getInstance().getGafPrint().actionPerformed(null);
}
}
| lgpl-3.0 |
joansmith/sonarqube | server/sonar-server/src/main/java/org/sonar/server/metric/DefaultMetricFinder.java | 4019 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.metric;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.MetricFinder;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.server.db.DbClient;
import static com.google.common.collect.FluentIterable.from;
public class DefaultMetricFinder implements MetricFinder {
private final DbClient dbClient;
public DefaultMetricFinder(DbClient dbClient) {
this.dbClient = dbClient;
}
@Override
public Metric findById(int id) {
DbSession session = dbClient.openSession(false);
try {
MetricDto dto = dbClient.metricDao().selectById(session, id);
if (dto != null && dto.isEnabled()) {
return ToMetric.INSTANCE.apply(dto);
}
return null;
} finally {
MyBatis.closeQuietly(session);
}
}
@Override
public Metric findByKey(String key) {
DbSession session = dbClient.openSession(false);
try {
MetricDto dto = dbClient.metricDao().selectByKey(session, key);
if (dto != null && dto.isEnabled()) {
return ToMetric.INSTANCE.apply(dto);
}
return null;
} finally {
MyBatis.closeQuietly(session);
}
}
@Override
public Collection<Metric> findAll(List<String> metricKeys) {
DbSession session = dbClient.openSession(false);
try {
List<MetricDto> dtos = dbClient.metricDao().selectByKeys(session, metricKeys);
return from(dtos).filter(IsEnabled.INSTANCE).transform(ToMetric.INSTANCE).toList();
} finally {
MyBatis.closeQuietly(session);
}
}
@Override
public Collection<Metric> findAll() {
DbSession session = dbClient.openSession(false);
try {
List<MetricDto> dtos = dbClient.metricDao().selectEnabled(session);
return from(dtos).transform(ToMetric.INSTANCE).toList();
} finally {
MyBatis.closeQuietly(session);
}
}
private enum IsEnabled implements Predicate<MetricDto> {
INSTANCE;
@Override
public boolean apply(@Nonnull MetricDto dto) {
return dto.isEnabled();
}
}
private enum ToMetric implements Function<MetricDto, Metric> {
INSTANCE;
@Override
public Metric apply(@Nonnull MetricDto dto) {
Metric<Serializable> metric = new Metric<>();
metric.setId(dto.getId());
metric.setKey(dto.getKey());
metric.setDescription(dto.getDescription());
metric.setName(dto.getShortName());
metric.setBestValue(dto.getBestValue());
metric.setDomain(dto.getDomain());
metric.setEnabled(dto.isEnabled());
metric.setDirection(dto.getDirection());
metric.setHidden(dto.isHidden());
metric.setQualitative(dto.isQualitative());
metric.setType(Metric.ValueType.valueOf(dto.getValueType()));
metric.setOptimizedBestValue(dto.isOptimizedBestValue());
metric.setUserManaged(dto.isUserManaged());
metric.setWorstValue(dto.getWorstValue());
return metric;
}
}
}
| lgpl-3.0 |
ideaconsult/i5 | iuclid_5_5-io/src/main/java/eu/europa/echa/schemas/iuclid5/_20130101/studyrecord/EC_CHRONFISHTOX_SECTION/package-info.java | 602 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.15 at 10:52:33 PM EET
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://echa.europa.eu/schemas/iuclid5/20130101", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package eu.europa.echa.schemas.iuclid5._20130101.studyrecord.EC_CHRONFISHTOX_SECTION;
| lgpl-3.0 |
foyt/coops-sdk-java | src/main/java/fi/foyt/coops/model/Patch.java | 812 | package fi.foyt.coops.model;
import java.util.Map;
public class Patch {
public Long getRevisionNumber() {
return revisionNumber;
}
public void setRevisionNumber(Long revisionNumber) {
this.revisionNumber = revisionNumber;
}
public String getPatch() {
return patch;
}
public void setPatch(String patch) {
this.patch = patch;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
private Long revisionNumber;
private String patch;
private String algorithm;
private Map<String, String> properties;
}
| lgpl-3.0 |
denarie/Portofino | portofino-chart/src/main/java/com/manydesigns/portofino/pageactions/chart/jfreechart/JFreeChartAction.java | 15742 | /*
* Copyright (C) 2005-2017 ManyDesigns srl. All rights reserved.
* http://www.manydesigns.com/
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.manydesigns.portofino.pageactions.chart.jfreechart;
import com.manydesigns.elements.ElementsThreadLocals;
import com.manydesigns.elements.fields.Field;
import com.manydesigns.elements.forms.Form;
import com.manydesigns.elements.forms.FormBuilder;
import com.manydesigns.elements.messages.SessionMessages;
import com.manydesigns.elements.options.DefaultSelectionProvider;
import com.manydesigns.elements.options.SelectionProvider;
import com.manydesigns.elements.util.RandomUtil;
import com.manydesigns.portofino.buttons.annotations.Button;
import com.manydesigns.portofino.chart.ChartGenerator;
import com.manydesigns.portofino.di.Inject;
import com.manydesigns.portofino.logic.SelectionProviderLogic;
import com.manydesigns.portofino.model.database.Database;
import com.manydesigns.portofino.modules.DatabaseModule;
import com.manydesigns.portofino.pageactions.AbstractPageAction;
import com.manydesigns.portofino.pageactions.PageActionName;
import com.manydesigns.portofino.pageactions.annotations.ConfigurationClass;
import com.manydesigns.portofino.pageactions.annotations.ScriptTemplate;
import com.manydesigns.portofino.pageactions.chart.jfreechart.configuration.JFreeChartConfiguration;
import com.manydesigns.portofino.persistence.Persistence;
import com.manydesigns.portofino.security.AccessLevel;
import com.manydesigns.portofino.security.RequiresPermissions;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.util.UrlBuilder;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/*
* @author Paolo Predonzani - paolo.predonzani@manydesigns.com
* @author Angelo Lupo - angelo.lupo@manydesigns.com
* @author Giampiero Granatella - giampiero.granatella@manydesigns.com
* @author Alessio Stalla - alessio.stalla@manydesigns.com
*/
@RequiresPermissions(level = AccessLevel.VIEW)
@ScriptTemplate("script_template.groovy")
@ConfigurationClass(JFreeChartConfiguration.class)
@PageActionName("Chart (with JFreeChart)")
public class JFreeChartAction extends AbstractPageAction {
public static final String copyright =
"Copyright (C) 2005-2017 ManyDesigns srl";
//**************************************************************************
// Constants
//**************************************************************************
public static final String CHART_FILENAME_FORMAT = "chart-{0}.png";
//**************************************************************************
// Injections
//**************************************************************************
@Inject(DatabaseModule.PERSISTENCE)
public Persistence persistence;
//**************************************************************************
// Web parameters
//**************************************************************************
public String chartId;
public int width = 470;
public int height = 354;
public boolean antiAlias = true;
public boolean borderVisible = true;
//**************************************************************************
// Model metadata
//**************************************************************************
public JFreeChartConfiguration chartConfiguration;
//**************************************************************************
// Presentation elements
//**************************************************************************
public Form form;
public JFreeChart chart;
public JFreeChartInstance jfreeChartInstance;
public File file;
public static final Logger logger =
LoggerFactory.getLogger(JFreeChartAction.class);
//**************************************************************************
// Action default execute method
//**************************************************************************
@DefaultHandler
public Resolution execute() {
if(chartConfiguration == null) {
return forwardToPageActionNotConfigured();
}
try {
// Run/generate the chart
try {
Thread.currentThread().setContextClassLoader(Class.class.getClassLoader());
generateChart();
} finally {
Thread.currentThread().setContextClassLoader(JFreeChartAction.class.getClassLoader());
}
chartId = RandomUtil.createRandomId();
String actionurl = context.getActionPath();
UrlBuilder chartResolution =
new UrlBuilder(context.getLocale(), actionurl, false)
.addParameter("chartId", chartId)
.addParameter("chart", "");
String url = context.getRequest().getContextPath() + chartResolution.toString();
file = RandomUtil.getTempCodeFile(CHART_FILENAME_FORMAT, chartId);
jfreeChartInstance =
new JFreeChartInstance(chart, file, chartId, "Chart: " + chartConfiguration.getName(),
width, height, url);
} catch (Throwable e) {
logger.error("Chart exception", e);
return forwardToPageActionError(e);
}
return new ForwardResolution("/m/chart/jfreechart/display.jsp");
}
public void generateChart() {
ChartGenerator chartGenerator;
if(chartConfiguration.getGeneratorClass() == null) {
throw new IllegalStateException("Invalid chart type: " + chartConfiguration.getActualType());
}
try {
chartGenerator = chartConfiguration.getGeneratorClass().newInstance();
} catch (Exception e) {
throw new RuntimeException("Invalid generator for chart", e);
}
chartGenerator.setAntiAlias(antiAlias);
chartGenerator.setBorderVisible(borderVisible);
chartGenerator.setHeight(height);
chartGenerator.setWidth(width);
chart = chartGenerator.generate(chartConfiguration, persistence, context.getLocale());
}
public Resolution chart() throws FileNotFoundException {
final File file = RandomUtil.getTempCodeFile(CHART_FILENAME_FORMAT, chartId);
if(!file.exists()) {
return new ErrorResolution(404);
}
final InputStream inputStream = new FileInputStream(file);
//Cache the file, expire after 12h
int expiresAfter = 12 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
HttpServletResponse response = context.getResponse();
response.setHeader("Cache-Control", "max-age=" + expiresAfter);
response.setDateHeader("Last-Modified", now);
response.setDateHeader("Expires", now + expiresAfter);
response.setHeader("Pragma", "");
return new StreamingResolution("image/png", inputStream) {
@Override
protected void stream(HttpServletResponse response) throws Exception {
super.stream(response);
if(!file.delete()) {
logger.warn("Could not delete temporary file for chart: " + file.getAbsolutePath());
}
}
};
}
//**************************************************************************
// Configuration
//**************************************************************************
public static final String[][] CONFIGURATION_FIELDS =
{{"name", "type", "orientation", "legend", "database", "query", "urlExpression"}};
public static final String[] chartTypes1D = {
JFreeChartConfiguration.Type.PIE.name(),
JFreeChartConfiguration.Type.PIE3D.name(),
JFreeChartConfiguration.Type.RING.name()
};
public static final String[] chartTypes2D = {
JFreeChartConfiguration.Type.AREA.name(),
JFreeChartConfiguration.Type.BAR.name(),
JFreeChartConfiguration.Type.BAR3D.name(),
JFreeChartConfiguration.Type.LINE.name(),
JFreeChartConfiguration.Type.LINE3D.name(),
JFreeChartConfiguration.Type.STACKED_BAR.name(),
JFreeChartConfiguration.Type.STACKED_BAR_3D.name()
};
public final String[] chartTypeValues = new String[chartTypes1D.length + chartTypes2D.length + 2];
public final String[] chartTypeLabels = new String[chartTypeValues.length];
@Button(list = "pageHeaderButtons", titleKey = "configure", order = 1, icon = Button.ICON_WRENCH)
@RequiresPermissions(level = AccessLevel.DEVELOP)
public Resolution configure() {
prepareConfigurationForms();
return new ForwardResolution("/m/chart/jfreechart/configure.jsp");
}
@Override
protected void prepareConfigurationForms() {
super.prepareConfigurationForms();
String prefix = "com.manydesigns.portofino.jfreechart.type.";
chartTypeValues[0] = "--1D";
chartTypeLabels[0] = "-- 1D charts --";
for(int i = 0; i < chartTypes1D.length; i++) {
chartTypeValues[i + 1] = chartTypes1D[i];
chartTypeLabels[i + 1] = ElementsThreadLocals.getText(prefix + chartTypes1D[i], chartTypes1D[i]);
}
chartTypeValues[chartTypes1D.length + 1] = "--2D";
chartTypeLabels[chartTypes1D.length + 1] = "-- 2D charts --";
for(int i = 0; i < chartTypes2D.length; i++) {
chartTypeValues[i + 2 + chartTypes1D.length] = chartTypes2D[i];
chartTypeLabels[i + 2 + chartTypes1D.length] =
ElementsThreadLocals.getText(prefix + chartTypes2D[i], chartTypes2D[i]);
}
SelectionProvider databaseSelectionProvider =
SelectionProviderLogic.createSelectionProvider("database",
persistence.getModel().getDatabases(),
Database.class,
null,
new String[]{"databaseName"});
DefaultSelectionProvider typeSelectionProvider = new DefaultSelectionProvider("type");
for(int i = 0; i < chartTypeValues.length; i++) {
typeSelectionProvider.appendRow(chartTypeValues[i], chartTypeLabels[i], true);
}
String[] orientationValues =
{ JFreeChartConfiguration.Orientation.HORIZONTAL.name(), JFreeChartConfiguration.Orientation.VERTICAL.name() };
String[] orientationLabels = { "Horizontal", "Vertical" };
DefaultSelectionProvider orientationSelectionProvider = new DefaultSelectionProvider("orientation");
for(int i = 0; i < orientationValues.length; i++) {
orientationSelectionProvider.appendRow(orientationValues[i], orientationLabels[i], true);
}
form = new FormBuilder(JFreeChartConfiguration.class)
.configFields(CONFIGURATION_FIELDS)
.configFieldSetNames("Chart")
.configSelectionProvider(typeSelectionProvider, "type")
.configSelectionProvider(orientationSelectionProvider, "orientation")
.configSelectionProvider(databaseSelectionProvider, "database")
.build();
form.readFromObject(chartConfiguration);
}
@Button(list = "configuration", key = "update.configuration", order = 1, type = Button.TYPE_PRIMARY)
@RequiresPermissions(level = AccessLevel.DEVELOP)
public Resolution updateConfiguration() {
prepareConfigurationForms();
form.readFromObject(chartConfiguration);
form.readFromRequest(context.getRequest());
readPageConfigurationFromRequest();
boolean valid = form.validate();
valid = validatePageConfiguration() && valid;
Field typeField = form.findFieldByPropertyName("type");
String typeValue = typeField.getStringValue();
boolean placeHolderValue =
typeValue != null && typeValue.startsWith("--");
if(placeHolderValue) {
valid = false;
String errorMessage =
ElementsThreadLocals.getTextProvider().getText("elements.error.field.required");
typeField.getErrors().add(errorMessage);
SessionMessages.addErrorMessage("");
}
if (valid) {
updatePageConfiguration();
if(chartConfiguration == null) {
chartConfiguration = new JFreeChartConfiguration();
}
form.writeToObject(chartConfiguration);
saveConfiguration(chartConfiguration);
SessionMessages.addInfoMessage(ElementsThreadLocals.getText("configuration.updated.successfully"));
return cancel();
} else {
return new ForwardResolution("/m/chart/jfreechart/configure.jsp");
}
}
public Resolution preparePage() {
if(!pageInstance.getParameters().isEmpty()) {
return new ErrorResolution(404);
}
chartConfiguration = (JFreeChartConfiguration) pageInstance.getConfiguration();
return null;
}
//**************************************************************************
// Getter/setter
//**************************************************************************
public String getChartId() {
return chartId;
}
public void setChartId(String chartId) {
this.chartId = chartId;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public boolean isAntiAlias() {
return antiAlias;
}
public void setAntiAlias(boolean antiAlias) {
this.antiAlias = antiAlias;
}
public boolean isBorderVisible() {
return borderVisible;
}
public void setBorderVisible(boolean borderVisible) {
this.borderVisible = borderVisible;
}
public JFreeChartConfiguration getChartConfiguration() {
return chartConfiguration;
}
public void setChartConfiguration(JFreeChartConfiguration chartConfiguration) {
this.chartConfiguration = chartConfiguration;
}
public Form getForm() {
return form;
}
public void setForm(Form form) {
this.form = form;
}
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public JFreeChartInstance getJfreeChartInstance() {
return jfreeChartInstance;
}
public void setJfreeChartInstance(JFreeChartInstance jfreeChartInstance) {
this.jfreeChartInstance = jfreeChartInstance;
}
}
| lgpl-3.0 |
carterjohn21/LetsModReboot | src/main/java/com/carterjohn21/letsmodreboot/LetsModReboot.java | 1040 | package com.carterjohn21.letsmodreboot;
import com.carterjohn21.letsmodreboot.proxy.IProxy;
import com.carterjohn21.letsmodreboot.reference.Reference;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version=Reference.VERSION)
public class LetsModReboot
{
@Mod.Instance(Reference.MOD_ID)
public static LetsModReboot instance;
@SidedProxy(clientSide ="com.carterjohn21.letsmodreboot.proxy.ClientProxy",
serverSide ="com.carterjohn21.letsmodreboot.ServerProxy" )
public static IProxy proxy;
@Mod.EventHandler
void preinit(FMLPreInitializationEvent event)
{
}
@Mod.EventHandler
public void init(FMLInitializationEvent event)
{
}
@Mod.EventHandler
public void postinit(FMLPostInitializationEvent event)
{
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/types/BillingRateQueryRqTypeMetaDataType.java | 2605 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: BillingRateQueryRqTypeMetaDataType.java,v 1.1.1.1 2010-05-04 22:06:02 ryan Exp $
*/
package org.chocolate_milk.model.types;
/**
* Enumeration BillingRateQueryRqTypeMetaDataType.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:02 $
*/
public enum BillingRateQueryRqTypeMetaDataType {
//------------------/
//- Enum Constants -/
//------------------/
/**
* Constant NOMETADATA
*/
NOMETADATA("NoMetaData"),
/**
* Constant METADATAONLY
*/
METADATAONLY("MetaDataOnly"),
/**
* Constant METADATAANDRESPONSEDATA
*/
METADATAANDRESPONSEDATA("MetaDataAndResponseData");
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field value.
*/
private final java.lang.String value;
/**
* Field enumConstants.
*/
private static final java.util.Map<java.lang.String, BillingRateQueryRqTypeMetaDataType> enumConstants = new java.util.HashMap<java.lang.String, BillingRateQueryRqTypeMetaDataType>();
static {
for (BillingRateQueryRqTypeMetaDataType c: BillingRateQueryRqTypeMetaDataType.values()) {
BillingRateQueryRqTypeMetaDataType.enumConstants.put(c.value, c);
}
};
//----------------/
//- Constructors -/
//----------------/
private BillingRateQueryRqTypeMetaDataType(final java.lang.String value) {
this.value = value;
}
//-----------/
//- Methods -/
//-----------/
/**
* Method fromValue.
*
* @param value
* @return the constant for this value
*/
public static org.chocolate_milk.model.types.BillingRateQueryRqTypeMetaDataType fromValue(
final java.lang.String value) {
BillingRateQueryRqTypeMetaDataType c = BillingRateQueryRqTypeMetaDataType.enumConstants.get(value);
if (c != null) {
return c;
}
throw new IllegalArgumentException(value);
}
/**
*
*
* @param value
*/
public void setValue(
final java.lang.String value) {
}
/**
* Method toString.
*
* @return the value of this constant
*/
public java.lang.String toString(
) {
return this.value;
}
/**
* Method value.
*
* @return the value of this constant
*/
public java.lang.String value(
) {
return this.value;
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/TimeTrackingAddRqDescriptor.java | 3628 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: TimeTrackingAddRqDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.TimeTrackingAddRq;
/**
* Class TimeTrackingAddRqDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $
*/
public class TimeTrackingAddRqDescriptor extends org.chocolate_milk.model.descriptors.TimeTrackingAddRqTypeDescriptor {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public TimeTrackingAddRqDescriptor() {
super();
setExtendsWithoutFlatten(new org.chocolate_milk.model.descriptors.TimeTrackingAddRqTypeDescriptor());
_xmlName = "TimeTrackingAddRq";
_elementDefinition = true;
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
if (_identity == null) {
return super.getIdentity();
}
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.TimeTrackingAddRq.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
alta189/Plug | src/main/java/com/alta189/plug/exception/InvalidPluginException.java | 330 | package com.alta189.plug.exception;
public class InvalidPluginException extends Exception {
public InvalidPluginException(String message) {
super(message);
}
public InvalidPluginException(String message, Throwable cause) {
super(message, cause);
}
public InvalidPluginException(Throwable cause) {
super(cause);
}
}
| lgpl-3.0 |
cismet/watergis-client | src/main/java/de/cismet/watergis/gui/actions/map/ZoomInAction.java | 2257 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.watergis.gui.actions.map;
import org.apache.log4j.Logger;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.watergis.broker.AppBroker;
/**
* DOCUMENT ME!
*
* @author Gilles Baatz
* @version $Revision$, $Date$
*/
public class ZoomInAction extends AbstractAction {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(ZoomInAction.class);
//~ Constructors -----------------------------------------------------------
/**
* Creates a new CloseAction object.
*/
public ZoomInAction() {
final String tooltip = org.openide.util.NbBundle.getMessage(
ZoomInAction.class,
"ZoomInAction.toolTipText");
putValue(SHORT_DESCRIPTION, tooltip);
final String text = org.openide.util.NbBundle.getMessage(
ZoomInAction.class,
"ZoomInAction.text");
putValue(NAME, text);
final String mnemonic = org.openide.util.NbBundle.getMessage(
ZoomInAction.class,
"ZoomInAction.mnemonic");
putValue(MNEMONIC_KEY, KeyStroke.getKeyStroke(mnemonic).getKeyCode());
final ImageIcon icon = new javax.swing.ImageIcon(getClass().getResource(
"/de/cismet/watergis/res/icons16/icon-zoom-in.png"));
putValue(SMALL_ICON, icon);
}
//~ Methods ----------------------------------------------------------------
@Override
public void actionPerformed(final ActionEvent e) {
AppBroker.getInstance().simpleZoom(1.5f);
AppBroker.getInstance().switchMapMode(MappingComponent.ZOOM);
}
@Override
public boolean isEnabled() {
return true || AppBroker.getInstance().isActionsAlwaysEnabled();
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v61/AddErrorColumnsToCeActivityTest.java | 2691 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.platform.db.migration.version.v61;
import java.sql.SQLException;
import java.sql.Types;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.db.CoreDbTester;
import static java.lang.String.valueOf;
public class AddErrorColumnsToCeActivityTest {
private static final String TABLE = "CE_ACTIVITY";
@Rule
public CoreDbTester db = CoreDbTester.createForSchema(AddErrorColumnsToCeActivityTest.class, "old_ce_activity.sql");
@Rule
public ExpectedException expectedException = ExpectedException.none();
private AddErrorColumnsToCeActivity underTest = new AddErrorColumnsToCeActivity(db.database());
@Test
public void migration_adds_column_to_empty_table() throws SQLException {
underTest.execute();
verifyAddedColumns();
}
@Test
public void migration_adds_columns_to_populated_table() throws SQLException {
for (int i = 0; i < 9; i++) {
db.executeInsert(
TABLE,
"uuid", valueOf(i),
"task_type", "PROJECT",
"component_uuid", valueOf(i + 20),
"analysis_uuid", valueOf(i + 30),
"status", "ok",
"is_last", "true",
"is_last_key", "aa",
"submitted_at", valueOf(84654),
"created_at", valueOf(9512),
"updated_at", valueOf(45120));
}
underTest.execute();
verifyAddedColumns();
}
@Test
public void migration_is_not_reentrant() throws SQLException {
underTest.execute();
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Fail to execute ");
underTest.execute();
}
private void verifyAddedColumns() {
db.assertColumnDefinition(TABLE, "error_message", Types.VARCHAR, 1000, true);
db.assertColumnDefinition(TABLE, "error_stacktrace", Types.CLOB, null, true);
}
}
| lgpl-3.0 |
OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/engine/design/JRDesignPropertyExpression.java | 1870 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oss.pdfreporter.engine.design;
import org.oss.pdfreporter.engine.JRConstants;
import org.oss.pdfreporter.engine.JRExpression;
import org.oss.pdfreporter.engine.JRPropertyExpression;
import org.oss.pdfreporter.engine.base.JRBasePropertyExpression;
/**
* Implementation of {@link JRPropertyExpression} to be used at report
* design time.
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: JRDesignPropertyExpression.java 4595 2011-09-08 15:55:10Z teodord $
*/
public class JRDesignPropertyExpression extends JRBasePropertyExpression
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
/**
* Sets the property value expression.
*
* @param valueExpression the value expression
*/
public void setValueExpression(JRExpression valueExpression)
{
super.setValueExpression(valueExpression);
}
}
| lgpl-3.0 |
mapsforge/vtm | vtm/src/org/oscim/layers/tile/vector/VectorTileLoader.java | 9686 | /*
* Copyright 2012-2014 Hannes Janetzek
* Copyright 2016-2022 devemux86
*
* This file is part of the OpenScienceMap project (http://www.opensciencemap.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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.layers.tile.vector;
import org.oscim.core.GeometryBuffer.GeometryType;
import org.oscim.core.*;
import org.oscim.layers.tile.MapTile;
import org.oscim.layers.tile.TileLoader;
import org.oscim.renderer.bucket.*;
import org.oscim.theme.IRenderTheme;
import org.oscim.theme.RenderTheme;
import org.oscim.theme.styles.*;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.oscim.layers.tile.MapTile.State.LOADING;
public class VectorTileLoader extends TileLoader implements RenderStyle.Callback {
static final Logger log = LoggerFactory.getLogger(VectorTileLoader.class);
protected static final double STROKE_INCREASE = 1.4;
protected static final byte LAYERS = 11;
public static final byte STROKE_MIN_ZOOM = 12;
protected IRenderTheme renderTheme;
/**
* current TileDataSource used by this MapTileLoader
*/
protected ITileDataSource mTileDataSource;
/**
* currently processed MapElement
*/
protected MapElement mElement;
/**
* current line bucket (will be used for outline bucket)
*/
protected LineBucket mCurLineBucket;
/**
* Current bucket for adding elements
*/
protected int mCurBucket;
/**
* Line-scale-factor depending on zoom and latitude
*/
protected float mLineScale = 1.0f;
protected RenderBuckets mBuckets;
private final VectorTileLayer mTileLayer;
public VectorTileLoader(VectorTileLayer tileLayer) {
super(tileLayer.getManager());
mTileLayer = tileLayer;
}
@Override
public void dispose() {
if (mTileDataSource != null)
mTileDataSource.dispose();
}
@Override
public void cancel() {
if (mTileDataSource != null)
mTileDataSource.cancel();
}
@Override
public boolean loadTile(MapTile tile) {
if (mTileDataSource == null) {
log.error("no tile source is set");
return false;
}
renderTheme = mTileLayer.getTheme();
if (renderTheme == null) {
log.error("no theme is set");
return false;
}
//mTileLayer.getLoaderHooks();
/* account for area changes with latitude */
double lat = MercatorProjection.toLatitude(tile.y);
mLineScale = (float) Math.pow(STROKE_INCREASE, tile.zoomLevel - STROKE_MIN_ZOOM);
if (mLineScale < 1)
mLineScale = 1;
/* scale line width relative to latitude + PI * thumb */
mLineScale *= 0.4f + 0.6f * ((float) Math.sin(Math.abs(lat) * (Math.PI / 180)));
mBuckets = new RenderBuckets();
tile.data = mBuckets;
try {
/* query data source, which calls process() callback */
mTileDataSource.query(tile, this);
} catch (NullPointerException e) {
log.debug("NPE {} {}", tile, e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.debug("{} {}", tile, e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
@Override
public void completed(QueryResult result) {
boolean ok = (result == QueryResult.SUCCESS);
mTileLayer.callHooksComplete(mTile, ok);
/* finish buckets- tessellate and cleanup on worker-thread */
mBuckets.prepare();
clearState();
super.completed(result);
}
protected static int getValidLayer(int layer) {
if (layer < 0) {
return 0;
} else if (layer >= LAYERS) {
return LAYERS - 1;
} else {
return layer;
}
}
public void setDataSource(ITileDataSource dataSource) {
dispose();
mTileDataSource = dataSource;
}
static class TagReplacement {
public TagReplacement(String key) {
this.key = key;
this.tag = new Tag(key, null);
}
String key;
Tag tag;
}
/**
* Override this method to change tags that should be passed
* to {@link RenderTheme} matching.
* E.g. to replace tags that should not be cached in Rendertheme
*/
protected TagSet filterTags(TagSet tagSet) {
return tagSet;
}
@Override
public void process(MapElement element) {
if (isCanceled() || !mTile.state(LOADING))
return;
if (mTileLayer.callProcessHooks(mTile, mBuckets, element))
return;
TagSet tags = filterTags(element.tags);
if (tags == null)
return;
mElement = element;
/* get and apply render instructions */
if (element.type == GeometryType.POINT) {
renderNode(renderTheme.matchElement(element.type, tags, mTile.zoomLevel));
} else {
mCurBucket = getValidLayer(element.layer) * renderTheme.getLevels() * (element.level > 0 ? element.level : 1);
renderWay(renderTheme.matchElement(element.type, tags, mTile.zoomLevel));
}
clearState();
}
protected void renderWay(RenderStyle[] style) {
if (style == null)
return;
for (int i = 0, n = style.length; i < n; i++)
style[i].renderWay(this);
}
protected void renderNode(RenderStyle[] style) {
if (style == null)
return;
for (int i = 0, n = style.length; i < n; i++)
style[i].renderNode(this);
}
protected void clearState() {
mCurLineBucket = null;
mElement = null;
}
/***
* RenderThemeCallback
***/
@Override
public void renderWay(LineStyle line, int level) {
int nLevel = mCurBucket + level;
if (line.outline && mCurLineBucket == null) {
log.debug("missing line for outline! " + mElement.tags
+ " lvl:" + level + " layer:" + mElement.layer);
return;
}
//LineBucket lb;
if (line.stipple == 0 && line.texture == null) {
//lb = mBuckets.getLineBucket(nLevel);
// else
// lb = mBuckets.getLineTexBucket(nLevel);
LineBucket lb = mBuckets.getLineBucket(nLevel);
if (lb.line == null) {
lb.line = line;
lb.scale = line.fixed ? 1 : mLineScale;
lb.setExtents(-16, Tile.SIZE + 16);
}
if (line.outline) {
lb.addOutline(mCurLineBucket);
return;
}
lb.addLine(mElement);
/* keep reference for outline layer(s) */
//if (!(lb instanceof LineTexBucket))
mCurLineBucket = lb;
} else {
LineTexBucket lb = mBuckets.getLineTexBucket(nLevel);
if (lb.line == null) {
lb.line = line;
lb.scale = line.fixed ? 1 : mLineScale;
lb.setExtents(-16, Tile.SIZE + 16);
}
//if (lb.line == null) {
// lb.line = line;
// float w = line.width;
// if (!line.fixed)
// w *= mLineScale;
// lb.scale = w;
//}
lb.addLine(mElement);
}
}
/* slower to load (requires tesselation) and uses
* more memory but should be faster to render */
public static boolean USE_MESH_POLY = false;
@Override
public void renderArea(AreaStyle area, int level) {
/* dont add faded out polygon layers */
if (mTile.zoomLevel < area.fadeScale)
return;
int nLevel = mCurBucket + level;
mTileLayer.callThemeHooks(mTile, mBuckets, mElement, area, nLevel);
if (USE_MESH_POLY || area.mesh) {
MeshBucket mb = mBuckets.getMeshBucket(nLevel);
mb.area = area;
mb.addMesh(mElement);
} else {
PolygonBucket pb = mBuckets.getPolygonBucket(nLevel);
pb.area = area;
pb.addPolygon(mElement.points, mElement.index);
}
}
@Override
public void renderSymbol(SymbolStyle symbol) {
mTileLayer.callThemeHooks(mTile, mBuckets, mElement, symbol, 0);
}
@Override
public void renderExtrusion(ExtrusionStyle extrusion, int level) {
mTileLayer.callThemeHooks(mTile, mBuckets, mElement, extrusion, level);
}
@Override
public void renderCircle(CircleStyle circle, int level) {
int nLevel = mCurBucket + level;
CircleBucket cb = mBuckets.getCircleBucket(nLevel);
cb.circle = circle;
cb.addCircle(mElement);
}
@Override
public void renderText(TextStyle text) {
mTileLayer.callThemeHooks(mTile, mBuckets, mElement, text, 0);
}
}
| lgpl-3.0 |
OurGrid/OurGrid | src/test/java/org/ourgrid/acceptance/suites/Suite3_Peer_2.java | 1617 | /*
* Copyright (C) 2008 Universidade Federal de Campina Grande
*
* This file is part of OurGrid.
*
* OurGrid is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.ourgrid.acceptance.suites;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.ourgrid.acceptance.peer.Req_016_Test;
import org.ourgrid.acceptance.peer.Req_018_Test;
import org.ourgrid.acceptance.peer.Req_019_Test;
import org.ourgrid.acceptance.peer.Req_020_Test;
import org.ourgrid.acceptance.peer.Req_022_Test;
import org.ourgrid.acceptance.peer.Req_025_Test;
import org.ourgrid.acceptance.peer.Req_027_Test;
import org.ourgrid.acceptance.peer.Req_034_Test;
@RunWith(Suite.class)
@SuiteClasses({
Req_016_Test.class,
Req_018_Test.class,
Req_019_Test.class,
Req_020_Test.class,
Req_022_Test.class,
Req_025_Test.class,
Req_027_Test.class,
Req_034_Test.class
})
public class Suite3_Peer_2 {
}
| lgpl-3.0 |
racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/css/model/property/standard/FontMaxSize.java | 1633 | /*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: david.racodon@gmail.com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.css.model.property.standard;
import org.sonar.css.model.property.StandardProperty;
import org.sonar.css.model.property.validator.ValidatorFactory;
import org.sonar.css.model.property.validator.valueelement.IdentifierValidator;
public class FontMaxSize extends StandardProperty {
public FontMaxSize() {
setExperimental(true);
addLinks("https://drafts.csswg.org/css-fonts-4/#propdef-font-max-size");
addValidators(
new IdentifierValidator("xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"),
new IdentifierValidator("larger", "smaller"),
new IdentifierValidator("infinity"),
ValidatorFactory.getPositiveLengthValidator(),
ValidatorFactory.getPositivePercentageValidator());
}
}
| lgpl-3.0 |
nicosio2/Tourality | simpleplayer/Java/org/pixelgaffer/turnierserver/tourality/SimplePlayer.java | 1956 | /*
* SimplePlayer.java
*
* Copyright (C) 2015 Pixelgaffer
*
* This work 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 any later
* version.
*
* This work 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 version 2 and version 3 of the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pixelgaffer.turnierserver.tourality;
import java.awt.Point;
import java.util.Random;
import org.pixelgaffer.turnierserver.tourality.ai.*;
public class SimplePlayer extends TouralityAi {
//Dies ist der Konstruktor. Bitte modifiziere diesen nicht!
public SimplePlayer(String[] args) {
super(args);
}
private Random random = new Random();
//In dieser Methode machst du deinen Zug. Dir wird deine eigene Position, die Position des Gegners und das Spielfeld wie es momentan aussieht übergeben.
//Zurückgeben musst du die Richtung in die du dich bewegen willst, oder Richtung.STEHENBLEIBEN wenn du stehenbleiben willst.
@Override
public Richtung bewegen(Point du, Point gegner, Feld[][] spielfeld) {
return Richtung.values()[random.nextInt(Richtung.values().length)];
}
//Dies hier ist die main-Methode. Du kannst sie so lassen wie sie ist und unser Networking-zeugs verwenden, du kannst deine KI aber auch
//komplett selbst schreiben. Hierbei kannst du Ai.java in unserem GitHub-Repository als Vorbild nehmen. Falls du Verbesserungsvprschläge hast,
//bitten wir dich, einen pull-request zu erstellen-
public static void main(String[] args) {
new SimplePlayer(args).start();
}
}
| lgpl-3.0 |
seanbright/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_5_0/actions/ActionEndpoints_impl_ari_1_5_0.java | 5586 | package ch.loway.oss.ari4java.generated.ari_1_5_0.actions;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Jan 30 13:39:05 CET 2016
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import ch.loway.oss.ari4java.tools.BaseAriAction;
import ch.loway.oss.ari4java.tools.RestException;
import ch.loway.oss.ari4java.tools.AriCallback;
import ch.loway.oss.ari4java.tools.HttpParam;
import ch.loway.oss.ari4java.tools.HttpResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import ch.loway.oss.ari4java.generated.ari_1_5_0.models.*;
/**********************************************************
*
* Generated by: Apis
*********************************************************/
public class ActionEndpoints_impl_ari_1_5_0 extends BaseAriAction implements ActionEndpoints {
/**********************************************************
* Asterisk endpoints
*
* List all endpoints.
*********************************************************/
private void buildList() {
reset();
url = "/endpoints";
method = "GET";
}
@Override
public List<Endpoint> list() throws RestException {
buildList();
String json = httpActionSync();
return deserializeJsonAsAbstractList( json,
new TypeReference<List<Endpoint_impl_ari_1_5_0>>() {} );
}
@Override
public void list(AriCallback<List<Endpoint>> callback) {
buildList();
httpActionAsync(callback, new TypeReference<List<Endpoint_impl_ari_1_5_0>>() {});
}
/**********************************************************
* Send a message to some technology URI or endpoint.
*
* Send a message to some technology URI or endpoint.
*********************************************************/
private void buildSendMessage(String to, String from, String body, Map<String,String> variables) {
reset();
url = "/endpoints/sendMessage";
method = "PUT";
lParamQuery.add( HttpParam.build( "to", to) );
lParamQuery.add( HttpParam.build( "from", from) );
lParamQuery.add( HttpParam.build( "body", body) );
lE.add( HttpResponse.build( 404, "Endpoint not found") );
}
@Override
public void sendMessage(String to, String from, String body, Map<String,String> variables) throws RestException {
buildSendMessage(to, from, body, variables);
String json = httpActionSync();
}
@Override
public void sendMessage(String to, String from, String body, Map<String,String> variables, AriCallback<Void> callback) {
buildSendMessage(to, from, body, variables);
httpActionAsync(callback);
}
/**********************************************************
* Asterisk endpoints
*
* List available endoints for a given endpoint technology.
*********************************************************/
private void buildListByTech(String tech) {
reset();
url = "/endpoints/" + tech + "";
method = "GET";
lE.add( HttpResponse.build( 404, "Endpoints not found") );
}
@Override
public List<Endpoint> listByTech(String tech) throws RestException {
buildListByTech(tech);
String json = httpActionSync();
return deserializeJsonAsAbstractList( json,
new TypeReference<List<Endpoint_impl_ari_1_5_0>>() {} );
}
@Override
public void listByTech(String tech, AriCallback<List<Endpoint>> callback) {
buildListByTech(tech);
httpActionAsync(callback, new TypeReference<List<Endpoint_impl_ari_1_5_0>>() {});
}
/**********************************************************
* Single endpoint
*
* Details for an endpoint.
*********************************************************/
private void buildGet(String tech, String resource) {
reset();
url = "/endpoints/" + tech + "/" + resource + "";
method = "GET";
lE.add( HttpResponse.build( 400, "Invalid parameters for sending a message.") );
lE.add( HttpResponse.build( 404, "Endpoints not found") );
}
@Override
public Endpoint get(String tech, String resource) throws RestException {
buildGet(tech, resource);
String json = httpActionSync();
return deserializeJson( json, Endpoint_impl_ari_1_5_0.class );
}
@Override
public void get(String tech, String resource, AriCallback<Endpoint> callback) {
buildGet(tech, resource);
httpActionAsync(callback, Endpoint_impl_ari_1_5_0.class);
}
/**********************************************************
* Send a message to some endpoint in a technology.
*
* Send a message to some endpoint in a technology.
*********************************************************/
private void buildSendMessageToEndpoint(String tech, String resource, String from, String body, Map<String,String> variables) {
reset();
url = "/endpoints/" + tech + "/" + resource + "/sendMessage";
method = "PUT";
lParamQuery.add( HttpParam.build( "from", from) );
lParamQuery.add( HttpParam.build( "body", body) );
lE.add( HttpResponse.build( 400, "Invalid parameters for sending a message.") );
lE.add( HttpResponse.build( 404, "Endpoint not found") );
}
@Override
public void sendMessageToEndpoint(String tech, String resource, String from, String body, Map<String,String> variables) throws RestException {
buildSendMessageToEndpoint(tech, resource, from, body, variables);
String json = httpActionSync();
}
@Override
public void sendMessageToEndpoint(String tech, String resource, String from, String body, Map<String,String> variables, AriCallback<Void> callback) {
buildSendMessageToEndpoint(tech, resource, from, body, variables);
httpActionAsync(callback);
}
/** No missing signatures from interface */
};
| lgpl-3.0 |
sing-group/aibench-project | aibench-core/src/main/java/es/uvigo/ei/aibench/core/datatypes/annotation/Property.java | 1252 | /*
* #%L
* The AIBench Core Plugin
* %%
* Copyright (C) 2006 - 2017 Daniel Glez-Peña and Florentino Fdez-Riverola
* %%
* 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 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General 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-3.0.html>.
* #L%
*/
package es.uvigo.ei.aibench.core.datatypes.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Daniel Glez-Peña
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface Property {
String name() default "";
}
| lgpl-3.0 |
bartcharbon/molgenis | molgenis-data-security/src/main/java/org/molgenis/data/security/auth/GroupService.java | 8535 | package org.molgenis.data.security.auth;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Objects.requireNonNull;
import static org.molgenis.data.meta.model.PackageMetadata.PACKAGE;
import static org.molgenis.data.security.auth.RoleMetadata.ROLE;
import static org.molgenis.security.core.SidUtils.createRoleAuthority;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.molgenis.data.DataService;
import org.molgenis.data.Fetch;
import org.molgenis.data.UnknownEntityException;
import org.molgenis.data.meta.model.Package;
import org.molgenis.data.meta.model.PackageFactory;
import org.molgenis.data.meta.model.PackageMetadata;
import org.molgenis.data.security.exception.IsAlreadyMemberException;
import org.molgenis.data.security.exception.NotAValidGroupRoleException;
import org.molgenis.data.security.permission.RoleMembershipService;
import org.molgenis.security.core.model.GroupValue;
import org.molgenis.security.core.runas.RunAsSystem;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class GroupService {
private final DataService dataService;
private final PackageFactory packageFactory;
private final GroupMetadata groupMetadata;
private final RoleMembershipService roleMembershipService;
private final RoleMembershipMetadata roleMembershipMetadata;
public static final String MANAGER = "Manager";
public static final String EDITOR = "Editor";
public static final String VIEWER = "Viewer";
public static final String AUTHORITY_MANAGER = createRoleAuthority(MANAGER.toUpperCase());
public static final String AUTHORITY_EDITOR = createRoleAuthority(EDITOR.toUpperCase());
public static final String AUTHORITY_VIEWER = createRoleAuthority(VIEWER.toUpperCase());
public static final Set<String> DEFAULT_ROLES = ImmutableSet.of(MANAGER, EDITOR, VIEWER);
@SuppressWarnings("squid:S00107")
GroupService(
PackageFactory packageFactory,
DataService dataService,
GroupMetadata groupMetadata,
RoleMembershipService roleMembershipService,
RoleMembershipMetadata roleMembershipMetadata) {
this.packageFactory = requireNonNull(packageFactory);
this.dataService = requireNonNull(dataService);
this.groupMetadata = requireNonNull(groupMetadata);
this.roleMembershipService = requireNonNull(roleMembershipService);
this.roleMembershipMetadata = requireNonNull(roleMembershipMetadata);
}
/**
* Creates {@link Group}, {@link Role} and {@link Package} entities and adds them to the
* dataService.
*
* @param groupValue details of the group that should be created
*/
@Transactional
public void persist(GroupValue groupValue) {
Package rootPackage = packageFactory.create(groupValue.getRootPackage());
dataService.add(PACKAGE, rootPackage);
}
@RunAsSystem
public Collection<Group> getGroups() {
return dataService.findAll(GroupMetadata.GROUP, Group.class).collect(Collectors.toList());
}
/**
* Get the group entity by its unique name.
*
* @param groupName unique group name
* @return group with given name
* @throws UnknownEntityException in case no group with given name can be retrieved
*/
@RunAsSystem
public Group getGroup(String groupName) {
Fetch roleFetch = new Fetch().field(RoleMetadata.NAME).field(RoleMetadata.LABEL);
Fetch fetch =
new Fetch()
.field(GroupMetadata.ROLES, roleFetch)
.field(GroupMetadata.NAME)
.field(GroupMetadata.LABEL)
.field(GroupMetadata.DESCRIPTION)
.field(GroupMetadata.ID)
.field(GroupMetadata.PUBLIC)
.field(GroupMetadata.ROOT_PACKAGE);
Group group =
dataService
.query(GroupMetadata.GROUP, Group.class)
.eq(GroupMetadata.NAME, groupName)
.fetch(fetch)
.findOne();
if (group == null) {
throw new UnknownEntityException(
groupMetadata, groupMetadata.getAttribute(GroupMetadata.NAME), groupName);
}
return group;
}
/**
* Add member to group. User can only be added to a role that belongs to the group. The user can
* only have a single role within the group
*
* @param group group to add the user to in the given role
* @param user user to be added in the given role to the given group
* @param role role in which the given user is to be added to given group
*/
@RunAsSystem
public void addMember(final Group group, final User user, final Role role) {
ArrayList<Role> groupRoles = newArrayList(group.getRoles());
Collection<RoleMembership> memberships = roleMembershipService.getMemberships(groupRoles);
boolean isGroupRole = isGroupRole(role, groupRoles);
if (!isGroupRole) {
throw new NotAValidGroupRoleException(role, group);
}
boolean isMember = memberships.stream().parallel().anyMatch(m -> m.getUser().equals(user));
if (isMember) {
throw new IsAlreadyMemberException(user, group);
}
roleMembershipService.addUserToRole(user, role);
}
private boolean isGroupRole(Role role, ArrayList<Role> groupRoles) {
return groupRoles.stream().anyMatch(groupRole -> groupRole.getName().equals(role.getName()));
}
@RunAsSystem
public void removeMember(final Group group, final User user) {
ArrayList<Role> groupRoles = newArrayList(group.getRoles());
final RoleMembership membership = findRoleMembership(user, groupRoles);
roleMembershipService.removeMembership(membership);
}
@RunAsSystem
public void updateMemberRole(final Group group, final User member, final Role newRole) {
ArrayList<Role> groupRoles = newArrayList(group.getRoles());
boolean isGroupRole = isGroupRole(newRole, groupRoles);
if (!isGroupRole) {
throw new NotAValidGroupRoleException(newRole, group);
}
final RoleMembership roleMembership = findRoleMembership(member, groupRoles);
roleMembershipService.updateMembership(roleMembership, newRole);
}
@RunAsSystem
public boolean isGroupNameAvailable(final GroupValue groupValue) {
String rootPackageName = groupValue.getRootPackage().getName();
final Package existingPackage =
dataService.query(PACKAGE, Package.class).eq(PackageMetadata.ID, rootPackageName).findOne();
return existingPackage == null;
}
private UnknownEntityException unknownMembershipForUser(User user) {
return new UnknownEntityException(
roleMembershipMetadata,
roleMembershipMetadata.getAttribute(RoleMembershipMetadata.USER),
user.getUsername());
}
private RoleMembership findRoleMembership(User member, List<Role> groupRoles) {
Collection<RoleMembership> memberships = roleMembershipService.getMemberships(groupRoles);
return memberships.stream()
.filter(m -> m.getUser().getId().equals(member.getId()))
.findFirst()
.orElseThrow(() -> unknownMembershipForUser(member));
}
public void deleteGroup(String groupName) {
Group group =
dataService
.query(GroupMetadata.GROUP, Group.class)
.eq(GroupMetadata.NAME, groupName)
.findOne();
if (group == null) {
throw new UnknownEntityException(
groupMetadata, groupMetadata.getAttribute(GroupMetadata.NAME), groupName);
}
dataService.delete(PACKAGE, group.getRootPackage());
}
public void updateExtendsRole(Group group, Role groupRole, Role memberRole) {
List<Role> newIncludes = removeIncludedGroupRoles(group, memberRole);
if (!isGroupRole(groupRole, newArrayList(group.getRoles()))) {
throw new NotAValidGroupRoleException(groupRole, group);
}
newIncludes.add(groupRole);
memberRole.setIncludes(newIncludes);
dataService.update(ROLE, memberRole);
}
public void removeExtendsRole(Group group, Role memberRole) {
List<Role> newIncludes = removeIncludedGroupRoles(group, memberRole);
memberRole.setIncludes(newIncludes);
dataService.update(ROLE, memberRole);
}
private List<Role> removeIncludedGroupRoles(Group group, Role memberRole) {
ArrayList<Role> includes = newArrayList(memberRole.getIncludes());
ArrayList<Role> groupRoles = newArrayList(group.getRoles());
return includes.stream()
.filter(role -> !isGroupRole(role, groupRoles))
.collect(Collectors.toList());
}
}
| lgpl-3.0 |
aoindustries/aoserv-client | src/main/java/com/aoindustries/aoserv/client/email/CyrusImapdBind.java | 5876 | /*
* aoserv-client - Java client for the AOServ Platform.
* Copyright (C) 2017, 2018, 2019, 2021 AO Industries, Inc.
* support@aoindustries.com
* 7262 Bull Pen Cir
* Mobile, AL 36695
*
* This file is part of aoserv-client.
*
* aoserv-client 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.
*
* aoserv-client 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 aoserv-client. If not, see <https://www.gnu.org/licenses/>.
*/
package com.aoindustries.aoserv.client.email;
import com.aoapps.hodgepodge.io.stream.StreamableInput;
import com.aoapps.hodgepodge.io.stream.StreamableOutput;
import com.aoapps.lang.validation.ValidationException;
import com.aoapps.net.DomainName;
import com.aoindustries.aoserv.client.CachedObjectIntegerKey;
import com.aoindustries.aoserv.client.net.Bind;
import com.aoindustries.aoserv.client.pki.Certificate;
import com.aoindustries.aoserv.client.schema.AoservProtocol;
import com.aoindustries.aoserv.client.schema.Table;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;
/**
* Each <code>CyrusImapdServer</code> may listen for network connections on
* multiple <code>NetBind</code>s. A <code>CyrusImapdBind</code> ties
* <code>CyrusImapdServer</code>s to <code>NetBinds</code>.
*
* @see CyrusImapdServer
* @see Bind
*
* @author AO Industries, Inc.
*/
public final class CyrusImapdBind extends CachedObjectIntegerKey<CyrusImapdBind> {
static final int
COLUMN_NET_BIND = 0,
COLUMN_CYRUS_IMAPD_SERVER = 1,
COLUMN_SSL_CERTIFICATE = 3
;
static final String COLUMN_NET_BIND_name = "net_bind";
private int cyrus_imapd_server;
private DomainName servername;
private int certificate;
private Boolean allowPlaintextAuth;
/**
* @deprecated Only required for implementation, do not use directly.
*
* @see #init(java.sql.ResultSet)
* @see #read(com.aoapps.hodgepodge.io.stream.StreamableInput, com.aoindustries.aoserv.client.schema.AoservProtocol.Version)
*/
@Deprecated/* Java 9: (forRemoval = true) */
public CyrusImapdBind() {
// Do nothing
}
@Override
public String toStringImpl() throws SQLException, IOException {
CyrusImapdServer server = getCyrusImapdServer();
Bind bind = getNetBind();
return server.toStringImpl() + '|' + bind.toStringImpl();
}
@Override
protected Object getColumnImpl(int i) {
switch(i) {
case COLUMN_NET_BIND: return pkey;
case COLUMN_CYRUS_IMAPD_SERVER: return cyrus_imapd_server;
case 2: return servername;
case COLUMN_SSL_CERTIFICATE: return certificate == -1 ? null : certificate;
case 4: return allowPlaintextAuth;
default: throw new IllegalArgumentException("Invalid index: " + i);
}
}
@Override
public Table.TableID getTableID() {
return Table.TableID.CYRUS_IMAPD_BINDS;
}
@Override
public void init(ResultSet result) throws SQLException {
try {
int pos = 1;
pkey = result.getInt(pos++);
cyrus_imapd_server = result.getInt(pos++);
servername = DomainName.valueOf(result.getString(pos++));
certificate = result.getInt(pos++);
if(result.wasNull()) certificate = -1;
allowPlaintextAuth = result.getBoolean(pos++);
if(result.wasNull()) allowPlaintextAuth = null;
} catch(ValidationException e) {
throw new SQLException(e);
}
}
@Override
public void read(StreamableInput in, AoservProtocol.Version protocolVersion) throws IOException {
try {
pkey = in.readCompressedInt();
cyrus_imapd_server = in.readCompressedInt();
servername = DomainName.valueOf(in.readNullUTF());
certificate = in.readCompressedInt();
allowPlaintextAuth = in.readNullBoolean();
} catch(ValidationException e) {
throw new IOException(e);
}
}
@Override
public void write(StreamableOutput out, AoservProtocol.Version protocolVersion) throws IOException {
out.writeCompressedInt(pkey);
out.writeCompressedInt(cyrus_imapd_server);
out.writeNullUTF(Objects.toString(servername, null));
out.writeCompressedInt(certificate);
out.writeNullBoolean(allowPlaintextAuth);
}
public Bind getNetBind() throws SQLException, IOException {
Bind obj = table.getConnector().getNet().getBind().get(pkey);
if(obj == null) throw new SQLException("Unable to find NetBind: " + pkey);
return obj;
}
public CyrusImapdServer getCyrusImapdServer() throws SQLException, IOException {
CyrusImapdServer obj = table.getConnector().getEmail().getCyrusImapdServer().get(cyrus_imapd_server);
if(obj == null) throw new SQLException("Unable to find CyrusImapd: " + cyrus_imapd_server);
return obj;
}
/**
* The fully qualified hostname for <code>servername</code>.
*
* When {@code null}, defaults to {@link CyrusImapdServer#getServername()}.
*/
public DomainName getServername() {
return servername;
}
/**
* Gets the SSL certificate for this server.
*
* @return the SSL certificate or {@code null} when filtered or defaulting to {@link CyrusImapdServer#getCertificate()}
*/
public Certificate getCertificate() throws SQLException, IOException {
if(certificate == -1) return null;
// May be filtered
return table.getConnector().getPki().getCertificate().get(certificate);
}
/**
* Allows plaintext authentication (PLAIN/LOGIN) on non-TLS links.
*
* When {@code null}, defaults to {@link CyrusImapdServer#getAllowPlaintextAuth()}.
*/
public Boolean getAllowPlaintextAuth() {
return allowPlaintextAuth;
}
}
| lgpl-3.0 |
nelt/poomjobs | poomjobs-engine-in-memory/src/test/java/org/codingmatters/poomjobs/engine/inmemory/acceptance/list/InMemoryJobListServiceAcceptanceTest.java | 936 | package org.codingmatters.poomjobs.engine.inmemory.acceptance.list;
import org.codingmatters.poomjobs.apis.TestConfigurationProvider;
import org.codingmatters.poomjobs.apis.list.JobListServiceAcceptanceTest;
import org.codingmatters.poomjobs.engine.inmemory.acceptance.InMemoryConfigurationProvider;
import org.codingmatters.poomjobs.engine.inmemory.InMemoryEngine;
import org.junit.After;
import org.junit.Rule;
/**
* Created by nel on 06/07/15.
*/
public class InMemoryJobListServiceAcceptanceTest extends JobListServiceAcceptanceTest {
@Rule
public InMemoryConfigurationProvider configurationProvider = new InMemoryConfigurationProvider();
@Override
protected TestConfigurationProvider getConfigurationProvider() {
return this.configurationProvider;
}
@After
public void tearDown() throws Exception {
InMemoryEngine.removeEngine(this.configurationProvider.getQueueConfig());
}
} | lgpl-3.0 |
Poesys-Associates/dataloader | dataloader/src/com/poesys/accounting/dataloader/oldaccounting/OldDataBuilder.java | 50763 | /*
* Copyright (c) 2018 Poesys Associates. All rights reserved.
*
* This file is part of Poesys/Dataloader.
*
* Poesys/Dataloader 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.
*
* Poesys/Dataloader 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
* Poesys/Dataloader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.poesys.accounting.dataloader.oldaccounting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.poesys.accounting.dataloader.newaccounting.*;
import org.apache.log4j.Logger;
import com.poesys.accounting.dataloader.IBuilder;
import com.poesys.accounting.dataloader.properties.IParameters;
import com.poesys.db.InvalidParametersException;
/**
* Production implementation of the IBuilder interface that loads data from a designated path for a
* list of fiscal years.
*
* @author Robert J. Muller
*/
public class OldDataBuilder implements IBuilder {
/** logger for this class */
private static final Logger logger = Logger.getLogger(OldDataBuilder.class);
/** the program parameters object */
private final IParameters parameters;
/** the fiscal year being built */
private FiscalYear fiscalYear;
/** the list of all fiscal years built so far */
private List<FiscalYear> fiscalYears = new ArrayList<>();
/** the set of transactions built from the data */
private final Set<com.poesys.accounting.dataloader.newaccounting.Transaction> transactions =
new HashSet<>();
/**
* the set of transactions for the current fiscal year; this gets cleared when each fiscal year
* starts processing. This set exists to enable easier debugging of the transaction list, which
* can get very large. The list for a specific year is much smaller, so you can more easily
* inspect it in the debugger. The variable is not used elsewhere and has no accessors.
*/
private final Set<com.poesys.accounting.dataloader.newaccounting.Transaction>
currentTransactions = new HashSet<>();
// operational constants
/** limit on number of rows from file, prevents infinite loop */
private static final int LIMIT = 10000;
/**
* integer id for the start of the integer id series for balance transactions, because the old
* accounting system doesn't actually have transaction ids for these transactions
*/
private static final String FIRST_BALANCE_TRANSACTION_ID = "100000";
// Data sets shared across process iterations
/** the capital entities for the accounting entity accounts */
private CapitalStructure capitalStructure;
/** map of capital entities indexed by capital/distribution account names */
private Map<String, CapitalEntity> capitalEntityMap = new HashMap<>();
/** the map of shared sets of account groups indexed by fiscal year */
private final Map<FiscalYear, Set<com.poesys.accounting.dataloader.newaccounting.AccountGroup>>
groupSetsMap = new HashMap<>();
/** the shared set of accounts */
private final Set<com.poesys.accounting.dataloader.newaccounting.Account> accounts =
new HashSet<>();
// Messages
private static final String ZERO_RECEIVABLE_ID_ERROR =
"zero receivable id for transaction not in first year";
private static final String NO_BALANCE_ERROR = "no balance for receivable account ";
private static final String ZERO_BALANCE_ERROR = "zero balance for account ";
private static final String ACCOUNT_ERROR = "cannot find account ";
private static final String NULL_FILE_PATH_ERROR = "Null file path in parameter file";
private static final String FILE_READER_CLOSE_ERROR = "IO exception closing file reader";
private static final String READER_CLOSE_ERROR = "IO exception closing buffered reader";
private static final String GROUP_LOOKUP_ERROR = "cannot find group for account ";
private static final String NULL_PARAMETER_ERROR = "parameters required but are null";
private static final String NULL_INCOME_SUMMARY_ERROR =
"Null income summary account name in parameter file";
private static final String NO_SUCH_TRANSACTION_ERROR = "no such transaction ";
private static final String NO_SUCH_ACCOUNT_ERROR = "no such account ";
private static final String FISCAL_YEAR_ERROR = " in fiscal year ";
private static final String INVALID_TRANSACTION_ERROR = "invalid transaction: ";
private static final String INVALID_TRANSACTIONS_ERROR = "invalid transactions";
private static final String NO_REIMBURSEMENTS_ITEM_MAP_ERROR =
"no reimbursements item map for fiscal year ";
private static final String NO_RECEIVABLES_ITEM_MAP_ERROR =
"no receivables item map for fiscal year ";
private static final String NOT_RECEIVABLE_ACCOUNT_ERROR =
"indexing receivable item but account is not a receivable account: ";
private static final String INVALID_CAPITAL_ACCOUNT =
"found account name in map but no such account name in capital structure: ";
private static final String NO_NEW_CAPITAL_ENTITY_NAME_ERROR = "no new capital entity name";
private static final String NO_CAPITAL_ENTITY_NAME_ERROR = "no capital entity name";
private static final String NO_ACCOUNT_NAME_ERROR = "no name for lookup of account";
// lookup maps and index classes
/**
* lookup map that contains new-accounting groups indexed by old-accounting year and account
* intervals
*/
private final Map<AccountGroup, com.poesys.accounting.dataloader.newaccounting.AccountGroup>
groupMap = new HashMap<>();
/** map that organizes groups by account type for numbering */
private final Map<AccountType, List<AccountGroup>> typeMap = new HashMap<>();
/**
* lookup map that translates account numbers to new-accounting account names; permits mapping of
* incoming accounts for the current fiscal year to existing accounts from prior fiscal years by
* name mapping
*/
private final Map<Integer, String> accountMap = new HashMap<>();
/**
* lookup map that translates account numbers to new accounts; this provides a way to get the
* account name for balance transactions to use as a transaction description; cleared by
* buildFiscalYear()
*/
private final Map<Integer, com.poesys.accounting.dataloader.newaccounting.Account>
accountNumberMap = new HashMap<>();
/**
* lookup map that translates account names to new accounts; this provides a way to get the
* account object based on the name; cleared by buildFiscalYear()
*/
private final Map<String, com.poesys.accounting.dataloader.newaccounting.Account> accountNameMap =
new HashMap<>();
/**
* lookup map that translates an old transaction id into a new-accounting transaction object; this
* provides a way to map items to transactions; cleared by buildFiscalYear()
*/
private final Map<Integer, com.poesys.accounting.dataloader.newaccounting.Transaction>
transactionMap = new HashMap<>();
/**
* Map index object that indexes items by a combination of transaction id and account; used in
* item lookup maps for receivables
*/
private class ItemIndex {
private final Integer id;
private final Float accountNumber;
/**
* Create a ItemIndex object.
*
* @param id the transaction id
* @param accountNumber the account number (float, for example 111.1)
*/
public ItemIndex(Integer id, Float accountNumber) {
this.id = id;
this.accountNumber = accountNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ItemIndex other = (ItemIndex)obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (accountNumber == null) {
if (other.accountNumber != null) {
return false;
}
} else if (!accountNumber.equals(other.accountNumber)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
private OldDataBuilder getOuterType() {
return OldDataBuilder.this;
}
}
/**
* the shared lookup map of fiscal year maps of receivable items indexed by year, then by the
* ItemIndex combination of transaction id and account (that is, Map(year, Map(itemIndex, item));
* the buildFiscalYear() method initializes the nested map for the year
*/
private final Map<Integer, Map<ItemIndex, com.poesys.accounting.dataloader.newaccounting.Item>>
receivablesMap = new HashMap<>();
/**
* the shared lookup map of fiscal year maps of reimbursing items indexed by year, then by the
* ItemIndex combination of transaction id and account (that is, Map(year, Map(itemIndex, item));
* the buildFiscalYear() method initializes the nested map for the year
*/
private final Map<Integer, Map<ItemIndex, com.poesys.accounting.dataloader.newaccounting.Item>>
reimbursementsMap = new HashMap<>();
// list of capital entities read directly
private final List<CapitalEntity> entities = new ArrayList<>();
// sets of the data read directly; cleared by buildFiscalYear()
private final Set<Reimbursement> reimbursementDataSet = new HashSet<>();
private final Set<Balance> balanceDataSet = new HashSet<>();
private final Set<Transaction> transactionDataSet = new HashSet<>();
private final Set<Item> itemDataSet = new HashSet<>();
/**
* Strategy pattern that allows the Builder to share the basic file-reading code, putting the
* construction-specific work into each strategy class. Each strategy builds all the data sets
* that can be built a line at a time. The interface is publicly accessible for unit testing.
*/
public interface IBuildStrategy {
/**
* Strategy execution method, builds the target DTOs using the input data from the reader
*
* @param r the reader pointing to input data
*/
void build(BufferedReader r);
}
/**
* A capital entity is a named entity that owns some part of the capital of the accounting system.
* Each system has one or more entities with accompanying capital and distribution accounts.
*/
private class CapitalEntityStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
CapitalEntity entity = new CapitalEntity(r);
entities.add(entity);
}
}
/**
* The system groups accounts into categories (Cash, Credit Cards, and so on) that grouped
* accounts by number; each group had a range of accounts, always from nn0.00 to nn9.99, so groups
* had "ten" accounts (plus some number of sub-accounts). The old accounting system had a set of
* account groups for each year that included all the accounts in the year. The groups could be
* rearranged from year to year (a group added, a group removed, or a group changed (that is, the
* account number range would be associated with a different group name. The new system identifies
* groups within account types ("Assets", "Liabilities" and so on) by name, so names are unique
* within account type across all years. The Old Data Builder must therefore map groups into
* new-accounting groups when creating fiscal-year-account links between accounts and fiscal
* years, which is where groups associate with accounts and years. Also, to get the order number
* of the group within the account type, the builder builds a data structure containing ordered
* lists of groups indexed by account type. This operation builds the lists but leaves the
* ordering and numbering to the client.
*/
private class AccountGroupStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
AccountGroup group = new AccountGroup(fiscalYear.getYear(), r);
// Create new group, add to set for fiscal year
com.poesys.accounting.dataloader.newaccounting.AccountGroup newGroup =
new com.poesys.accounting.dataloader.newaccounting.AccountGroup(group.getName());
Set<com.poesys.accounting.dataloader.newaccounting.AccountGroup> groupSet =
groupSetsMap.computeIfAbsent(fiscalYear, k -> new HashSet<>());
// No set yet, create it.
// Add the group to the set.
groupSet.add(newGroup);
// Add new group to map indexed by old group
groupMap.put(group, newGroup);
// Add the group to the account type.
AccountType type = group.getAccountType();
List<AccountGroup> groupList = typeMap.computeIfAbsent(type, k -> new ArrayList<>());
// no list yet for this type, create one
// Add the group to the list. Note the list is not sorted at this point.
groupList.add(group);
}
}
/**
* The old accounting system was implemented separately for each fiscal year, allowing for changes
* to the account name and the changing of account numbers from year to year. The account map
* associates a particular new-accounting name with an account number in a given year and later
* years. The buildFiscalYear() method does not clear the account map. The data file for a given
* fiscal year thus contains one row for each account number that represents a specific account
* shifted to that number from the prior year. Later years will associate that number to that name
* unless the account map in the subsequent year replaces the name with another name. You only
* need to set the account number once for all subsequent years.
*/
private class AccountMapStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
// Read the map data and store in the map.
AccountMap map = new AccountMap(r);
// Convert account number from float to int, e.g., 100.21 -> 10021.
Integer accountNumber = new Float(map.getAccountNumber() * 100F).intValue();
accountMap.put(accountNumber, map.getName());
}
}
/**
* Accounts in the old system had unique account numbers with two parts separated by a decimal
* point, which represented the main account and sub-accounts. These accounts were distinct for
* each fiscal year, and this introduced the need to map from account number to account number
* across fiscal years for balance sheet accounts. It also made comparing accounts across years
* impossible. The new accounting system dispenses with the account numbers and the concept of
* sub-accounts and just identifies an account by its name, and the account may be active or
* inactive in a given fiscal year but applies to all fiscal years. This requires using a mapping
* file to determine the account mapping. At the end of the account build() process step, the
* accounts set reflects the unified set of accounts across all fiscal years read so far. The
* account map, which maps account numbers to new accounts, represents the accounts in the current
* fiscal year. Any account in the accounts set that is not mapped in the account map is not
* active in the current fiscal year, meaning there is no FiscalYearAccount link between the
* account and the FiscalYear in the database.
*/
private class AccountStrategy implements IBuildStrategy {
/** Tracks account order number within groups */
Map<com.poesys.accounting.dataloader.newaccounting.AccountGroup, Integer>
groupAccountOrderNumbers = new HashMap<>();
@Override
public void build(BufferedReader r) {
Integer year = fiscalYear.getYear();
Account oldAccount = new Account(fiscalYear.getYear(), r);
// Convert account number to 5-digit integer for comparisons
Float accountNumber = oldAccount.getAccountNumber();
Integer intAccountNumber = new Float(accountNumber * 100F).intValue();
// Determine whether the account is a receivable account.
Boolean receivable = intAccountNumber >= 11000 && intAccountNumber < 12000;
// Get the account group for the account.
com.poesys.accounting.dataloader.newaccounting.AccountGroup group = null;
Integer groupOrderNumber = null;
for (AccountGroup key : groupMap.keySet()) {
if (key.contains(year, accountNumber)) {
group = groupMap.get(key);
groupOrderNumber = key.getOrderNumber();
break;
}
}
if (group == null || groupOrderNumber == null) {
throw new RuntimeException(GROUP_LOOKUP_ERROR + oldAccount);
}
// Get the account name using the account map. This mapping links the
// account to an account created in an earlier fiscal year or sets the
// name to a "standardized" name rather than to the old name.
String name = accountMap.get(intAccountNumber);
// If not mapped, use the input name.
name = (name == null ? oldAccount.getName() : name);
// Create new account, add to set
com.poesys.accounting.dataloader.newaccounting.Account newAccount =
new com.poesys.accounting.dataloader.newaccounting.Account(name, name,
oldAccount.getAccountType(),
oldAccount.getDefaultDebit(),
receivable);
if (!accounts.add(newAccount)) {
// The account is already in the accounts set, so get that account.
newAccount = accountNameMap.get(name);
} else {
// The account is new, so add it to the name map. The OldDataBuilder
// preserves the accounts set and the account name map over multiple
// fiscal years.
accountNameMap.put(name, newAccount);
}
// Set the capital account; this conditionally sets the capital account if
// this account is the capital account.
setCapitalAccount(newAccount);
Integer accountOrderNumber = incrementAccountOrderNumber(group);
// Index the account in the fiscal year account-number lookup map. The
// getFiscalYear() method clears this map for each fiscal year, so this
// method needs to add the account with the account number for this year
// regardless of whether a previous year created the shared new-accounting
// account.
accountNumberMap.put(intAccountNumber, newAccount);
logger.debug("Indexed account " + oldAccount.getAccountNumber());
// Add the account to the fiscal year by creating a FiscalYearAccount link
// with the associated group. This operation links the account to the
// fiscal year by creating a linking object in the database on store().
// The link is put into the three linked objects as well.
FiscalYearAccount fsYAccount =
new FiscalYearAccount(fiscalYear, oldAccount.getAccountType(), group, groupOrderNumber,
newAccount, accountOrderNumber);
fiscalYear.addAccount(fsYAccount);
newAccount.addYear(fsYAccount);
group.addLink(fsYAccount);
}
/**
* If this account is one of the capital structure accounts, associate the generated capital
* entity with the account. This links the account to the capital entity and vice versa.
*
* @param newAccount the account object
*/
private void setCapitalAccount(com.poesys.accounting.dataloader.newaccounting.Account
newAccount) {
String name = newAccount.getName();
CapitalEntity capEntity = capitalEntityMap.get(name);
if (capEntity != null) {
// The account name is in the capital entity map, so this is a capital
// or distribution account; set the account in the entity in the proper
// place.
// Check for the capital entity name, required to get new entity object.
if (capEntity.getName() == null) {
throw new RuntimeException(NO_CAPITAL_ENTITY_NAME_ERROR);
}
for (com.poesys.accounting.dataloader.newaccounting.CapitalEntity newCapEntity :
capitalStructure.getEntities()) {
if (newCapEntity.getName() == null) {
throw new RuntimeException(NO_NEW_CAPITAL_ENTITY_NAME_ERROR);
}
if (newCapEntity.getName().equals(capEntity.getName())) {
// Found the entity to set with the account.
if (capEntity.getCapitalAccountName().equals(name)) {
// This is the capital account for the entity.
newCapEntity.setCapitalAccount(newAccount);
newAccount.setCapitalEntity(newCapEntity);
} else if (capEntity.getDistributionAccountName() != null &&
capEntity.getDistributionAccountName().equals(name)) {
newCapEntity.setDistributionAccount(newAccount);
newAccount.setCapitalEntity(newCapEntity);
} else if (capEntity.getDistributionAccountName() != null) {
// error, neither capital nor distribution account matches
throw new RuntimeException(INVALID_CAPITAL_ACCOUNT + name);
} // else do nothing
}
}
}
}
/**
* Increment the account order number within the group.
*
* @param group the group containing the account
* @return the next order number in the group
*/
private Integer incrementAccountOrderNumber(com.poesys.accounting.dataloader.newaccounting
.AccountGroup group) {
Integer accountOrderNumber;
// Increment the counter for ordering the accounts within the group.
accountOrderNumber = groupAccountOrderNumbers.get(group);
if (accountOrderNumber == null) {
// No count for this group yet, create it as 1.
accountOrderNumber = 1;
} else {
// Order number is there, so increment it.
accountOrderNumber++;
}
// Save the current order number.
groupAccountOrderNumbers.put(group, accountOrderNumber);
return accountOrderNumber;
}
}
/**
* Balances get set in the first fiscal year processed, associating an initial balance with an
* account. The buildFiscalYear() method does not clear the balances.
*/
private class BalanceStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
Balance balance = new Balance(fiscalYear.getYear(), r);
balanceDataSet.add(balance);
}
}
/**
* Reimbursements link reimbursing transactions to receivable transactions in the current or prior
* fiscal years. These get cleared for each fiscal year.
*/
private class ReimbursementStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
Reimbursement reimbursement = new Reimbursement(fiscalYear.getYear(), r);
reimbursementDataSet.add(reimbursement);
}
}
/**
* Transactions contain the set of transactions for each fiscal year. These get cleared for each
* fiscal year.
*/
private class TransactionStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
Transaction transaction = new Transaction(fiscalYear.getYear(), r);
transactionDataSet.add(transaction);
}
}
/**
* Transaction items associate with a transaction by id and an account by number, specifying the
* debit or credit amount by which the transaction changes the value of the account.These get
* cleared for each fiscal year.
*
* @author Robert J. Muller
*/
private class ItemStrategy implements IBuildStrategy {
@Override
public void build(BufferedReader r) {
Item item = new Item(fiscalYear.getYear(), r);
itemDataSet.add(item);
}
}
/**
* Create a OldDataBuilder object. The parameters object must contain a path to a directory
* containing one sub-directory for each fiscal year, no gaps allowed, and must provide a series
* of readers with the correct data characteristics. The fiscal year contains all the relevant
* data that the client can use to create the accounting system. Building a fiscal year clears all
* the data sets not shared between years, so the client must call all the process steps for a
* given fiscal year, then get the fiscal year object. Use the appropriate getters to get the
* shared data sets.
*
* @param parameters the program parameters object (path and file names)
*/
public OldDataBuilder(IParameters parameters) {
this.parameters = parameters;
if (parameters.getPath() == null) {
throw new InvalidParametersException(NULL_FILE_PATH_ERROR);
}
}
@Override
public void buildCapitalStructure() {
// Build the capital entities list for the accounting system.
String incomeSummary = parameters.getIncomeSummaryAccountName();
if (incomeSummary == null || incomeSummary.isEmpty()) {
throw new InvalidParametersException(NULL_INCOME_SUMMARY_ERROR);
}
capitalStructure = new CapitalStructure(incomeSummary);
IBuildStrategy strategy = new CapitalEntityStrategy();
readFile(parameters.getCapitalEntityReader(), strategy);
// Build a list of new-accounting capital entities from the old ones and add
// the account names to the capital entity map.
List<com.poesys.accounting.dataloader.newaccounting.CapitalEntity> newEntities =
new ArrayList<>();
for (CapitalEntity entity : entities) {
newEntities.add(
new com.poesys.accounting.dataloader.newaccounting.CapitalEntity(entity.getName(),
entity
.getCapitalAccountName(),
entity
.getDistributionAccountName(),
new BigDecimal(
entity.getOwnership())));
capitalEntityMap.put(entity.getCapitalAccountName(), entity);
if (entity.getDistributionAccountName() != null) {
capitalEntityMap.put(entity.getDistributionAccountName(), entity);
}
}
capitalStructure.addEntities(newEntities);
}
@Override
public void buildFiscalYear(Integer year) {
this.fiscalYear = new FiscalYear(year);
fiscalYears.add(this.fiscalYear);
logger.debug("Building fiscal year " + year);
// Add the sub-map for the receivables.
receivablesMap.put(year, new HashMap<>());
// Add the sub-map for the reimbursements.
reimbursementsMap.put(year, new HashMap<>());
// Clear the temporary data sets for the fiscal year.
reimbursementDataSet.clear();
balanceDataSet.clear();
transactionDataSet.clear();
itemDataSet.clear();
// Clear the lookup maps for accounts by account number and transactions by transaction id,
// as those values vary by fiscal year. Note that this method does not clear the accounts by
// account name lookup map, which uses the new-accounting name that does not vary by fiscal
// year. Also note that the transaction set itself is not cleared, as it spans the fiscal years.
accountNumberMap.clear();
transactionMap.clear();
// Clear currentTransaction data (debugging data)
currentTransactions.clear();
}
/**
* Read a specified file into the corresponding data structures using the appropriate
* IBuildStrategy object. The file must have fewer than 5,000 rows of data, which prevents
* infinite loops. This method has public access to allow direct unit testing, as it is the
* critical section of code in the class.
*
* @param reader the input data reader
* @param strategy the build strategy object
*/
public void readFile(Reader reader, IBuildStrategy strategy) {
BufferedReader r = null;
if (reader == null || strategy == null) {
throw new InvalidParametersException(NULL_PARAMETER_ERROR);
}
try {
r = new BufferedReader(reader);
// iterate building objects until end-of-stream exception or hard-coded
// LIMIT is reached; the latter approach prevents an infinite loop from
// buggy readers
for (int i = 0; i < LIMIT; i++) {
strategy.build(r);
}
} catch (EndOfStream e) {
// reached end of file, ready to close
}
finally {
try {
reader.close();
} catch (IOException e) {
// log and ignore
logger.error(FILE_READER_CLOSE_ERROR, e);
}
if (r != null) {
try {
r.close();
} catch (IOException e) {
// log and ignore
logger.error(READER_CLOSE_ERROR, e);
}
}
}
}
@Override
public void buildAccountGroups() {
IBuildStrategy strategy = new AccountGroupStrategy();
readFile(parameters.getAccountGroupReader(fiscalYear.getYear()), strategy);
// type map is complete, sort the lists and generate order numbers; the
// AccountGroup objects are also in the groupMap, so the order numbers
// will be set for the objects in that map as well as the type map.
for (List<AccountGroup> list : typeMap.values()) {
// sort the list using compareTo
Collections.sort(list);
// generate order numbers starting at 1
int orderNumber = 1;
Integer previousYear = null;
for (AccountGroup group : list) {
if (previousYear != null && !group.getYear().equals(previousYear)) {
// year changed, reset counter to 1
orderNumber = 1;
}
group.setOrderNumber(orderNumber);
previousYear = group.getYear();
orderNumber++;
}
}
}
@Override
public void buildAccountMap() {
IBuildStrategy strategy = new AccountMapStrategy();
readFile(parameters.getAccountMapReader(fiscalYear.getYear()), strategy);
}
@Override
public void buildAccounts() {
IBuildStrategy strategy = new AccountStrategy();
readFile(parameters.getAccountReader(fiscalYear.getYear()), strategy);
}
@Override
public void buildBalances() {
IBuildStrategy strategy = new BalanceStrategy();
readFile(parameters.getBalanceReader(fiscalYear.getYear()), strategy);
if (!balanceDataSet.isEmpty()) {
buildBalanceTransactions();
}
}
/**
* Build the balance transactions and put them into the transaction set in the fiscal year. The
* method creates one balance transaction per account balance, with one item.
*/
private void buildBalanceTransactions() {
// Use a special, large transaction id for the balance transactions. This id
// must be larger than any fiscal year transaction id in the old accounting
// system.
BigInteger id = new BigInteger(FIRST_BALANCE_TRANSACTION_ID);
for (Balance balance : balanceDataSet) {
com.poesys.accounting.dataloader.newaccounting.Account account =
getAccountFromBalance(balance);
// Create a new-accounting balance transaction (balance flag is true).
com.poesys.accounting.dataloader.newaccounting.Transaction transaction =
new com.poesys.accounting.dataloader.newaccounting.Transaction(id, account.getName(),
fiscalYear.getStart(), false,
true);
// add the item to the transaction
transaction.addItem(balance.getAmount(), account, balance.isDebit(), false);
// validate the transaction
if (!transaction.isValid()) {
throw new RuntimeException(INVALID_TRANSACTION_ERROR + transaction);
}
// add the transaction to set of transactions
transactions.add(transaction);
// for receivable accounts, index the balance item
if (account.isReceivable()) {
indexReceivableItem(id.intValue(), balance.getAccountNumber(), balance.isDebit(),
transaction.getItem(account));
}
// increment the transaction id; assign because BigInteger is immutable
id = id.add(BigInteger.ONE);
}
}
/**
* Given a specified balance, get the new accounting system account for the balance by looking up
* the balance account number in the account map created earlier in the build process.
*
* @param balance the balance for which to get the account
* @return the new accounting system account
*/
private com.poesys.accounting.dataloader.newaccounting.Account getAccountFromBalance(Balance
balance) {
Integer accountNumber = new Float(balance.getAccountNumber() * 100F).intValue();
return accountNumberMap.get(accountNumber);
}
@Override
public void buildTransactions() {
readTransactionsAndItems();
createTransactions();
createItems();
if (!validateTransactions()) {
throw new RuntimeException(INVALID_TRANSACTIONS_ERROR + " for year " + fiscalYear.getYear());
}
// Get the updater if any and update with generated transactions.
IFiscalYearUpdater updater = parameters.getUpdater();
if (updater != null) {
updater.update(fiscalYear, transactions, currentTransactions, this);
}
}
/**
* Read the transactions and items from the old-accounting data with the appropriate strategies.
* Items are children of transactions, so the loader needs to load both together.
*/
private void readTransactionsAndItems() {
// Read the transaction, item, and reimbursement files.
IBuildStrategy strategy = new TransactionStrategy();
readFile(parameters.getTransactionReader(fiscalYear.getYear()), strategy);
strategy = new ItemStrategy();
readFile(parameters.getItemReader(fiscalYear.getYear()), strategy);
}
/**
* Iterate through the transaction data set and create all the new-accounting transactions, adding
* them to the transaction lookup map indexed by transaction id.
*/
private void createTransactions() {
// Iterate through transactions and create new-accounting transactions
for (Transaction transaction : transactionDataSet) {
BigInteger id = new BigInteger(transaction.getTransactionId().toString());
com.poesys.accounting.dataloader.newaccounting.Transaction newTransaction =
new com.poesys.accounting.dataloader.newaccounting.Transaction(id,
transaction.getDescription(),
transaction
.getTransactionDate(),
false, false);
// Add the transaction to the transaction map keyed on id.
transactionMap.put(transaction.getTransactionId(), newTransaction);
// Add the transaction to the set of transactions.
transactions.add(newTransaction);
currentTransactions.add(newTransaction);
// Set the fiscal year's "last" id to the current id if it is greater than the current one.
// At the end of the loop, the fiscal year's id will be the greatest id read from the file.
fiscalYear.setLastId(id);
}
}
/**
* Iterate through the old-accounting items. Look up the transaction in the transaction map. Look
* up the account in the account map. Add the item to the transaction, which creates the item and
* associates it to the transaction and account. Throw a runtime exception if the transaction id
* or the account number is not in the relevant lookup map. Index each receivable-account item
* either as a receivable (debit) or reimbursement (credit). The buildReimbursements process step
* that follows will use these lookups along with the reimbursements data set to create
* reimbursement links.
*/
private void createItems() {
for (Item item : itemDataSet) {
// Get the transaction based on transaction id.
com.poesys.accounting.dataloader.newaccounting.Transaction transaction =
transactionMap.get(item.getTransactionId());
if (transaction == null) {
throw new RuntimeException(
NO_SUCH_TRANSACTION_ERROR + item.getTransactionId() + FISCAL_YEAR_ERROR +
fiscalYear.getYear());
}
// Convert account number to 5-digit integer for comparisons, then look up
// the account with the integer.
Integer accountNumber = new Float(item.getAccountNumber() * 100F).intValue();
com.poesys.accounting.dataloader.newaccounting.Account account =
accountNumberMap.get(accountNumber);
if (account == null) {
throw new RuntimeException(
NO_SUCH_ACCOUNT_ERROR + item.getAccountNumber() + FISCAL_YEAR_ERROR +
fiscalYear.getYear());
}
com.poesys.accounting.dataloader.newaccounting.Item newItem =
transaction.addItem(item.getAmount(), account, item.isDebit(), item.isChecked());
// Index the item in receivables or reimbursements as required.
if (account.isReceivable()) {
indexReceivableItem(item.getTransactionId(), item.getAccountNumber(), item.isDebit(),
newItem);
}
}
}
/**
* Put a receivable account item into the receivables (debit) or reimbursements (credit) map.
*
* @param id the transaction id for the item
* @param accountNumber the account number for the item; must be a receivable account number
* @param debit whether the item is debit (true) or credit (false)
* @param newItem the new-accounting version of the item
*/
private void indexReceivableItem(Integer id, Float accountNumber, boolean debit, com.poesys
.accounting.dataloader.newaccounting.Item newItem) {
// Check for receivable account
Integer key = new Float(accountNumber * 100F).intValue();
com.poesys.accounting.dataloader.newaccounting.Account account = accountNumberMap.get(key);
if (!account.isReceivable()) {
throw new RuntimeException(NOT_RECEIVABLE_ACCOUNT_ERROR + accountNumber);
}
ItemIndex index = new ItemIndex(id, accountNumber);
if (debit) {
// Receivable item, add to map indexed by year and transaction id
logger.debug(
"Adding receivable item to receivables map: " + fiscalYear.getYear() + " - " + id + " " +
"for" + " account " + accountNumber);
receivablesMap.get(fiscalYear.getYear()).put(index, newItem);
} else {
// Reimbursing item, add to map indexed by year and transaction id
logger.debug(
"Adding reimbursing item to reimbursements map: " + fiscalYear.getYear() + " - " + id + "" +
" for account " + accountNumber);
reimbursementsMap.get(fiscalYear.getYear()).put(index, newItem);
}
}
/**
* Validate all the transactions currently in the transaction lookup map. If there are invalid
* transactions, log them as errors. Log all the invalid transactions. If there is at least one
* invalid transaction, return false; otherwise, return true.
*
* @return false if there is at least one invalid transaction; otherwise, true
*/
private boolean validateTransactions() {
boolean valid = true;
for (com.poesys.accounting.dataloader.newaccounting.Transaction transaction : transactionMap
.values()) {
if (!transaction.isValid()) {
logger.error(INVALID_TRANSACTION_ERROR + transaction);
if (valid) {
// set flag to invalid if valid only, thus never resets to valid state
valid = false;
}
}
}
return valid;
}
@Override
public void buildReimbursements() {
IBuildStrategy strategy = new ReimbursementStrategy();
readFile(parameters.getReimbursementReader(fiscalYear.getYear()), strategy);
// Iterate through reimbursements. Use the shared item lookup maps to get
// the new-accounting items to link, then reimburse the receivable items.
for (Reimbursement reimbursement : reimbursementDataSet) {
Integer receivableYear = reimbursement.getReceivableYear();
Integer receivableId = reimbursement.getReceivableTransactionId();
Float receivableAccountNumber = reimbursement.getAccountNumber();
if (receivableId.equals(0)) {
// unchanged prior year reimbursement, determine whether this is an
// oversight or whether to link the reimbursement to the balance
// transaction for the account.
receivableId = getBalanceReceivableId(receivableYear, receivableAccountNumber);
logger.debug("Reimbursement is for 0 id, balance id is " + receivableId);
}
com.poesys.accounting.dataloader.newaccounting.Item receivableItem =
lookupReceivableItem(receivableYear, receivableId, receivableAccountNumber);
Integer reimbursementYear = reimbursement.getReimbursementYear();
Integer reimbursementId = reimbursement.getReimbursementTransactionId();
com.poesys.accounting.dataloader.newaccounting.Item reimbursementItem =
lookupReimbursingItem(reimbursementYear, reimbursementId, receivableAccountNumber);
// if both there, link the items.
if (receivableItem != null && reimbursementItem != null) {
receivableItem.reimburse(reimbursementItem, reimbursement.getReimbursedAmount(),
reimbursement.getAllocatedAmount());
} else if (receivableItem == null) {
// The receivable wasn't found, warn but ignore.
logger.warn("Reimbursing transaction id " + reimbursementId + " reimburses year " +
reimbursementYear + " id " + receivableId + " but " + receivableId +
" was not found " + "" + "in " + receivableYear + " as a receivable.");
} else {
// The reimbursing item wasn't found, warn but ignore.
logger.warn(
"Reimbursing transaction id " + reimbursementId + " reimburses year " + receivableYear +
" id " + receivableId + " but " + reimbursementId + " was not found in " +
reimbursementYear + " as a reimbursement.");
}
}
}
/**
* Get the balance id for a receivable account if the balance year is the same as the receivable
* year; otherwise, throw a runtime exception. Make sure the balance for the account is non-zero,
* and if it is zero, throw a runtime exception.
*
* @param receivableYear the designated receivable year of a reimbursement
* @param receivableAccountNumber the old-accounting account number for the receivable account
* @return the transaction id for the balance transaction for the receivable account
*/
private Integer getBalanceReceivableId(Integer receivableYear, Float receivableAccountNumber) {
com.poesys.accounting.dataloader.newaccounting.Account account =
getAccountFromNumber(receivableYear, receivableAccountNumber);
// Find the balance transaction for the account.
com.poesys.accounting.dataloader.newaccounting.Transaction balanceTransaction = null;
for (com.poesys.accounting.dataloader.newaccounting.Item item : account.getItems()) {
if (item.getTransaction().isBalance()) {
balanceTransaction = item.getTransaction();
validateBalanceReceivable(receivableYear, receivableAccountNumber, balanceTransaction,
item);
}
}
return balanceTransaction != null ? balanceTransaction.getId().intValue() : null;
}
/**
* Get a new-accounting Account object from a fiscal year and account number. Note that the
* old-accounting account numbers are unique only within a fiscal year, so you need to know the
* fiscal year if there is an error.
*
* @param year the fiscal year (used in error message)
* @param accountNumber the account number in the fiscal year
* @return the account
*/
private com.poesys.accounting.dataloader.newaccounting.Account getAccountFromNumber(Integer
year,
Float
accountNumber) {
// Get the account.
Integer number = new Float(accountNumber * 100F).intValue();
com.poesys.accounting.dataloader.newaccounting.Account account = accountNumberMap.get(number);
if (account == null) {
throw new RuntimeException(ACCOUNT_ERROR + accountNumber + " for year " + year);
}
return account;
}
/**
* Validate a balance transaction: <ul> <li>Is the item amount non-zero? Balance must be
* positive.</li> <li>Is the balance transaction non-null?</li> <li>Is the year of the transaction
* the same as the receivable year?</li> </ul>
*
* @param receivableYear the year of the receivable in the reimbursement
* @param receivableAccountNumber the receivable account (for error report)
* @param balanceTransaction the balance transaction to check
* @param item the balance item to check
*/
private void validateBalanceReceivable(Integer receivableYear, Float receivableAccountNumber,
com.poesys.accounting.dataloader.newaccounting
.Transaction balanceTransaction, com.poesys.accounting
.dataloader.newaccounting.Item item) {
if (balanceTransaction == null) {
throw new RuntimeException(NO_BALANCE_ERROR + receivableAccountNumber);
}
if (item.getAmount().equals(0.00D)) {
throw new RuntimeException(ZERO_BALANCE_ERROR + receivableAccountNumber);
}
if (!balanceTransaction.getYear().equals(receivableYear)) {
throw new RuntimeException(ZERO_RECEIVABLE_ID_ERROR);
}
}
/**
* Look up a receivable item in the receivables map.
*
* @param year the fiscal year of the item
* @param id the transaction id of the item
* @param accountNumber the account number of the item
* @return the receivable item
*/
private com.poesys.accounting.dataloader.newaccounting.Item lookupReceivableItem(Integer year,
Integer id,
Float
accountNumber) {
logger.debug("Looking up receivable item for reimbursement: " + year + " - " + id);
Map<ItemIndex, com.poesys.accounting.dataloader.newaccounting.Item> items =
receivablesMap.get(year);
if (items == null) {
throw new RuntimeException(NO_RECEIVABLES_ITEM_MAP_ERROR + year);
}
ItemIndex index = new ItemIndex(id, accountNumber);
return items.get(index);
}
/**
* Look up a reimbursing item in the reimbursements map.
*
* @param year the fiscal year of the item
* @param id the transaction id of the item
* @param accountNumber the account number of the item
* @return the reimbursing item
*/
private com.poesys.accounting.dataloader.newaccounting.Item lookupReimbursingItem(Integer year,
Integer id,
Float
accountNumber) {
logger.debug("Looking up reimbursing item for receivable: " + year + " - " + id);
Map<ItemIndex, com.poesys.accounting.dataloader.newaccounting.Item> items =
reimbursementsMap.get(year);
if (items == null) {
throw new RuntimeException(NO_REIMBURSEMENTS_ITEM_MAP_ERROR + year);
}
ItemIndex index = new ItemIndex(id, accountNumber);
return items.get(index);
}
@Override
public String getPath() {
return parameters.getPath();
}
@Override
public List<FiscalYear> getFiscalYears() {
return fiscalYears;
}
@Override
public com.poesys.accounting.dataloader.newaccounting.FiscalYear getFiscalYear() {
return fiscalYear;
}
@Override
public CapitalStructure getCapitalStructure() {
return capitalStructure;
}
@Override
public Set<com.poesys.accounting.dataloader.newaccounting.AccountGroup> getAccountGroups
(FiscalYear year) {
return groupSetsMap.get(year);
}
/**
* Get the typeMap for unit testing.
*
* @return the typeMap
*/
Map<AccountType, List<AccountGroup>> getTypeMap() {
return typeMap;
}
@Override
public Set<com.poesys.accounting.dataloader.newaccounting.Account> getAccounts() {
return accounts;
}
/**
* Get the balance data set. This package-access method permits unit testing of the
* buildBalances() method, which fills in this balance data set.
*
* @return returns the balance data set for unit test validation
*/
Set<Balance> getBalanceDataSet() {
return balanceDataSet;
}
@Override
public com.poesys.accounting.dataloader.newaccounting.Account getAccountByName(String name) {
if (name == null) {
throw new RuntimeException(NO_ACCOUNT_NAME_ERROR);
}
return accountNameMap.get(name);
}
public Set<com.poesys.accounting.dataloader.newaccounting.Transaction> getTransactions() {
return transactions;
}
}
| lgpl-3.0 |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/trok/TROKAdventureCombatFragment.java | 9477 | package pt.joaomneto.titancompanion.adventure.impl.fragments.trok;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import kotlin.jvm.functions.Function0;
import pt.joaomneto.titancompanion.R;
import pt.joaomneto.titancompanion.adventure.Adventure;
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment;
import pt.joaomneto.titancompanion.adventure.impl.util.DiceRoll;
import pt.joaomneto.titancompanion.adventurecreation.impl.adapter.DropdownStringAdapter;
import pt.joaomneto.titancompanion.util.DiceRoller;
import java.util.Arrays;
import java.util.List;
public class TROKAdventureCombatFragment extends AdventureCombatFragment {
public static final String TROK15_GUNFIGHT = "TROK15_GUNFIGHT";
String overrideDamage = null;
private Spinner damageSpinner = null;
private TextView damageText = null;
private List<String> damageList = Arrays.asList("4", "5", "6", "1D6");
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRootView(inflater.inflate(R.layout.fragment_15trok_adventure_combat, container, false));
damageSpinner = getRootView().findViewById(R.id.damageSpinner);
damageText = getRootView().findViewById(R.id.damageText);
if (damageSpinner != null) {
DropdownStringAdapter adapter = new DropdownStringAdapter(getActivity(), android.R.layout.simple_list_item_1, damageList);
damageSpinner.setAdapter(adapter);
}
if (overrideDamage != null) {
damageSpinner.setSelection(damageList.indexOf(overrideDamage));
} else {
damageSpinner.setSelection(0);
}
damageSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
overrideDamage = damageList.get(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
overrideDamage = null;
}
});
init();
return getRootView();
}
protected void combatTurn() {
if (getCombatPositions().size() == 0)
return;
if (getCombatStarted() == false) {
setCombatStarted(true);
getCombatTypeSwitch().setClickable(false);
}
if (getCombatMode().equals(TROK15_GUNFIGHT)) {
gunfightCombatTurn();
} else {
standardCombatTurn();
}
}
@Override
public Function0<Integer> getDamage() {
if (getCombatMode().equals(Companion.getNORMAL())) {
return () -> 2;
} else if (getCombatMode().equals(TROK15_GUNFIGHT)) {
return () -> Companion.convertDamageStringToInteger(overrideDamage);
}
return () -> 2;
}
protected String combatTypeSwitchBehaviour(boolean isChecked) {
setCombatMode(isChecked ? TROK15_GUNFIGHT : Companion.getNORMAL());
return getCombatMode();
}
public String getOntext() {
return getString(R.string.gunfight);
}
@Override
protected void resetCombat(boolean clearResults) {
super.resetCombat(clearResults);
}
protected void switchLayoutCombatStarted() {
damageSpinner.setVisibility(View.GONE);
damageText.setVisibility(View.GONE);
super.switchLayoutCombatStarted();
}
protected void switchLayoutReset(boolean clearResult) {
damageSpinner.setVisibility(View.VISIBLE);
damageText.setVisibility(View.VISIBLE);
super.switchLayoutReset(clearResult);
}
protected int getKnockoutStamina() {
return -1;
}
protected void addCombatButtonOnClick() {
Adventure adv = (Adventure) getActivity();
final InputMethodManager mgr = (InputMethodManager) adv.getSystemService(Context.INPUT_METHOD_SERVICE);
if (getCombatStarted())
return;
AlertDialog.Builder builder = new AlertDialog.Builder(adv);
final View addCombatantView = adv.getLayoutInflater().inflate(
getCombatMode() == null || getCombatMode().equals(Companion.getNORMAL()) ? R.layout.component_add_combatant : R.layout.component_add_combatant_damage, null);
final EditText damageValue = addCombatantView.findViewById(R.id.enemyDamage);
if (damageValue != null) {
damageValue.setText(getDefaultEnemyDamage());
damageValue.setRawInputType(Configuration.KEYBOARD_12KEY);
}
builder.setTitle(R.string.addEnemy).setCancelable(false).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mgr.hideSoftInputFromWindow(addCombatantView.getWindowToken(), 0);
dialog.cancel();
}
});
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mgr.hideSoftInputFromWindow(addCombatantView.getWindowToken(), 0);
EditText enemySkillValue = addCombatantView.findViewById(R.id.enemySkillValue);
EditText enemyStaminaValue = addCombatantView.findViewById(R.id.enemyStaminaValue);
EditText handicapValue = addCombatantView.findViewById(R.id.handicapValue);
Integer skill = Integer.valueOf(enemySkillValue.getText().toString());
Integer stamina = Integer.valueOf(enemyStaminaValue.getText().toString());
Integer handicap = Integer.valueOf(handicapValue.getText().toString());
addCombatant(skill, stamina, handicap, damageValue == null ? getDefaultEnemyDamage() : damageValue.getText().toString());
}
});
AlertDialog alert = builder.create();
EditText skillValue = addCombatantView.findViewById(R.id.enemySkillValue);
alert.setView(addCombatantView);
mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
skillValue.requestFocus();
alert.show();
}
@Override
protected void startCombat() {
if (getCombatMode().equals(TROK15_GUNFIGHT)) {
for (int i = 0; i < getCombatPositions().size(); i++) {
Combatant c = getCombatPositions().get(i);
if (c != null)
c.setDamage("4");
}
}
super.startCombat();
}
protected String getDefaultEnemyDamage() {
return "4";
}
protected void gunfightCombatTurn() {
Combatant position = getCurrentEnemy();
Adventure adv = (Adventure) getActivity();
// if (!finishedCombats.contains(currentCombat)) {
setDraw(false);
setLuckTest(false);
setHit(false);
DiceRoll diceRoll = DiceRoller.INSTANCE.roll2D6();
int skill = adv.getCombatSkillValue();
boolean hitEnemy = diceRoll.getSum() <= skill;
if (hitEnemy) {
int damage = getDamage().invoke();
position.setCurrentStamina(Math.max(0, position.getCurrentStamina() - damage));
setHit(true);
getCombatResult().setText(getString(R.string.hitEnemyDamage, damage));
} else {
setDraw(true);
getCombatResult().setText(R.string.missedTheEnemy);
}
if (position.getCurrentStamina() == 0) {
removeAndAdvanceCombat(position);
getCombatResult().setText(getCombatResult().getText() + "\n" + getString(R.string.defeatedEnemy));
}
for (int i = 0; i < getCombatPositions().size(); i++) {
Combatant enemy = getCombatPositions().get(i);
if (enemy != null && enemy.getCurrentStamina() > 0) {
if (DiceRoller.INSTANCE.roll2D6().getSum() <= enemy.getCurrentSkill()) {
int damage = Companion.convertDamageStringToInteger(enemy.getDamage());
getCombatResult().setText(getCombatResult().getText() + "\n" + getString(R.string.saCombatText2, enemy.getCurrentSkill(), enemy.getCurrentStamina(), damage));
adv.setCurrentStamina(Math.max(0, adv.getCurrentStamina() - damage));
} else {
getCombatResult().setText(getCombatResult().getText() + "\n" + getString(R.string.saCombatText3, enemy.getCurrentSkill(), enemy.getCurrentStamina()));
}
}
}
if (adv.getCurrentStamina() <= 0) {
getCombatResult().setText(R.string.youveDied);
}
refreshScreensFromResume();
}
@Override
public void refreshScreensFromResume() {
getCombatantListAdapter().notifyDataSetChanged();
getCombatTypeSwitch().setEnabled(getCombatPositions().isEmpty());
}
}
| lgpl-3.0 |
sibbr/portal-qualidade | check-names/src/br/gov/sibbr/Report.java | 756 | package br.gov.sibbr;
public class Report {
BD bd = new BD();
public void start() {
/*
bd.abreConexao();
ArrayList<String> sourcefileid = new ArrayList<String>();
ArrayList<String> resource_name = new ArrayList<String>();
ResultSet rs = bd.consulta("Select sourcefileid, resource_name from public.resource_contact");
try{
while(rs.next()){
sourcefileid.add(rs.getString("sourcefileid"));
resource_name.add(rs.getString("resource_name"));
}
}catch(Exception e){
e.printStackTrace();
}
String lista[] = new String[resource_name.size()];
for(int i = 0; i < resource_name.size(); i++){
lista[i] = resource_name.get(i);
System.out.println("Resource Name: " + lista[i]);
}
*/
}
}
| lgpl-3.0 |
WarpOrganization/warp | core/src/main/java/net/warpgame/engine/core/execution/task/EngineTask.java | 821 | package net.warpgame.engine.core.execution.task;
/**
* @author Jaca777
* Created 2016-06-25 at 12
*/
public abstract class EngineTask {
private boolean initialized = false;
/**
* Call only this method in order to initialize the task.
*/
public void init() {
if (initialized)
throw new TaskInitializedException();
onInit();
initialized = true;
}
public void close() {
if(!initialized) throw new TaskNotInitializedException();
onClose();
initialized = false;
}
public boolean isInitialized() {
return initialized;
}
protected abstract void onInit();
protected abstract void onClose();
public abstract void update(int delta);
public int getPriority() {
return 0;
}
}
| lgpl-3.0 |
alimg/maxball | app/src/main/java/com/xsonsui/maxball/LobbyBrowserActivity.java | 5298 | package com.xsonsui.maxball;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.xsonsui.maxball.model.Lobby;
import com.xsonsui.maxball.nuts.model.NetAddress;
import java.util.List;
public class LobbyBrowserActivity extends Activity{
LobbyManager lobbyManager = new LobbyManager();
private String mSessionId;
public LobbyManager.Listener<List<NetAddress>> listLobbiesListener = new LobbyManager.Listener<List<NetAddress>>() {
@Override
public void onSuccess(List<NetAddress> result) {
mAdapter.clear();
mAdapter.addAll(result);
mAdapter.notifyDataSetInvalidated();
}
@Override
public void onFailed() {
Toast.makeText(LobbyBrowserActivity.this, "Something bad happened :(", Toast.LENGTH_SHORT).show();
}
};
private LobbyManager.Listener<String> registerListener = new LobbyManager.Listener<String>() {
@Override
public void onSuccess(String sessionId) {
mSessionId = sessionId;
lobbyManager.listLobbies(listLobbiesListener);
}
@Override
public void onFailed() {
Toast.makeText(LobbyBrowserActivity.this, "Something bad happened :(", Toast.LENGTH_SHORT).show();
finish();
}
};
private ListView listView;
private ArrayAdapter<NetAddress> mAdapter;
private ViewGroup layoutCreateLobby;
private EditText editLobbyName;
private LobbyManager.Listener<Lobby> createLobbyListener = new LobbyManager.Listener<Lobby>() {
@Override
public void onSuccess(Lobby lobby) {
Intent i = new Intent(LobbyBrowserActivity.this, GameActivity.class);
i.putExtra("lobby", lobby);
startActivity(i);
}
@Override
public void onFailed() {
Toast.makeText(LobbyBrowserActivity.this, "Something bad happened :(", Toast.LENGTH_SHORT).show();
}
};
private String playerName;
private String playerAvatar;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lobby);
Bundle extras = getIntent().getExtras();
playerName = extras.getString("name");
if(playerName.isEmpty())
playerName = "guest" + (int)(Math.random()*100000);
playerAvatar = playerName.substring(0, 1);
layoutCreateLobby = (ViewGroup)findViewById(R.id.layoutCreateLobby);
layoutCreateLobby.setVisibility(View.GONE);
editLobbyName = (EditText)findViewById(R.id.editText);
listView = (ListView)findViewById(R.id.listView);
mAdapter = new ArrayAdapter<NetAddress>(this, R.layout.lobby_list_item, R.id.textView);
listView.setAdapter(mAdapter);
findViewById(R.id.buttonRefresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
lobbyManager.listLobbies(listLobbiesListener);
}
});
findViewById(R.id.buttonCreate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
layoutCreateLobby.setVisibility(View.VISIBLE);
}
});
layoutCreateLobby.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
layoutCreateLobby.setVisibility(View.GONE);
}
});
findViewById(R.id.buttonCreateLobby).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editLobbyName.getText().toString();
Intent i = new Intent(LobbyBrowserActivity.this, GameActivity.class);
i.putExtra("action", "host");
i.putExtra("lobbyName", name);
i.putExtra("sessionId", mSessionId);
i.putExtra("playerName", playerName);
i.putExtra("playerAvatar", playerAvatar);
startActivity(i);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
NetAddress netAddress = mAdapter.getItem(pos);
Intent i = new Intent(LobbyBrowserActivity.this, GameActivity.class);
i.putExtra("action", "join");
i.putExtra("lobby", new Lobby(netAddress.srcAddress, netAddress.srcPort));
i.putExtra("sessionId", mSessionId);
i.putExtra("playerName", playerName);
i.putExtra("playerAvatar", playerAvatar);
startActivity(i);
}
});
}
@Override
protected void onResume() {
super.onResume();
lobbyManager.registerPlayer(playerName, registerListener);
}
}
| lgpl-3.0 |
fommil/matrix-toolkits-java | src/test/java/no/uib/cipr/matrix/sparse/GMRESDiagonalTest.java | 1125 | /*
* Copyright (C) 2003-2006 Bjørn-Ove Heimsund
*
* This file is part of MTJ.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package no.uib.cipr.matrix.sparse;
/**
* Test of GMRES with diagonal preconditioning
*/
public class GMRESDiagonalTest extends GMRESTest {
@Override
protected void createSolver() throws Exception {
super.createSolver();
M = new DiagonalPreconditioner(A.numRows());
}
}
| lgpl-3.0 |