repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
DanielYao/tigase-server | src/main/java/tigase/server/ext/handlers/StreamFeaturesProcessor.java | 3819 | /*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2012 "Artur Hefczyc" <artur.hefczyc@tigase.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.server.ext.handlers;
//~--- non-JDK imports --------------------------------------------------------
import tigase.server.Packet;
import tigase.server.ext.ComponentConnection;
import tigase.server.ext.ComponentIOService;
import tigase.server.ext.ComponentProtocolHandler;
import tigase.server.ext.ExtProcessor;
import tigase.xml.Element;
//~--- JDK imports ------------------------------------------------------------
import java.util.List;
import java.util.Queue;
import java.util.logging.Logger;
//~--- classes ----------------------------------------------------------------
/**
* Created: Oct 31, 2009 3:51:09 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class StreamFeaturesProcessor implements ExtProcessor {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(StreamFeaturesProcessor.class.getName());
private static final String EL_NAME = "stream:features";
private static final String ID = EL_NAME;
private static final String STARTTLS = "starttls";
private static final String SASL = "sasl";
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
*
*/
@Override
public String getId() {
return ID;
}
/**
* Method description
*
*
* @param serv
* @param handler
*
*
*/
@Override
public List<Element> getStreamFeatures(ComponentIOService serv,
ComponentProtocolHandler handler) {
return null;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param p
* @param serv
* @param handler
* @param results
*
*
*/
@Override
public boolean process(Packet p, ComponentIOService serv, ComponentProtocolHandler handler,
Queue<Packet> results) {
if (p.isElement("features", "http://etherx.jabber.org/streams")) {
log.fine("Received stream features: " + p.toString());
Element elem = p.getElement();
if (elem.getChild(STARTTLS) != null) {
ExtProcessor proc = handler.getProcessor(STARTTLS);
proc.startProcessing(null, serv, handler, results);
return true;
}
if (elem.getChild("mechanisms") != null) {
ExtProcessor proc = handler.getProcessor(SASL);
proc.startProcessing(null, serv, handler, results);
return true;
}
return true;
}
return false;
}
/**
* Method description
*
*
* @param p
* @param serv
* @param handler
* @param results
*/
@Override
public void startProcessing(Packet p, ComponentIOService serv,
ComponentProtocolHandler handler, Queue<Packet> results) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
//~ Formatted in Sun Code Convention
//~ Formatted by Jindent --- http://www.jindent.com
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa2.2/src/test/java/org/asqatasun/rules/rgaa22/Rgaa22Rule05321Test.java | 3947 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa22;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.rules.rgaa22.test.Rgaa22RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 5.32 of the referential RGAA 2.2.
*
* @author jkowalczyk
*/
public class Rgaa22Rule05321Test extends Rgaa22RuleImplementationTestCase {
/**
* Default constructor
*/
public Rgaa22Rule05321Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.rgaa22.Rgaa22Rule05321");
}
@Override
protected void setUpWebResourceMap() {
// getWebResourceMap().put("Rgaa22.Test.5.32-1Passed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05321/RGAA22.Test.5.32-1Passed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.32-2Failed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05321/RGAA22.Test.5.32-2Failed-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.32-3NMI-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05321/RGAA22.Test.5.32-3NMI-01.html"));
// getWebResourceMap().put("Rgaa22.Test.5.32-4NA-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "rgaa22/Rgaa22Rule05321/RGAA22.Test.5.32-4NA-01.html"));
getWebResourceMap().put("Rgaa22.Test.5.32-5NT-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "rgaa22/Rgaa22Rule05321/RGAA22.Test.5.32-5NT-01.html"));
}
@Override
protected void setProcess() {
// assertEquals(TestSolution.PASSED,
// processPageTest("Rgaa22.Test.5.32-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// processPageTest("Rgaa22.Test.5.32-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// processPageTest("Rgaa22.Test.5.32-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// processPageTest("Rgaa22.Test.5.32-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
processPageTest("Rgaa22.Test.5.32-5NT-01").getValue());
}
@Override
protected void setConsolidate() {
// assertEquals(TestSolution.PASSED,
// consolidate("Rgaa22.Test.5.32-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// consolidate("Rgaa22.Test.5.32-2Failed-01").getValue());
// assertEquals(TestSolution.NEED_MORE_INFO,
// consolidate("Rgaa22.Test.5.32-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// consolidate("Rgaa22.Test.5.32-4NA-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("Rgaa22.Test.5.32-5NT-01").getValue());
}
}
| agpl-3.0 |
oregami/oregami-game-database | src/main/java/org/oregami/data/GameDao.java | 920 | package org.oregami.data;
import org.oregami.domain.model.games.Game;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import java.util.List;
@Component
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GameDao extends GenericDAOUUIDImpl<Game, String> {
@Autowired
public GameDao(EntityManager em) {
super(em);
entityClass=Game.class;
}
@SuppressWarnings("unchecked")
public List<Game> findByName(String name) {
List<Game> games = getEntityManager()
.createNativeQuery("SELECT * FROM Game g, GameTitle t where g.id=t.gameTitleList_id and lower(t.title) like '%" + name.toLowerCase() + "%'", Game.class).getResultList();
return games;
}
}
| agpl-3.0 |
moskiteau/KalturaGeneratedAPIClientsJava | src/com/kaltura/client/types/KalturaConfigurableDistributionJobProviderData.java | 2836 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import org.w3c.dom.Element;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
import com.kaltura.client.utils.ParseUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
* @date Mon, 10 Aug 15 02:02:11 -0400
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public abstract class KalturaConfigurableDistributionJobProviderData extends KalturaDistributionJobProviderData {
public String fieldValues;
public KalturaConfigurableDistributionJobProviderData() {
}
public KalturaConfigurableDistributionJobProviderData(Element node) throws KalturaApiException {
super(node);
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node aNode = childNodes.item(i);
String nodeName = aNode.getNodeName();
String txt = aNode.getTextContent();
if (nodeName.equals("fieldValues")) {
this.fieldValues = ParseUtils.parseString(txt);
continue;
}
}
}
public KalturaParams toParams() {
KalturaParams kparams = super.toParams();
kparams.add("objectType", "KalturaConfigurableDistributionJobProviderData");
kparams.add("fieldValues", this.fieldValues);
return kparams;
}
}
| agpl-3.0 |
Orichievac/FallenGalaxy | src-client/fr/fg/client/core/AdministrationPanelDialog.java | 26734 | /*
Copyright 2010 Thierry Chevalier
This file is part of Fallen Galaxy.
Fallen Galaxy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fallen Galaxy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Fallen Galaxy. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.fg.client.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import fr.fg.client.ajax.Action;
import fr.fg.client.ajax.ActionCallback;
import fr.fg.client.ajax.ActionCallbackAdapter;
import fr.fg.client.core.settings.Settings;
import fr.fg.client.data.AnswerData;
import fr.fg.client.data.PlayerInfosData;
import fr.fg.client.data.PlayersInfosData;
import fr.fg.client.data.MotdData;
import fr.fg.client.data.MotdsData;
import fr.fg.client.data.ScriptData;
import fr.fg.client.data.ScriptsData;
import fr.fg.client.openjwt.ui.DialogListener;
import fr.fg.client.openjwt.ui.JSButton;
import fr.fg.client.openjwt.ui.JSComboBox;
import fr.fg.client.openjwt.ui.JSDialog;
import fr.fg.client.openjwt.ui.JSLabel;
import fr.fg.client.openjwt.ui.JSList;
import fr.fg.client.openjwt.ui.JSRowLayout;
import fr.fg.client.openjwt.ui.JSTabbedPane;
import fr.fg.client.openjwt.ui.JSTextField;
import fr.fg.client.openjwt.ui.JSTextPane;
import fr.fg.client.openjwt.ui.SelectionListener;
@SuppressWarnings("deprecation")
public class AdministrationPanelDialog extends JSDialog implements SelectionListener,
ClickListener, ActionCallback, DialogListener {
// ------------------------------------------------------- CONSTANTES -- //
public final int VIEW_GENERAL=0,
VIEW_ARCHIVE=1,
VIEW_MULTIACCOUNTS=2,
VIEW_MANAGEMENT=3,
VIEW_SCRIPTS = 4,
VIEW_STATISTICS = 5,
VIEW_BUGS = 6;
// -------------------------------------------------------- ATTRIBUTS -- //
private JSRowLayout mainLayout;
private JSRowLayout layoutGeneral, layoutArchiveBan, layoutMultiAccounts, layoutManagement, layoutScripts,
layoutStatistics, layoutBugsReports;
private JSTabbedPane viewsPane;
private JSLabel tabHeader, label3, label4, scriptSelectionLabel,loadingLabel, player1Label, player2Label,
tabMultiAccountsHeader,spacingLabel;
private JSTextField player1, player2;
private JSButton changeMotdBt, showBannedBt, unbanBt, banBt,execScriptBt, checkMultiAccountsBt,
genericMultiAccountsCheckBt;
private JSList bannedList, multiAccountsList;
private Widget currentWidget;
private HTMLPanel motdModerators, scriptAnswer;
private JSComboBox scriptSelection;
List<MotdData> motd;
ArrayList<String> scriptList;
// ---------------------------------------------------- CONSTRUCTEURS -- //
/**
* @Lloyd: On te fera pas payé plus cher pour mettre des commentaires :p
*/
public AdministrationPanelDialog() {
super("Panneau d'administration", false, true, true);
mainLayout = new JSRowLayout(); //Le layout de la fenetre, on met tous les éléments affichés dedans
layoutGeneral = new JSRowLayout();
layoutArchiveBan = new JSRowLayout();
layoutMultiAccounts = new JSRowLayout();
layoutManagement = new JSRowLayout();
layoutScripts = new JSRowLayout();
layoutStatistics = new JSRowLayout();
layoutBugsReports = new JSRowLayout();
currentWidget = layoutGeneral;
layoutArchiveBan.setVisible(false);
layoutMultiAccounts.setVisible(false);
layoutManagement.setVisible(false);
layoutScripts.setVisible(false);
layoutStatistics.setVisible(false);
layoutBugsReports.setVisible(false);
ArrayList<String> views = new ArrayList<String>(); //Les titres des onglets
views.add("Général");
views.add("Bans");
if(Settings.isAdministrator()) {
views.add("Doubles comptes");
views.add("Gestion modérateurs");
views.add("Scripts");
views.add("Statistiques");
views.add("Bugs reports");
}
label4 = new JSLabel("Onglet gestion modérateurs");
label4.setWidth("240");
/***************************** Partie Général *****************************/
if(Settings.isAdministrator()) {
changeMotdBt = new JSButton("Changer le message du jour");
changeMotdBt.setPixelWidth(240);
changeMotdBt.addClickListener(this);
}
motdModerators = new HTMLPanel("");
motdModerators.setPixelSize(640, 360);
motd = new ArrayList<MotdData>();
if(Settings.isAdministrator()) {
layoutGeneral.addComponent(changeMotdBt);
layoutGeneral.addRow();
}
layoutGeneral.addComponent(motdModerators);
/*********************** Partie Gestion des Bannis ***********************/
showBannedBt = new JSButton("Afficher les bannis");
showBannedBt.setPixelWidth(240);
showBannedBt.addClickListener(this);
unbanBt = new JSButton("Débannir");
unbanBt.setPixelWidth(150);
unbanBt.addClickListener(this);
unbanBt.setVisible(false);
banBt = new JSButton("Bannir un joueur");
banBt.setPixelWidth(240);
banBt.addClickListener(this);
banBt.setVisible(true);
bannedList = new JSList();
bannedList.setPixelSize(640,320);
bannedList.addSelectionListener(this);
tabHeader = new JSLabel(new BannedPlayer().getTabHeader());
tabHeader.setPixelSize(640, 30);
layoutArchiveBan.addComponent(showBannedBt);
layoutArchiveBan.addComponent(unbanBt);
layoutArchiveBan.addComponent(banBt);
layoutArchiveBan.addComponent(new JSLabel(" "));
layoutArchiveBan.addRowSeparator(3);
layoutArchiveBan.addComponent(tabHeader);
layoutArchiveBan.addRow();
layoutArchiveBan.addComponent(bannedList);
/*********************** Partie Multi-comptes ***********************/
if(Settings.isAdministrator()) {
player1Label = new JSLabel(" Joueur 1: ");
player1Label.setPixelWidth(65);
player2Label = new JSLabel("Joueur 2: ");
player2Label.setPixelWidth(65);
spacingLabel = new JSLabel(" ");
spacingLabel.setPixelWidth(10);
player1 = new JSTextField();
player1.setPixelWidth(120);
player2 = new JSTextField();
player2.setPixelWidth(120);
tabMultiAccountsHeader = new JSLabel(new PlayerInfos().getTabHeader());
tabMultiAccountsHeader.setPixelSize(640, 30);
multiAccountsList = new JSList();
multiAccountsList.setPixelSize(640,320);
multiAccountsList.addSelectionListener(this);
checkMultiAccountsBt = new JSButton("Vérifier");
checkMultiAccountsBt.setPixelWidth(100);
checkMultiAccountsBt.addClickListener(this);
checkMultiAccountsBt.setToolTipText("Vérification entre les 2 joueurs");
genericMultiAccountsCheckBt = new JSButton("Vérification générique");
genericMultiAccountsCheckBt.setPixelWidth(160);
genericMultiAccountsCheckBt.addClickListener(this);
genericMultiAccountsCheckBt.setToolTipText("Vérification pour tous les joueurs (non implémenté)");
layoutMultiAccounts.addComponent(player1Label);
layoutMultiAccounts.addComponent(player1);
layoutMultiAccounts.addComponent(spacingLabel);
layoutMultiAccounts.addComponent(player2Label);
layoutMultiAccounts.addComponent(player2);
layoutMultiAccounts.addComponent(checkMultiAccountsBt);
layoutMultiAccounts.addComponent(genericMultiAccountsCheckBt);
layoutMultiAccounts.addRow();
layoutMultiAccounts.addComponent(tabMultiAccountsHeader);
layoutMultiAccounts.addRow();
layoutMultiAccounts.addComponent(multiAccountsList);
}
/************************** Partie Scripts **************************/
if(Settings.isAdministrator()) {
scriptList = new ArrayList<String>();
scriptSelectionLabel = new JSLabel("Script: ");
scriptSelectionLabel.setPixelWidth(80);
scriptSelection = new JSComboBox();
scriptSelection.setPixelWidth(220);
execScriptBt = new JSButton("Exécuter le script");
execScriptBt.setPixelWidth(180);
execScriptBt.addClickListener(this);
loadingLabel = new JSLabel();
loadingLabel.setStyleName("loading-script");
loadingLabel.setVisible(false);
scriptAnswer = new HTMLPanel("");
scriptAnswer.setPixelSize(640, 360);
layoutScripts.addComponent(scriptSelectionLabel);
layoutScripts.addComponent(scriptSelection);
layoutScripts.addComponent(execScriptBt);
layoutScripts.addComponent(loadingLabel);
layoutScripts.addRow();
layoutScripts.addComponent(scriptAnswer);
}
/********************** Partie Statistiques **********************/
/*********************** Partie Bug Report ***********************/
if(Settings.isAdministrator()) {
layoutBugsReports = new LayoutBugsReports();
}
/*********************** Layout principal ***********************/
mainLayout.setPixelSize(640,360);
layoutGeneral.setPixelSize(640,320);
layoutArchiveBan.setPixelWidth(640);
layoutMultiAccounts.setPixelSize(640,320);
layoutManagement.setPixelSize(640,320);
layoutManagement.addComponent(label4);
layoutManagement.addRow();
viewsPane = new JSTabbedPane(); //Les onglets
viewsPane.setTabs(views);
viewsPane.setPixelSize(720, 30);
viewsPane.addSelectionListener(this);
//On ajoute les éléments par défaut au layout
mainLayout.addComponent(viewsPane);
mainLayout.addRowSeparator(3);
mainLayout.addComponent(layoutGeneral);
mainLayout.addComponent(layoutArchiveBan);
if(Settings.isAdministrator()) {
mainLayout.addComponent(layoutMultiAccounts);
mainLayout.addComponent(layoutManagement);
mainLayout.addComponent(layoutScripts);
mainLayout.addComponent(layoutStatistics);
}
mainLayout.addRowSeparator(30);
mainLayout.addComponent(new JSLabel(" "));
setComponent(mainLayout);
centerOnScreen();
getMotd();
if(Settings.isAdministrator()) {
refreshBannedList();
refreshScriptList();
}
}
// --------------------------------------------------------- METHODES -- //
public void selectionChanged(Widget sender, int newValue, int oldValue) {
if(sender==viewsPane) {
currentWidget.setVisible(false);
switch (viewsPane.getSelectedIndex()) {
case VIEW_GENERAL:
layoutGeneral.setVisible(true);
currentWidget = layoutGeneral;
layoutGeneral.update();
break;
case VIEW_ARCHIVE:
layoutArchiveBan.setVisible(true);
currentWidget = layoutArchiveBan;
layoutArchiveBan.update();
break;
case VIEW_MULTIACCOUNTS:
layoutMultiAccounts.setVisible(true);
currentWidget = layoutMultiAccounts;
layoutMultiAccounts.update();
break;
case VIEW_MANAGEMENT:
layoutManagement.setVisible(true);
currentWidget = layoutManagement;
layoutManagement.update();
break;
case VIEW_SCRIPTS:
layoutScripts.setVisible(true);
currentWidget = layoutScripts;
layoutScripts.update();
break;
case VIEW_STATISTICS:
layoutStatistics.setVisible(true);
currentWidget = layoutStatistics;
layoutScripts.update();
break;
default:break;
}
mainLayout.update();
}
else if(sender == bannedList) {
if( bannedList.getSelectedIndex()!=-1) {
if( ((BannedPlayer) bannedList.getSelectedItem()).isGameBanned() && !Settings.isAdministrator()) {
unbanBt.setVisible(false);
layoutArchiveBan.update();
}
else {
unbanBt.setVisible(true);
layoutArchiveBan.update();
}
}
}
}
public void onClick(Widget sender) {
if(sender == showBannedBt) {
getBanned();
}
else if(sender == unbanBt) {
unbanPlayer();
}
else if(sender == banBt) {
BanPlayerDialog banPlayerDialog = new BanPlayerDialog(this);
banPlayerDialog.setVisible(true);
}
else if(sender == changeMotdBt) {
MotdDialog motdDialog = new MotdDialog(this);
motdDialog.setVisible(true);
}
else if(sender == execScriptBt) {
executeScript();
}
else if(sender == checkMultiAccountsBt) {
checkMultiAccounts();
}
}
public void refreshBannedList() {
getBanned();
}
public void refreshMotd() {
getMotd();
}
public void refreshScriptList() {
getScriptList();
}
public String getMotdAt(int index) {
String message ="";
if(index>=motd.size())
return message;
for(int i=0;i<motd.size();i++) {
if(motd.get(i).getId()==index) {
message = motd.get(i).getMessage();
break;
}
}
return message;
}
public void onFailure(String error) {
//ignoré
}
public void onSuccess(AnswerData data) {
}
public void dialogClosed(Widget sender) {
}
// ------------------------------------------------- METHODES PRIVEES -- //
private void getBanned() {
HashMap<String,String> params = new HashMap<String,String>();
new Action("admin/getbanned", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
unbanBt.setVisible(false);
bannedList.setSelectedIndex(-1);
onBannedPlayerLoaded(data);
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private void onBannedPlayerLoaded(AnswerData data) {
ArrayList<BannedPlayer> bannedPlayers = new ArrayList<BannedPlayer>();
PlayersInfosData playersInfosData = data.getPlayersInfosData();
int length = playersInfosData.getPlayersInfosCount();
for(int i=0;i<length;i++) {
bannedPlayers.add(new BannedPlayer(playersInfosData.getPlayerInfosDataAt(i)));
}
bannedList.setItems(bannedPlayers);
}
private void unbanPlayer() {
HashMap<String,String> params = new HashMap<String,String>();
params.put("id", String.valueOf(((BannedPlayer) bannedList.getSelectedItem()).getId()));
new Action("admin/unban", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
getBanned();
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private void getMotd() {
HashMap<String,String> params = new HashMap<String,String>();
new Action("admin/getmotd", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
motd.clear();
MotdsData motds = data.getMotdsData();
for(int i=0;i<motds.getMotdCount();i++) {
motd.add(motds.getMotdDataAt(i));
}
motdModerators.getElement().setInnerHTML(Utilities.parseSmilies(getMotdAt(1)));
layoutGeneral.update();
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private void getScriptList() {
HashMap<String,String> params = new HashMap<String,String>();
new Action("admin/getscripts", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
scriptList.clear();
ScriptsData scriptsData = data.getScriptsData();
for(int i=0;i<scriptsData.getScriptCount();i++) {
scriptList.add(scriptsData.getScriptDataAt(i).getName());
}
scriptSelection.setItems(scriptList);
layoutScripts.update();
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private void executeScript() {
HashMap<String,String> params = new HashMap<String,String>();
params.put("name", ((String) scriptSelection.getSelectedItem()));
loadingLabel.setVisible(true);
new Action("admin/usescript", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
ScriptData scriptData = data.getScriptData();
scriptAnswer.getElement().setInnerHTML(scriptData.getMessage());
loadingLabel.setVisible(false);
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private void checkMultiAccounts() {
HashMap<String,String> params = new HashMap<String,String>();
params.put("player1", ((String) player1.getText()));
params.put("player2", ((String) player2.getText()));
new Action("admin/checkmultiplesaccounts", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
PlayerInfosData playerInfosData = data.getPlayerInfosData();
ArrayList<PlayerInfos> multiAccountsPlayers = new ArrayList<PlayerInfos>();
multiAccountsPlayers.add(new PlayerInfos(playerInfosData));
multiAccountsList.setItems(multiAccountsPlayers);
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
private static class BannedPlayer {
int idPlayer;
String login;
boolean gameBanned;
String reason;
String date;
public BannedPlayer() {}
public BannedPlayer(PlayerInfosData data) {
this.idPlayer = data.getId();
this.login = data.getLogin();
this.gameBanned = data.isBanned();
this.reason = data.getReason();
this.date = data.getDate();
}
public final String toString() {
return "<table cellspacing=\"0\" style=\"width: 100%;\"><tr>" +
"<td style=\"width: 25%;\">" + login + "</td>" +
"<td class=\"center\" style=\"width: 25%;\">" + reason + "</td>" +
"<td class=\"center\" style=\"width: 25%;\">" + (!gameBanned? "Chat":"Jeu") + "</td>" +
"<td class=\"date right\" style=\"width: 25%;\">" +
date + " </td>" +
"</tr></table>";
}
public int getId() {
return idPlayer;
}
public boolean isGameBanned() {
return gameBanned;
}
public String getTabHeader() {
return "<table cellspacing=\"0\" style=\"width: 100%;\"><tr>" +
"<td style=\"width: 25%;\"> Pseudo </td>" +
"<td class=\"center\" style=\"width: 25%;\"> Raison </td>" +
"<td class=\"center\" style=\"width: 25%;\"> Type </td>" +
"<td class=\"date right\" style=\"width: 25%;\">" +
"Jusqu'au </td>" +
"</tr></table>";
}
}
private static class PlayerInfos {
String login;
String otherLogin;
String reason;
int probability;
int lastIp;
String color;
public PlayerInfos() {}
public PlayerInfos(PlayerInfosData data) {
this.login = data.getLogin();
this.otherLogin = data.getOtherLogin();
this.lastIp = data.getRedundantIp();
this.probability = data.getProbability();
this.reason = data.getReason();
if(probability<20) {
color = "#347C2C";
}
else if(probability>=20 && probability<40) {
color = "#667C26";
}
else if(probability>=40 && probability<70) {
color = "#F88017";
}
else {
color = "#FF0000";
}
}
public final String toString() {
Utilities.log("Avant toString");
return "<table cellspacing=\"0\" style=\"width: 100%;\"><tr>" +
"<td class=\"center\" style=\"width: 15%;\">" + login + "</td>" +
"<td class=\"center\" style=\"width: 15%;\">" + otherLogin + "</td>" +
"<td class=\"center\" style=\"width: 15%; color:"+color+";\">" + probability+"% </td>" +
"<td class=\"center\" style=\"width: 20%;\">" +(lastIp!=0? Utilities.long2ip(lastIp):"")+ "</td>" +
"<td class=\"center\" style=\"width: 35%;\">" +reason+ "</td>" +
"</tr></table>";
}
public String getTabHeader() {
return "<table cellspacing=\"0\" style=\"width: 100%;\"><tr>" +
"<td class=\"center\" style=\"width: 15%;\"> Joueur 1 </td>" +
"<td class=\"center\" style=\"width: 15%;\">Joueur 2</td>" +
"<td class=\"center\" style=\"width: 15%;\">Probabilité</td>" +
"<td class=\"center\" style=\"width: 20%;\">ip commune</td>" +
"<td class=\"center\" style=\"width: 35%;\">Description détaillée</td>" +
"</tr></table>";
}
}
private class BanPlayerDialog extends JSDialog implements ClickListener, ActionCallback {
private JSRowLayout mainLayout;
private JSTextField playerLogin, banTimeDay, banTimeHour, banTimeMinute;
private JSLabel playerLoginLabel, banReasonLabel,banTypeLabel, banTimeLabel, banTimeDayLabel,
banTimeHourLabel, banTimeMinuteLabel;
private JSComboBox banType;
private JSTextPane banReason;
private JSButton confirmBt, cancelBt;
AdministrationPanelDialog administrationPanelDialog;
public BanPlayerDialog(AdministrationPanelDialog administrationPanelDialog) {
super("Bannir un joueur", true, true, true);
this.administrationPanelDialog = administrationPanelDialog;
playerLoginLabel = new JSLabel("Pseudo: ");
playerLoginLabel.setPixelWidth(120);
playerLogin = new JSTextField();
playerLogin.setPixelWidth(200);
banTimeLabel = new JSLabel("Temps: ");
banTimeLabel.setPixelWidth(120);
banTimeDayLabel = new JSLabel(" j");
banTimeDayLabel.setPixelWidth(20);
banTimeHourLabel = new JSLabel(" h");
banTimeHourLabel.setPixelWidth(20);
banTimeMinuteLabel = new JSLabel(" m");
banTimeMinuteLabel.setPixelWidth(20);
banTimeDay = new JSTextField();
banTimeDay.setPixelWidth(30);
banTimeHour = new JSTextField();
banTimeHour.setPixelWidth(30);
banTimeMinute = new JSTextField();
banTimeMinute.setPixelWidth(30);
banTypeLabel = new JSLabel("Type de ban: ");
banTypeLabel.setPixelWidth(120);
banType = new JSComboBox();
banType.setPixelWidth(120);
banType.addItem("Chat");
if(Settings.isAdministrator()) {
banType.addItem("Jeu");
}
banReasonLabel = new JSLabel("Raison: ");
banReasonLabel.setPixelWidth(160);
banReason = new JSTextPane();
banReason.setPixelSize(320, 120);
confirmBt = new JSButton("Bannir");
confirmBt.setPixelWidth(160);
confirmBt.addClickListener(this);
cancelBt = new JSButton("Annuler");
cancelBt.setPixelWidth(160);
cancelBt.addClickListener(this);
mainLayout = new JSRowLayout();
mainLayout.addComponent(playerLoginLabel);
mainLayout.addComponent(playerLogin);
mainLayout.addRow();
mainLayout.addComponent(banTimeLabel);
mainLayout.addComponent(banTimeDay);
mainLayout.addComponent(banTimeDayLabel);
mainLayout.addComponent(banTimeHour);
mainLayout.addComponent(banTimeHourLabel);
mainLayout.addComponent(banTimeMinute);
mainLayout.addComponent(banTimeMinuteLabel);
mainLayout.addRow();
mainLayout.addComponent(banTypeLabel);
mainLayout.addComponent(banType);
mainLayout.addRow();
mainLayout.addComponent(banReasonLabel);
mainLayout.addRow();
mainLayout.addComponent(banReason);
mainLayout.addRow();
mainLayout.addComponent(confirmBt);
mainLayout.addComponent(cancelBt);
setComponent(mainLayout);
centerOnScreen();
}
public void onClick(Widget sender) {
if(sender == confirmBt) {
if(playerLogin.getText().length()>0 &&
(banTimeDay.getText().length()>0 || banTimeHour.getText().length()>0 || banTimeMinute.getText().length()>0)
&& banType.getSelectedIndex()>=0) {
banPlayer();
}
}
else if(sender == cancelBt) {
setVisible(false);
}
}
private void banPlayer() {
HashMap<String,String> params = new HashMap<String,String>();
int days = banTimeDay.getText().length()>0? Integer.parseInt(banTimeDay.getText()) : 0;
int hours = banTimeHour.getText().length()>0? Integer.parseInt(banTimeHour.getText()) : 0;
int minutes = banTimeMinute.getText().length()>0? Integer.parseInt(banTimeMinute.getText()) : 0;
long time = (days*24*3600) + (hours*3600) + (minutes*60);
params.put("login", playerLogin.getText());
params.put("time", String.valueOf(time));
params.put("reason", banReason.getHTML());
params.put("bangame", String.valueOf(banType.getSelectedIndex()==0? false : true));
new Action("admin/ban", params, this);
}
public void onSuccess(AnswerData data) {
administrationPanelDialog.refreshBannedList();
setVisible(false);
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
} //End BanPlayerDialog
private class MotdDialog extends JSDialog implements SelectionListener, ClickListener {
private JSRowLayout mainLayout;
private JSLabel typeLabel;
private JSComboBox type;
private JSTextPane content;
private JSButton confirmBt, cancelBt;
private AdministrationPanelDialog administrationPanelDialog;
public MotdDialog(AdministrationPanelDialog administrationPanelDialog) {
super("Message du jour",true,true,true);
this.administrationPanelDialog = administrationPanelDialog;
if(!Settings.isAdministrator()) {
setVisible(false);
return;
}
typeLabel = new JSLabel("Type: ");
typeLabel.setPixelWidth(120);
type = new JSComboBox();
type.setPixelWidth(200);
type.addItem("Chat");
type.addItem("Moderateur");
type.addSelectionListener(this);
content = new JSTextPane();
content.setPixelSize(320, 120);
content.setHTML(administrationPanelDialog.getMotdAt(0));
confirmBt = new JSButton("Confirmer");
confirmBt.setPixelWidth(160);
confirmBt.addClickListener(this);
cancelBt = new JSButton("Annuler");
cancelBt.setPixelWidth(160);
cancelBt.addClickListener(this);
mainLayout = new JSRowLayout();
mainLayout.addComponent(typeLabel);
mainLayout.addComponent(type);
mainLayout.addRow();
mainLayout.addComponent(content);
mainLayout.addRow();
mainLayout.addComponent(confirmBt);
mainLayout.addComponent(cancelBt);
setComponent(mainLayout);
centerOnScreen();
}
public void onClick(Widget sender) {
if(sender == confirmBt) {
changeMotd();
}
else if(sender == cancelBt) {
setVisible(false);
}
}
private void changeMotd() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", (String.valueOf(type.getSelectedIndex())));
params.put("content", content.getHTML());
new Action("admin/changemotd", params, new ActionCallback() {
public void onSuccess(AnswerData data) {
administrationPanelDialog.refreshMotd();
setVisible(false);
}
public void onFailure(String error) {
ActionCallbackAdapter.onFailureDefaultBehavior(error);
}
});
}
public void selectionChanged(Widget sender, int newValue, int oldValue) {
if(sender == type) {
if(content.getHTML().equals(administrationPanelDialog.getMotdAt(oldValue))) {
content.setHTML(administrationPanelDialog.getMotdAt(newValue));
mainLayout.update();
}
}
}
}
/**
* layout pour les bugs reports
* @author Ghost
* @todo Ghost commencer!
*/
private class LayoutBugsReports extends JSRowLayout {
public LayoutBugsReports(){
}
}
} //End AdministrationPanelDialog
| agpl-3.0 |
apotocki/fex | src/main/java/org/aksw/simba/quetsal/configuration/QuetzalConfig.java | 6124 | package org.aksw.simba.quetsal.configuration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.sail.memory.MemoryStore;
import com.fluidops.fedx.Config;
import com.fluidops.fedx.FedXFactory;
import com.fluidops.fedx.exception.FedXException;
/**
* Quetzal configurations setup. Need to run one time in the start before query execution
* @author Saleem
*
*/
public class QuetzalConfig {
static Logger log = Logger.getLogger(Config.class);
static Repository sumRepository = null;
public static RepositoryConnection con = null;
public static ArrayList<String> dataSources = new ArrayList<String>() ;
public static ArrayList<String> commonPredicates = new ArrayList<String>(); // list of common predicates. Note we use this in ASK_dominent Source selection Algorithm
public static double commonPredThreshold; //A threshold value for a predicate ( in % of total data sources) to be considered in common predicate list
//public static SailRepository repo;
public static enum Mode {
INDEX_DOMINANT,
ASK_DOMINANT
}
public static Mode mode; // Index_dominant , ASK_dominant. In first type of mode we make use of sbj, obj authorities to find relevant sources for triple patterns with bound subject or objects e.g ?s owl:sameAs <http://dbpedia.org/resource/Barack_Obama>, we will perform index lookup for predicate owl:sameAs and objAuthority <http://dbpedia.org> and all the qualifying sources will be added to the set of capable sources for that triple pattern.
// In hybrid mode we make use of SPARQL ASK queries for bound subjects or objects of a common predicate such as owl:sameAs. If Predicate is not common then we use index sbj ,obj authorities parts as explained above
public static void initialize()
{
try {
mode = Mode.valueOf(Config.getProperty("quetzal.mode", "ASK_DOMINANT"));
commonPredThreshold = Double.parseDouble(Config.getProperty("quetzal.inputCommonPredThreshold", "0.33"));
loadFedSummaries(Config.getProperty("quetzal.fedSummaries"));
//loadDataSources(); skip, must be initialized explicitly by user
if (mode == Mode.ASK_DOMINANT)
loadCommonPredList();
} catch (IOException e) {
throw new FedXException(e);
}
}
public static void reset()
{
con.close();
con = null;
sumRepository.shutDown();
sumRepository = null;
}
/**
* Quetzal Configurations. Must call this method once before starting source selection.
* mode can be either set to Index_dominant or ASK_dominant. See details in FedSum paper.
* @param inputCommonPredThreshold Threshold value between common and normal predicates
* @param inputMode Source Selection mode i.e. Index_dominant or ASK_dominant
* @param InputFedSummaries Summaries of all the available data sources
* @throws Exception Errors
*/
@Deprecated
public static void initialize(String inputFedSummaries, Mode inputMode, double inputCommonPredThreshold) throws Exception
{
Config.initialize();
mode = inputMode; //{ASK_dominant, Index_dominant}
commonPredThreshold = inputCommonPredThreshold; //considered a predicate as common predicate if it is present in 33% available data sources
//long startTime = System.currentTimeMillis();
loadFedSummaries(inputFedSummaries);
//System.out.println("Index Load Time: "+ (System.currentTimeMillis()-startTime));
loadDataSources();
if (mode == Mode.ASK_DOMINANT)
loadCommonPredList();
}
/**
* Initialize list of SPARQL endpoints from FedSummaires
* @throws Exception Errors
*/
public static void loadDataSources()
{
String queryString = "SELECT DISTINCT ?url WHERE {?s <http://aksw.org/quetsal/url> ?url }";
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
TupleQueryResult result = tupleQuery.evaluate();
while(result.hasNext())
{
dataSources.add(result.next().getValue("url").stringValue());
}
FedXFactory.initializeSparqlFederation(dataSources);
}
/**
* Load common predicate list using the threshold value specified as input
*/
public static void loadCommonPredList() {
String queryString = "Prefix ds:<http://aksw.org/fedsum/> "
+ "SELECT DISTINCT ?p "
+ " WHERE {?s ds:predicate ?p. }";
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
TupleQueryResult result = tupleQuery.evaluate();
ArrayList<String> FedSumPredicates = new ArrayList<String>();
while(result.hasNext())
{
FedSumPredicates.add(result.next().getValue("p").stringValue());
}
//---check each distinct
for (String predicate : FedSumPredicates)
{
int count = 0;
queryString = "Prefix ds:<http://aksw.org/fedsum/> "
+ "SELECT Distinct ?url "
+ " WHERE {?s ds:url ?url. "
+ " ?s ds:capability ?cap. "
+ " ?cap ds:predicate <" + predicate + "> }" ;
tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
result = tupleQuery.evaluate();
while(result.hasNext())
{
result.next();
count++;
}
double threshold = (double) count/dataSources.size();
if(threshold>=commonPredThreshold)
commonPredicates.add(predicate);
}
// System.out.println(commonPredicates);
}
/**
* Load HiBISCuS Summaries file into sesame in memory model
* @param theFedSummaries Summaries file
* @throws IOException
*/
public static void loadFedSummaries(String theFedSummaries) throws IOException {
File curfile = new File ("summaries/memorystore.data");
curfile.delete();
File fileDir = new File("summaries/");
sumRepository = new SailRepository( new MemoryStore(fileDir) );
sumRepository.initialize();
File file = new File(theFedSummaries);
con = sumRepository.getConnection();
con.add(file, "aksw.org.simba", RDFFormat.N3);
}
}
| agpl-3.0 |
aborg0/rapidminer-vega | src/com/rapidminer/io/process/conditions/ParameterUnequalsCondition.java | 1571 | /*
* RapidMiner
*
* Copyright (C) 2001-2011 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.io.process.conditions;
import org.w3c.dom.Element;
import com.rapidminer.operator.Operator;
/**
*
* @author Sebastian Land
*/
public class ParameterUnequalsCondition extends ParameterEqualsCondition {
public ParameterUnequalsCondition(Element element) {
super(element);
}
@Override
public boolean isSatisfied(Operator operator) {
String specifiedValue = operator.getParameters().getParameterAsSpecified(parameterKey);
return
operator.getParameters().isSpecified(parameterKey) &&
!parameterValue.equals(specifiedValue);
}
@Override
public String toString() {
return parameterKey + "!='"+parameterValue+"'";
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcConnectionSurfaceGeometry.java | 5177 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc4;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public interface IfcConnectionSurfaceGeometry extends IfcConnectionGeometry {
/**
* Returns the value of the '<em><b>Surface On Relating Element</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Surface On Relating Element</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Surface On Relating Element</em>' reference.
* @see #setSurfaceOnRelatingElement(IfcSurfaceOrFaceSurface)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcConnectionSurfaceGeometry_SurfaceOnRelatingElement()
* @model
* @generated
*/
IfcSurfaceOrFaceSurface getSurfaceOnRelatingElement();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcConnectionSurfaceGeometry#getSurfaceOnRelatingElement <em>Surface On Relating Element</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Surface On Relating Element</em>' reference.
* @see #getSurfaceOnRelatingElement()
* @generated
*/
void setSurfaceOnRelatingElement(IfcSurfaceOrFaceSurface value);
/**
* Returns the value of the '<em><b>Surface On Related Element</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Surface On Related Element</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Surface On Related Element</em>' reference.
* @see #isSetSurfaceOnRelatedElement()
* @see #unsetSurfaceOnRelatedElement()
* @see #setSurfaceOnRelatedElement(IfcSurfaceOrFaceSurface)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcConnectionSurfaceGeometry_SurfaceOnRelatedElement()
* @model unsettable="true"
* @generated
*/
IfcSurfaceOrFaceSurface getSurfaceOnRelatedElement();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcConnectionSurfaceGeometry#getSurfaceOnRelatedElement <em>Surface On Related Element</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Surface On Related Element</em>' reference.
* @see #isSetSurfaceOnRelatedElement()
* @see #unsetSurfaceOnRelatedElement()
* @see #getSurfaceOnRelatedElement()
* @generated
*/
void setSurfaceOnRelatedElement(IfcSurfaceOrFaceSurface value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcConnectionSurfaceGeometry#getSurfaceOnRelatedElement <em>Surface On Related Element</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetSurfaceOnRelatedElement()
* @see #getSurfaceOnRelatedElement()
* @see #setSurfaceOnRelatedElement(IfcSurfaceOrFaceSurface)
* @generated
*/
void unsetSurfaceOnRelatedElement();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcConnectionSurfaceGeometry#getSurfaceOnRelatedElement <em>Surface On Related Element</em>}' reference is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Surface On Related Element</em>' reference is set.
* @see #unsetSurfaceOnRelatedElement()
* @see #getSurfaceOnRelatedElement()
* @see #setSurfaceOnRelatedElement(IfcSurfaceOrFaceSurface)
* @generated
*/
boolean isSetSurfaceOnRelatedElement();
} // IfcConnectionSurfaceGeometry
| agpl-3.0 |
free-erp/invoicing | invoicing_client/src/org/free_erp/client/ui/report/sale/CSaleIndentCustomerStatWindow.java | 8811 | /*
* Copyright 2013, TengJianfa , and other 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.free_erp.client.ui.report.sale;
import com.jdatabeans.beans.CField;
import com.jdatabeans.beans.CMoneyField;
import com.jdatabeans.beans.CPanel;
import com.jdatabeans.beans.data.IDataRow;
import com.jdatabeans.beans.data.JDataDatePicker;
import com.jdatabeans.beans.data.JDataTableComboBox;
import com.jdatabeans.beans.data.ObjectDataRow;
import com.jdatabeans.beans.data.table.ITableColumnModel;
import com.jdatabeans.beans.data.table.ITableModel;
import com.jdatabeans.beans.data.table.JDataTableColumn;
import com.jdatabeans.print.CPrintDialog;
import org.free_erp.client.ui.main.Main;
import org.free_erp.client.ui.report.CBaseQueryWindow;
import org.free_erp.client.ui.util.ReportUtilities;
import org.free_erp.client.ui.util.ReportVO;
import org.free_erp.service.entity.base.Customer;
import org.free_erp.service.entity.base.Employee;
import org.free_erp.service.entity.sale.SaleOrderDetailPo;
import org.free_erp.service.entity.system.Permission;
import org.free_erp.service.logic.IPermissionsService;
import org.free_erp.service.logic.ISaleService;
import org.free_erp.service.logic.sale.SaleQueryVo;
import java.awt.Dimension;
import java.awt.Image;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
/**
* ÏúÊÛ¶©µ¥¿ÍÉÌͳ¼Æ
*
* @author TengJianfa mobile:086-13003311398 qq:575633370 www.free-erp.com
*/
public class CSaleIndentCustomerStatWindow extends CBaseQueryWindow
{
private JDataTableComboBox supplierField;
private JDataTableComboBox adminField;
private JDataDatePicker beginDateField;
private JDataDatePicker endDateField;
public CSaleIndentCustomerStatWindow(String title)
{
super(title);
}
@Override
protected void clearInfo()
{
this.beginDateField.setSelectedItem("");
this.endDateField.setSelectedItem("");
this.supplierField.setText("");
this.adminField.setText("");
}
@Override
protected void select()
{
SaleQueryVo vo = new SaleQueryVo(Main.getMainFrame().getCompany());
vo.setStatus(1);
if(this.supplierField.getText() != null && !this.supplierField.getText().equals(""))
{
vo.setSupplier((Customer)this.supplierField.getSelectedItem());
}
if(this.adminField.getText() != null && !this.adminField.getText().equals(""))
{
vo.setEmployee((Employee)this.adminField.getSelectedItem());
}
// if(this.numberField.getText() != null && !this.numberField.getText().trim().equals(""))
// {
// vo.setProductNumber(this.numberField.getText().trim());
// }
Object obj = null;
if(!beginDateField.getEditorText().equals(""))
{
obj = beginDateField.getSelectedItem();
if(obj != null && obj instanceof Date)
{
Date startDate = (Date)obj;
vo.setStartDatePo(startDate);
}
}
if(!endDateField.getEditorText().equals(""))
{
obj = endDateField.getSelectedItem();
if(obj != null && obj instanceof Date)
{
Date endDate = (Date)obj;
vo.setEndDatePo(endDate);
}
}
ITableModel model = this.dataTable.getTableModel();
ISaleService saleService = Main.getServiceManager().getSaleService();
this.dataSource.clear();
// vo.setWay(1);
List<SaleOrderDetailPo> SaleOrderPos =saleService.findSaleOrderCustomerProductDaetails(vo);
if(SaleOrderPos == null || SaleOrderPos.size() == 0)
{
this.clearInfo();
}
for(SaleOrderDetailPo po : SaleOrderPos)
{
IDataRow dataRow = new ObjectDataRow(po, "id", null);
model.insertDataRow(dataRow);
}
}
@Override
protected CPanel getMainPanel()
{
CPanel panel = new CPanel();
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(700,40));
panel.setLayout(null);
beginDateField = new JDataDatePicker();
endDateField = new JDataDatePicker();
endDateField.setSelectedItem("");
beginDateField.setSelectedItem("");
supplierField = new JDataTableComboBox("", Customer.class,this.dataSource,Main.getMainFrame().getObjectsPool().getCustomerTable() , "name");
adminField = new JDataTableComboBox("",Employee.class,this.dataSource,Main.getMainFrame().getObjectsPool().getEmployeeTable() , "name");
int x = 50;
int y = 10;
panel.addComponent(supplierField, x, y, 120, 20, "¿ÍÉÌ", 40);
panel.addComponent(adminField, x + 170, y, 100, 20, "ÒµÎñÔ±", 50);
panel.addComponent(beginDateField, x + 320, y, 100, 20, "²éѯʱ¼ä", 50);
panel.addComponent(endDateField, x + 440, y, 100, 20, "ÖÁ", 20);
panel.addComponent(selectButton, x + 545, y, 75, 25);
panel.addComponent(clearButton, x + 625, y, 75, 25);
return panel;
}
@Override
protected void initColumns()
{
ITableColumnModel columnModel = this.dataTable.getTableColumnModel();
JDataTableColumn column = new JDataTableColumn();
column.setHeaderText("¿Í»§±àºÅ");
column.setColumnName("customer.number");
column.setWidth(120);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("¿Í»§Ãû³Æ");
column.setColumnName("customer.name");
column.setWidth(80);
// column.setValueType(Date.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("ÊýÁ¿");
column.setColumnName("amount");
column.setWidth(80);
// column.setValueType(Date.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("½ð¶î");
column.setColumnName("totalMoney");
column.setWidth(80);
column.setValueType(Currency.class);
columnModel.addColumn(column);
// column = new JDataTableColumn();
// column.setHeaderText("ÏúÍ˽ð¶î");
// column.setColumnName("formDate");
// column.setWidth(80);
// column.setValueType(Date.class);
// columnModel.addColumn(column);
}
protected String getExcelExportTitle()
{
return "¿Í»§¶©µ¥Í³¼Æ";
}
protected void doPrint()
{
Map variables = new HashMap();
ReportVO vo=new ReportVO();
Image image = Main.getMainFrame().getCompanyLogo();
vo.setImage(image);
vo.setTitle("¿Í»§¶©µ¥Í³¼Æ±¨±í");
variables = ReportUtilities.creatParameterMap(vo);
CPrintDialog printDialog = new CPrintDialog(Main.getMainFrame(), this.getClass().getResourceAsStream("/com/e68erp/demo/client/report/jaspers/sale/rCcustomerSaleStat.jasper"),variables, this.dataSource.getDataRows());
printDialog.setVisible(true);
}
@Override
protected CPanel getTotalPanel()
{
CPanel bottomPanel = new CPanel();
bottomPanel.setPreferredSize(new Dimension(600, 40));
this.totalAmountField = new CField();
this.totalMoneyField = new CMoneyField();
this.totalAmountField.setEditable(false);
bottomPanel.addComponent(totalAmountField, 100, 10, 150, 20, "ºÏ¼ÆÊýÁ¿", 60);
bottomPanel.addComponent(totalMoneyField, 320, 10, 150, 20, "ºÏ¼Æ½ð¶î", 60);
return bottomPanel;
}
}
| lgpl-2.1 |
HubSpot/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/grammars/VarargTest.java | 2006 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2016 the original author or authors.
//
// 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.puppycrawl.tools.checkstyle.grammars;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* Tests varargs can be parsed.
* @author Michael Studman
*/
public class VarargTest
extends BaseCheckTestSupport {
@Override
protected String getPath(String filename) throws IOException {
return super.getPath("grammars" + File.separator + filename);
}
@Test
public void testCanParse()
throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(MemberNameCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputVararg.java"), expected);
}
}
| lgpl-2.1 |
trejkaz/jna | contrib/platform/src/com/sun/jna/platform/unix/solaris/LibKstat.java | 16563 | /* Copyright (c) 2017 Daniel Widdis, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna.platform.unix.solaris;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.Union;
/**
* Kstat library. The kstat facility is a general-purpose mechanism for
* providing kernel statistics to users.
*
* @author widdis[at]gmail[dot]com
*/
public interface LibKstat extends Library {
LibKstat INSTANCE = Native.loadLibrary("kstat", LibKstat.class);
/*
* Kstat Data Types
*/
// The "raw" kstat type is just treated as an array of bytes. This is
// generally used to export well-known structures, like sysinfo.
byte KSTAT_TYPE_RAW = 0;
byte KSTAT_TYPE_NAMED = 1; // name/value pairs
byte KSTAT_TYPE_INTR = 2; // interrupt statistics
byte KSTAT_TYPE_IO = 3; // I/O statistics
byte KSTAT_TYPE_TIMER = 4; // event timers
/*
* KstatNamed Data Types (for selecting from Union)
*/
byte KSTAT_DATA_CHAR = 0;
byte KSTAT_DATA_INT32 = 1;
byte KSTAT_DATA_UINT32 = 2;
byte KSTAT_DATA_INT64 = 3;
byte KSTAT_DATA_UINT64 = 4;
byte KSTAT_DATA_STRING = 9;
/*
* KstatIntr Interrupts
*/
int KSTAT_INTR_HARD = 0;
int KSTAT_INTR_SOFT = 1;
int KSTAT_INTR_WATCHDOG = 2;
int KSTAT_INTR_SPURIOUS = 3;
int KSTAT_INTR_MULTSVC = 4;
int KSTAT_NUM_INTRS = 5;
int KSTAT_STRLEN = 31; // 30 chars + NULL; must be 16 * n - 1
int EAGAIN = 11; // Temporarily busy
/**
* The kernel maintains a linked list of statistics structures, or kstats.
* Each kstat has a common header section and a type-specific data section.
* The header section is defined by the kstat_t structure
*/
class Kstat extends Structure {
// Fields relevant to both kernel and user
public long ks_crtime; // creation time
public Pointer ks_next; // kstat chain linkage
public int ks_kid; // unique kstat ID
public byte[] ks_module = new byte[KSTAT_STRLEN]; // module name
public byte ks_resv; // reserved
public int ks_instance; // module's instance
public byte[] ks_name = new byte[KSTAT_STRLEN]; // kstat name
public byte ks_type; // kstat data type
public byte[] ks_class = new byte[KSTAT_STRLEN]; // kstat class
public byte ks_flags; // kstat flags
public Pointer ks_data; // kstat type-specific data
public int ks_ndata; // # of data records
public long ks_data_size; // size of kstat data section
public long ks_snaptime; // time of last data snapshot
// Fields relevant to kernel only
public int ks_update; // dynamic update function
public Pointer ks_private; // provider-private data
public int ks_snapshot; // snapshot function
public Pointer ks_lock; // protects this kstat's data
public Kstat next() {
if (ks_next == null) {
return null;
}
Kstat n = new Kstat();
n.useMemory(ks_next);
n.read();
return n;
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "ks_crtime", "ks_next", "ks_kid", "ks_module", "ks_resv", "ks_instance",
"ks_name", "ks_type", "ks_class", "ks_flags", "ks_data", "ks_ndata", "ks_data_size", "ks_snaptime",
"ks_update", "ks_private", "ks_snapshot", "ks_lock" });
}
}
/**
* A list of arbitrary name=value statistics.
*/
class KstatNamed extends Structure {
public byte[] name = new byte[KSTAT_STRLEN]; // name of counter
public byte data_type; // data type
public UNION value; // value of counter
public static class UNION extends Union {
public byte[] charc = new byte[16]; // enough for 128-bit ints
public int i32;
public int ui32;
public long i64;
public long ui64;
public STR str;
public static class STR extends Structure {
public Pointer addr;
public int len; // length of string
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "addr", "len" });
}
}
}
public KstatNamed() {
super();
}
public KstatNamed(Pointer p) {
super(p);
read();
}
@Override
public void read() {
super.read();
switch (data_type) {
case KSTAT_DATA_CHAR:
value.setType(byte[].class);
break;
case KSTAT_DATA_STRING:
value.setType(UNION.STR.class);
break;
case KSTAT_DATA_INT32:
case KSTAT_DATA_UINT32:
value.setType(int.class);
break;
case KSTAT_DATA_INT64:
case KSTAT_DATA_UINT64:
value.setType(long.class);
break;
default:
break;
}
value.read();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "name", "data_type", "value" });
}
}
/**
* Interrupt statistics. An interrupt is a hard interrupt (sourced from the
* hardware device itself), a soft interrupt (induced by the system via the
* use of some system interrupt source), a watchdog interrupt (induced by a
* periodic timer call), spurious (an interrupt entry point was entered but
* there was no interrupt to service), or multiple service (an interrupt was
* detected and serviced just prior to returning from any of the other
* types).
*/
class KstatIntr extends Structure {
public int[] intrs = new int[KSTAT_NUM_INTRS]; // interrupt counters
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "intrs" });
}
}
/**
* Event timer statistics. These provide basic counting and timing
* information for any type of event.
*/
class KstatTimer extends Structure {
public byte[] name = new byte[KSTAT_STRLEN]; // event name
public byte resv; // reserved
public long num_events; // number of events
public long elapsed_time; // cumulative elapsed time
public long min_time; // shortest event duration
public long max_time; // longest event duration
public long start_time; // previous event start time
public long stop_time; // previous event stop time
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "name", "resv", "num_events", "elapsed_time", "min_time", "max_time",
"start_time", "stop_time" });
}
}
/**
* IO Statistics.
*/
class KstatIO extends Structure {
// Basic counters.
public long nread; // number of bytes read
public long nwritten; // number of bytes written
public int reads; // number of read operations
public int writes; // number of write operations
/*-
* Accumulated time and queue length statistics.
*
* Time statistics are kept as a running sum of "active" time.
* Queue length statistics are kept as a running sum of the
* product of queue length and elapsed time at that length --
* that is, a Riemann sum for queue length integrated against time.
* ^
* | _________
* 8 | i4 |
* | | |
* Queue 6 | |
* Length | _________ | |
* 4 | i2 |_______| |
* | | i3 |
* 2_______| |
* | i1 |
* |_______________________________|
* Time-- t1 t2 t3 t4
*
* At each change of state (entry or exit from the queue),
* we add the elapsed time (since the previous state change)
* to the active time if the queue length was non-zero during
* that interval; and we add the product of the elapsed time
* times the queue length to the running length*time sum.
*
* This method is generalizable to measuring residency
* in any defined system: instead of queue lengths, think
* of "outstanding RPC calls to server X".
*
* A large number of I/O subsystems have at least two basic
* "lists" of transactions they manage: one for transactions
* that have been accepted for processing but for which processing
* has yet to begin, and one for transactions which are actively
* being processed (but not done). For this reason, two cumulative
* time statistics are defined here: pre-service (wait) time,
* and service (run) time.
*
* The units of cumulative busy time are accumulated nanoseconds.
* The units of cumulative length*time products are elapsed time
* times queue length.
*/
public long wtime; // cumulative wait (pre-service) time
public long wlentime; // cumulative wait length*time product
public long wlastupdate; // last time wait queue changed
public long rtime; // cumulative run (service) time
public long rlentime; // cumulative run length*time product
public long rlastupdate; // last time run queue changed
public int wcnt; // count of elements in wait state
public int rcnt; // count of elements in run state
public KstatIO() {
super();
}
public KstatIO(Pointer p) {
super(p);
read();
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "nread", "nwritten", "reads", "writes", "wtime", "wlentime",
"wlastupdate", "rtime", "rlentime", "rlastupdate", "wcnt", "rcnt" });
}
}
class KstatCtl extends Structure {
public int kc_chain_id; // current kstat chain ID
public Kstat kc_chain; // pointer to kstat chain
public int kc_kd; // /dev/kstat descriptor - not public interface
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "kc_chain_id", "kc_chain", "kc_kd" });
}
}
/**
* The kstat_open() function initializes a kstat control structure, which
* provides access to the kernel statistics library.
*
* @return A pointer to this structure, which must be supplied as the kc
* argument in subsequent libkstat function calls.
*/
KstatCtl kstat_open();
/**
* The kstat_close() function frees all resources that were associated with
* kc.
*
* @param kc
* a kstat control structure
* @return 0 on success and -1 on failure.
*/
int kstat_close(KstatCtl kc);
/**
* The kstat_chain_update() function brings the user's kstat header chain in
* sync with that of the kernel. The kstat chain is a linked list of kstat
* headers (kstat_t's) pointed to by kc.kc_chain, which is initialized by
* kstat_open(3KSTAT). This chain constitutes a list of all kstats currently
* in the system. During normal operation, the kernel creates new kstats and
* delete old ones as various device instances are added and removed,
* thereby causing the user's copy of the kstat chain to become out of date.
* The kstat_chain_update() function detects this condition by comparing the
* kernel's current kstat chain ID(KCID), which is incremented every time
* the kstat chain changes, to the user's KCID, kc.kc_chain_id. If the KCIDs
* match, kstat_chain_update() does nothing. Otherwise, it deletes any
* invalid kstat headers from the user's kstat chain, adds any new ones, and
* sets kc.kc_chain_id to the new KCID. All other kstat headers in the
* user's kstat chain are unmodified.
*
* @param kc
* a kstat control structure
* @return the new KCID if the kstat chain has changed, 0 if it hasn't, or
* -1 on failure.
*/
int kstat_chain_update(KstatCtl kc);
/**
* kstat_read() gets data from the kernel for the kstat pointed to by ksp.
* ksp.ks_data is automatically allocated (or reallocated) to be large
* enough to hold all of the data. ksp.ks_ndata is set to the number of data
* fields, ksp.ks_data_size is set to the total size of the data, and
* ksp.ks_snaptime is set to the high-resolution time at which the data
* snapshot was taken.
*
* @param kc
* The kstat control structure
* @param ksp
* The kstat from which to retrieve data
* @param p
* If buf is non-NULL , the data is copied from ksp.ks_data into
* buf.
* @return On success, return the current kstat chain ID (KCID). On failure,
* return -1.
*/
int kstat_read(KstatCtl kc, Kstat ksp, Pointer p);
/**
* kstat_write() writes data from buf, or from ksp.ks_data if buf is NULL,
* to the corresponding kstat in the kernel. Only the superuser can use
* kstat_write() .
*
* @param kc
* The kstat control structure
* @param ksp
* The kstat on which to set data
* @param buf
* If buf is non-NULL, the data is copied from buf into
* ksp.ks_data.
* @return On success, return the current kstat chain ID (KCID). On failure,
* return -1.
*/
int kstat_write(KstatCtl kc, Kstat ksp, Pointer buf);
/**
* The kstat_lookup() function traverses the kstat chain, kc.kc_chain,
* searching for a kstat with the same ks_module, ks_instance, and ks_name
* fields; this triplet uniquely identifies a kstat. If ks_module is NULL,
* ks_instance is -1, or ks_name is NULL, then those fields will be ignored
* in the search. For example, kstat_lookup(kc, NULL, -1, "foo") will simply
* find the first kstat with name "foo".
*
* @param kc
* The kstat control structure
* @param ks_module
* The kstat module to search
* @param ks_instance
* The kstat instance number
* @param ks_name
* The kstat name to search
* @return a pointer to the requested kstat if it is found, or NULL if it is
* not.
*/
Kstat kstat_lookup(KstatCtl kc, String ks_module, int ks_instance, String ks_name);
/**
* The kstat_data_lookup() function searches the kstat's data section for
* the record with the specified name . This operation is valid only for
* kstat types which have named data records. Currently, only the
* KSTAT_TYPE_NAMED and KSTAT_TYPE_TIMER kstats have named data records.
*
* @param ksp
* The kstat to search
* @param name
* The key for the name-value pair, or name of the timer as
* applicable
* @return a pointer to the requested data record if it is found. If the
* requested record is not found, or if the kstat type is invalid,
* returns NULL.
*/
Pointer kstat_data_lookup(Kstat ksp, String name);
}
| lgpl-2.1 |
netarchivesuite/netarchivesuite-svngit-migration | tests/dk/netarkivet/testutils/MessageAsserts.java | 1716 | /* File: $Id$
* Version: $Revision$
* Date: $Date$
* Author: $Author$
*
* The Netarchive Suite - Software to harvest and preserve websites
* Copyright 2004-2012 The Royal Danish Library, the Danish State and
* University Library, the National Library of France and the Austrian
* National Library.
*
* 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 dk.netarkivet.testutils;
import junit.framework.TestCase;
import dk.netarkivet.common.distribute.NetarkivetMessage;
/**
* Assertions on JMS/Netarkivet messages
*
*/
public class MessageAsserts {
/** Assert that a message is ok, and if not, print out the error message.
*
* @param s A string explaining what was expected to happen, e.g.
* "Get message on existing file should reply ok"
* @param msg The message to check the status of
*/
public static void assertMessageOk(String s, NetarkivetMessage msg) {
if (!msg.isOk()) {
TestCase.fail(s + ": " + msg.getErrMsg());
}
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | libraries/libformula/src/test/java/org/pentaho/reporting/libraries/formula/function/text/MidFunctionTest.java | 1806 | /*
* 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.FormulaTestBase;
import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
/**
* @author Cedric Pronzato
*/
public class MidFunctionTest extends FormulaTestBase {
public void testDefault() throws Exception {
runDefaultTest();
}
public Object[][] createDataTest() {
return new Object[][]
{
{ "MID(\"123456789\";5;3)", "567" },
{ "MID(\"123456789\";20;3)", "" },
{ "MID(\"123456789\";-1;0)", LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE },
{ "MID(\"123456789\";1;0)", "" },
{ "MID(\"123456789\";2.9;1)", "2" },
{ "MID(\"123456789\";2;2.9)", "23" },
// custom tests
{ "MID(\"123456789\";5;10)", "56789" },
{ "MID(\"123456789\";1;9)", "123456789" },
{ "MID(\"text\";2;2)", "ex" },
{ "MID(123456789;\"3\";4)", "3456" },
};
}
}
| lgpl-2.1 |
pquiring/jfcraft | src/base/jfcraft/opengl/VertexShader.java | 1325 | package jfcraft.opengl;
/** Vertex Shader
*
* @author pquiring
*
* Created : Sept 17, 2013
*/
/*
* uniform = set with glUniform...()
* attribute = points to input array with glVertexAttribPointer()
* varying = passed from vertex shader to fragment shader (shared memory)
*/
public class VertexShader {
public static String source =
"attribute vec2 aTextureCoord;\n" +
"attribute vec2 aTextureCoord2;\n" + //used to show "cracking" overlay
"attribute vec3 aVertexPosition;\n" +
"attribute float aSunLightPercent;\n" +
"attribute float aBlockLightPercent;\n" +
"attribute vec3 aLightColor;\n" +
"\n" +
"uniform mat4 uPMatrix;\n" +
"uniform mat4 uVMatrix;\n" +
"uniform mat4 uMMatrix;\n" +
"\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec2 vTextureCoord2;\n" +
"varying float vLength;\n" +
"varying float vSunLightPercent;\n" +
"varying float vBlockLightPercent;\n" +
"varying vec3 vLightColor;\n" +
"\n" +
"void main() {\n" +
" gl_Position = uPMatrix * uVMatrix * uMMatrix * vec4(aVertexPosition, 1.0);\n" + //NOTE:order of matrix multiply matters
" vTextureCoord = aTextureCoord;\n" +
" vTextureCoord2 = aTextureCoord2;\n" +
" vSunLightPercent = aSunLightPercent;\n" +
" vBlockLightPercent = aBlockLightPercent;\n" +
" vLightColor = aLightColor;\n" +
" vLength = length(gl_Position);\n" +
"}\n";
}
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/enterprise/control/ajax/JSONEvent.java | 4631 | //$HeadURL$
/*---------------- FILE HEADER ------------------------------------------
This file is part of deegree.
Copyright (C) 2001-2008 by:
Department of Geography, University of Bonn
http://www.giub.uni-bonn.de/deegree/
lat/lon GmbH
http://www.lat-lon.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact:
Andreas Poth
lat/lon GmbH
Aennchenstr. 19
53177 Bonn
Germany
E-Mail: poth@lat-lon.de
Prof. Dr. Klaus Greve
Department of Geography
University of Bonn
Meckenheimer Allee 166
53115 Bonn
Germany
E-Mail: greve@giub.uni-bonn.de
---------------------------------------------------------------------------*/
package org.deegree.enterprise.control.ajax;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
import org.deegree.framework.util.FileUtils;
import org.stringtree.json.JSONReader;
/**
*
*
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
* @author last edited by: $Author$
*
* @version. $Revision$, $Date$
*/
public class JSONEvent extends WebEvent {
private static final long serialVersionUID = 6459849162427895987L;
private static final ILogger LOG = LoggerFactory.getLogger( JSONEvent.class );
private Map<String, ?> json;
/**
*
* @param servletContext
* @param request
* @throws ServletException
*/
@SuppressWarnings("unchecked")
JSONEvent( ServletContext servletContext, HttpServletRequest request ) throws ServletException {
super( servletContext, request, null );
JSONReader reader = new JSONReader();
String string = null;
try {
LOG.logDebug( "request character encoding: " + request.getCharacterEncoding() );
InputStreamReader isr = null;
if ( request.getCharacterEncoding() != null ) {
isr = new InputStreamReader( request.getInputStream(), request.getCharacterEncoding() );
} else {
// always use UTF-8 because XMLHttpRequest normally uses this encoding
isr = new InputStreamReader( request.getInputStream(), "UTF-8" );
}
string = FileUtils.readTextFile( isr ).toString();
} catch ( IOException e ) {
LOG.logError( e.getMessage(), e );
throw new ServletException( "can not parse json: " + json, e );
}
json = (Map<String, ?>) reader.read( string );
LOG.logDebug( "request parameter: " + json );
}
@SuppressWarnings("unchecked")
@Override
public Map getParameter() {
return json;
}
/**
*
* @param bean
*/
void setBean( String bean ) {
this.bean = bean;
}
@Override
public Object getAsBean()
throws Exception {
Class<?> clzz = Class.forName( bean );
Object bean = clzz.newInstance();
Method[] methods = clzz.getMethods();
for ( Method method : methods ) {
if ( method.getName().startsWith( "set" ) ) {
String var = method.getName().substring( 4, method.getName().length() );
var = method.getName().substring( 3, 4 ).toLowerCase() + var;
Object val = json.get( var );
Type type = method.getGenericParameterTypes()[0];
if ( val != null ) {
method.invoke( bean, ((Class<?>)type).cast( val ) );
}
}
}
return bean;
}
}
| lgpl-2.1 |
free-erp/invoicing | invoicing_client/src/org/free_erp/client/ui/forms/accounting/CReceivableSelectDialog.java | 5207 | /*
* Copyright 2013, TengJianfa , and other 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.free_erp.client.ui.forms.accounting;
import com.jdatabeans.beans.data.IDataRow;
import com.jdatabeans.beans.data.ObjectDataRow;
import com.jdatabeans.beans.data.table.ITableColumnModel;
import com.jdatabeans.beans.data.table.JDataTableColumn;
import org.free_erp.client.ui.main.Main;
import org.free_erp.service.constants.ServiceConstants;
import org.free_erp.service.entity.accounting.CustomerReceivableAccount;
import org.free_erp.service.entity.accounting.Receivable;
import org.free_erp.service.entity.base.Customer;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JLabel;
/**
*
* @author afa
*/
public class CReceivableSelectDialog extends CPayableSelectDialog
{
public CReceivableSelectDialog(Frame parent)
{
super(parent);
this.setTitle("Ñ¡ÔñÓ¦ÊÕ¿î");
}
@Override
protected void initDatas() {
List<Receivable> pos = service.findAllReceivable(Main.getMainFrame().getCompany());
Set<Customer> customers = new HashSet<Customer>();
List<IDataRow> detailDataRows = new ArrayList<IDataRow>();
for(Receivable po:pos)
{
Customer c = po.getCustomer();
if (po.getStatus() == ServiceConstants.UNFINISHED)
{
if (!customers.contains(c))
{
customers.add(c);
}
detailDataRows.add(ObjectDataRow.newDataRow(po, "id", null));
}
}
this.detailedTable.getDataSource().insertDataRows(detailDataRows);
List<IDataRow> dataRows = new ArrayList<IDataRow>();
for(Customer customer:customers)
{
CustomerReceivableAccount account = service.getCustomerReceivableAccount(customer);
if (account != null)
{
dataRows.add(ObjectDataRow.newDataRow(account, "id", null));
}
}
this.mainTable.getDataSource().insertDataRows(dataRows);
if (this.mainTable.getDataSource().getRowCount() > 0)
{
this.mainTable.setSelectedRow(0);
}
}
@Override
protected void initDetailedTableColumns() {
ITableColumnModel columnModel = detailedTable.getTableColumnModel();
JDataTableColumn column = new JDataTableColumn();
column.setHeaderText("Ñ¡Ôñ");
column.setColumnName("checked");
column.setWidth(50);
column.setValueType(Boolean.class);
column.setEditable(true);
//column.setAlignmentX(JLabel.LEFT);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("µ¥¾Ý±àºÅ");
column.setColumnName("formNo");
column.setWidth(120);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("µ¥¾ÝÈÕÆÚ");
column.setColumnName("formDate");
column.setWidth(80);
column.setValueType(Date.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("ÒµÎñÔ±");
column.setColumnName("employee.name");
column.setWidth(60);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("Ó¦ÊÕÈÕÆÚ");
column.setColumnName("receivableDate");
column.setWidth(80);
column.setValueType(Date.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("Ó¦ÊÕ½ð¶î");
column.setColumnName("receivableMoney");
column.setValueType(Currency.class);
column.setWidth(80);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("δ½á½ð¶î");
column.setColumnName("remainMoney");
column.setValueType(Currency.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("±¾´Î½áËã½ð¶î");
column.setColumnName("remainMoney");
column.setValueType(Currency.class);
columnModel.addColumn(column);
}
}
| lgpl-2.1 |
DBatOWL/jicofo-mirror | test/mock/xmpp/MockSetSimpleCapsOpSet.java | 2635 | package mock.xmpp;
import org.jitsi.protocol.xmpp.*;
import java.util.*;
/**
*
*/
public class MockSetSimpleCapsOpSet
extends MockCapsNode
implements OperationSetSimpleCaps
{
private long discoveryDelay = 0;
public MockSetSimpleCapsOpSet(String domain)
{
super(domain, new String[]{});
}
public void addDiscoveryDelay(long millis)
{
this.discoveryDelay = millis;
}
private MockCapsNode findFirstLevel(String name)
{
for (MockCapsNode node : childNodes)
{
if (node.getNodeName().equals(name))
{
return node;
}
}
return null;
}
@Override
public List<String> getItems(String nodeName)
{
ArrayList<String> result = new ArrayList<String>(childNodes.size());
MockCapsNode node;
if (nodeName.endsWith(getNodeName()))
{
node = this;
}
else
{
node = findFirstLevel(nodeName);
}
if (node != null)
{
for (MockCapsNode child : node.getChildNodes())
{
result.add(child.getNodeName());
}
}
return result;
}
@Override
public boolean hasFeatureSupport(String contactAddress, String[] features)
{
MockCapsNode node = findChild(contactAddress);
if (node == null)
{
return false;
}
String[] nodeFeatures = node.getFeatures();
for (String feature : features)
{
boolean found = false;
for (String toCheck : nodeFeatures)
{
if (toCheck.equals(feature))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
@Override
public List<String> getFeatures(String node)
{
if (discoveryDelay > 0)
{
try
{
Thread.sleep(discoveryDelay);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
MockCapsNode capsNode = findChild(node);
if (capsNode == null)
{
return null;
}
return Arrays.asList(capsNode.getFeatures());
}
//@Override
public boolean hasFeatureSupport(String node, String subnode,
String[] features)
{
return false;
}
}
| lgpl-2.1 |
agentlab/com.tilab.jade.chat | com.tilab.jade.chat.onto/src/chat/ontology/Joined.java | 428 | package chat.ontology;
import java.util.List;
import jade.content.Predicate;
import jade.core.AID;
/**
* Joined predicate used by chat ontology.
*
* @author Michele Izzo - Telecomitalia
*/
@SuppressWarnings("serial")
public class Joined implements Predicate {
private List<AID> _who;
public void setWho(List<AID> who) {
_who = who;
}
public List<AID> getWho() {
return _who;
}
}
| lgpl-2.1 |
phiresky/tuxguitar | TuxGuitar/src/org/herac/tuxguitar/app/view/util/TGBufferedPainterListenerLocked.java | 516 | package org.herac.tuxguitar.app.view.util;
import org.herac.tuxguitar.ui.event.UIPaintEvent;
import org.herac.tuxguitar.ui.event.UIPaintListener;
import org.herac.tuxguitar.util.TGContext;
public class TGBufferedPainterListenerLocked extends TGBufferedPainterLocked implements UIPaintListener {
public TGBufferedPainterListenerLocked(TGContext context, TGBufferedPainterHandle handle) {
super(context, handle);
}
public void onPaint(UIPaintEvent event) {
this.paintBufferLocked(event.getPainter());
}
}
| lgpl-2.1 |
zsoltii/dss | dss-document/src/main/java/eu/europa/esig/dss/validation/CertificateVerifier.java | 5754 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* 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 eu.europa.esig.dss.validation;
import eu.europa.esig.dss.client.http.DataLoader;
import eu.europa.esig.dss.x509.CertificatePool;
import eu.europa.esig.dss.x509.CertificateSource;
import eu.europa.esig.dss.x509.crl.CRLSource;
import eu.europa.esig.dss.x509.crl.ListCRLSource;
import eu.europa.esig.dss.x509.ocsp.ListOCSPSource;
import eu.europa.esig.dss.x509.ocsp.OCSPSource;
/**
* Provides information on the sources to be used in the validation process in
* the context of a signature.
*/
public interface CertificateVerifier {
/**
* Returns the OCSP source associated with this verifier.
*
* @return the used OCSP source for external access (web, filesystem,
* cached,...)
*/
OCSPSource getOcspSource();
/**
* Returns the CRL source associated with this verifier.
*
* @return the used CRL source for external access (web, filesystem, cached,...)
*/
CRLSource getCrlSource();
/**
* Defines the source of CRL used by this class
*
* @param crlSource
* the CRL source to set for external access (web, filesystem,
* cached,...)
*/
void setCrlSource(final CRLSource crlSource);
/**
* Defines the source of OCSP used by this class
*
* @param ocspSource
* the OCSP source to set for external access (web,
* filesystem, cached,...)
*/
void setOcspSource(final OCSPSource ocspSource);
/**
* Returns the trusted certificates source associated with this verifier. This
* source is used to identify the trusted anchors.
*
* @return the certificate source which contains trusted certificates
*/
CertificateSource getTrustedCertSource();
/**
* Sets the trusted certificates source.
*
* @param certSource
* The certificates source with known trusted certificates
*/
void setTrustedCertSource(final CertificateSource certSource);
/**
* Returns the adjunct certificates source associated with this verifier.
*
* @return the certificate source which contains additional certificate (missing
* CA,...)
*/
CertificateSource getAdjunctCertSource();
/**
* Associates an adjunct certificates source to this verifier.
*
* @param adjunctCertSource
* the certificate source with additional and missing
* certificates
*/
void setAdjunctCertSource(final CertificateSource adjunctCertSource);
/**
* The data loader used to access AIA certificate source.
*
* @return the used data loaded to load AIA resources and policy files
*/
DataLoader getDataLoader();
/**
* The data loader used to access AIA certificate source. If this property is
* not set the default {@code CommonsHttpDataLoader} is created.
*
* @param dataLoader
* the used data loaded to load AIA resources and policy files
*/
void setDataLoader(final DataLoader dataLoader);
/**
* This method returns the CRL source (information extracted from signatures).
*
* @return the CRL sources from the signature
*/
ListCRLSource getSignatureCRLSource();
/**
* This method allows to set the CRL source (information extracted from
* signatures).
*
* @param signatureCRLSource
* the CRL sources from the signature
*/
void setSignatureCRLSource(final ListCRLSource signatureCRLSource);
/**
* This method returns the OCSP source (information extracted from signatures).
*
* @return the OCSP sources from the signature
*/
ListOCSPSource getSignatureOCSPSource();
/**
* This method allows to set the OCSP source (information extracted from
* signatures).
*
* @param signatureOCSPSource
* the OCSP sources from the signature
*/
void setSignatureOCSPSource(final ListOCSPSource signatureOCSPSource);
/**
* This method allows to change the behavior on missing revocation data (LT/LTA
* augmentation). (default : true)
*
* @param throwExceptionOnMissingRevocationData
* true if an exception is raised
* on missing revocation data,
* false will only display a
* warning message
*/
void setExceptionOnMissingRevocationData(boolean throwExceptionOnMissingRevocationData);
/**
* This method returns true if an exception needs to be thrown on missing
* revocation data.
*
* @return true if an exception is thrown, false if a warning message is added
*/
boolean isExceptionOnMissingRevocationData();
/**
* This method creates the validation pool of certificates which is used
* during the validation process.
*/
CertificatePool createValidationPool();
} | lgpl-2.1 |
geotools/geotools | modules/library/main/src/main/java/org/geotools/data/ows/AbstractGetCapabilitiesRequest.java | 1734 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-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.data.ows;
import java.net.URL;
/**
* Each Open Web Service typically defines an operation that describes what operations it supports
* and what data it holds. The document describing this information is usually called the
* Capabilities document, and is usually accessed using the GetCapabilities operation.
*
* <p>This class provides a basic building block for clients to implement their
* GetCapabilitiesRequest. It automatically sets the REQUEST parameter to "GetCapabilities".
*
* @author rgould
*/
public abstract class AbstractGetCapabilitiesRequest extends AbstractRequest
implements GetCapabilitiesRequest {
/** Represents the SERVICE parameter */
public static final String SERVICE = "SERVICE"; // $NON-NLS-1$
public AbstractGetCapabilitiesRequest(URL serverURL) {
super(serverURL, null);
}
/**
* Sets the REQUEST parameter
*
* <p>Subclass can override if needed.
*/
@Override
protected void initRequest() {
setProperty(REQUEST, "GetCapabilities"); // $NON-NLS-1$
}
}
| lgpl-2.1 |
free-erp/invoicing | invoicing_client/src/org/free_erp/client/ui/forms/system/CEmpDegreeListDialog.java | 5030 | /*
* Copyright 2013, TengJianfa , and other 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.free_erp.client.ui.forms.system;
import com.jdatabeans.beans.data.IDataRow;
import com.jdatabeans.beans.data.IDbSupport;
import com.jdatabeans.beans.data.ObjectDataRow;
import com.jdatabeans.beans.data.table.ITableColumnModel;
import com.jdatabeans.beans.data.table.ITableModel;
import com.jdatabeans.beans.data.table.JDataTableColumn;
import com.jdatabeans.util.MessageBox;
import org.free_erp.client.ui.core.ObjectsPool;
import org.free_erp.client.ui.forms.CBaseListManageDialog;
import org.free_erp.client.ui.main.Main;
import org.free_erp.service.entity.system.EmployeeDegree;
import org.free_erp.service.logic.IOptionSetService;
import java.awt.Frame;
import java.util.Collection;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author TengJianfa mobile:086-13003311398 qq:575633370 www.free-erp.com
*/
public class CEmpDegreeListDialog extends CBaseListManageDialog
{
protected CEmpDegreeAddDialog dialog;
public CEmpDegreeListDialog(Frame parent)
{
super(parent);
this.createDbSupport();
this.initCs();
this.initDatas();
}
private void initCs()
{
this.setTitle("Ô±¹¤Ö°³ÆÏÂÀ¿òÉèÖÃ");
}
@Override
protected void initColumns()
{
ITableColumnModel columnModel = dataTable.getTableColumnModel();
JDataTableColumn column = new JDataTableColumn();
column.setHeaderText("Ô±¹¤Ö°³ÆÃû³Æ");
column.setColumnName("empDegree");
column.setWidth(165);
columnModel.addColumn(column);
}
@Override
public void initDatas()
{
ITableModel model = this.dataTable.getTableModel();
List<EmployeeDegree> employeeDegrees = service.getListEmployeeDegrees(Main.getMainFrame().getCompany());
for(EmployeeDegree po:employeeDegrees)
{
IDataRow dataRow = new ObjectDataRow(po, "id",dbSupport);
model.insertDataRow(dataRow);
}
}
@Override
public void doAdd()
{
if (this.dialog == null)
{
this.dialog = new CEmpDegreeAddDialog(this, this.dataSource);
}
dialog.newDataRow();
dialog.setTitle("Ìí¼ÓÔ±¹¤Ö°³Æ");
dialog.setVisible(true);
this.dataSource.clearTempDataRows();
}
@Override
public void doEdit()
{
if (this.dialog == null)
{
this.dialog = new CEmpDegreeAddDialog(this, this.dataSource);
}
if (this.dataTable.getSelectedRow() < 0)
{
MessageBox.showErrorDialog(Main.getMainFrame(), "ûÓÐÈκÎÊý¾ÝÐб»Ñ¡ÖÐ!");
return;
}
this.dataSource.setCurrentDataRow(this.dataTable.getSelectedDataRow());
dialog.setTitle("ÐÞ¸ÄÔ±¹¤Ö°³Æ");
dialog.setVisible(true);
}
public void createDbSupport()
{
dbSupport = new IDbSupport()
{
ObjectsPool pool = Main.getMainFrame().getObjectsPool();
IOptionSetService optionSetService = Main.getServiceManager().getOptionSetService();
public void delete(Object obj)
{
if (obj instanceof EmployeeDegree)
{
EmployeeDegree po = (EmployeeDegree) obj;
optionSetService.deleteEmployeeDegree(po);
pool.refreshEmployeeDegrees();
}
else
{
throw new IllegalArgumentException("²ÎÊýÀàÐͲ»·ûºÏ!´«ÈëµÄÀàÐÍΪ" + obj.getClass().getName());
}
}
public void save(Object obj)
{
if (obj instanceof EmployeeDegree)
{
EmployeeDegree po = (EmployeeDegree) obj;
optionSetService.saveEmployeeDegree(po);
pool.refreshEmployeeDegrees();
}
else
{
throw new IllegalArgumentException("²ÎÊýÀàÐͲ»·ûºÏ!´«ÈëµÄÀàÐÍΪ" + obj.getClass().getName());
}
}
public void deleteAll(Collection<Object> objs)
{
JOptionPane.showMessageDialog(null, "ÔÝδʵÏÖ!");
}
public void saveAll(Collection<Object> objs)
{
JOptionPane.showMessageDialog(null, "ÔÝδʵÏÖ!");
}
};
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/lob/LongByteArrayTest.java | 3680 | /*
* 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.lob;
import java.util.Arrays;
import org.hibernate.Session;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Assert;
import org.junit.Test;
import junit.framework.AssertionFailedError;
import static org.junit.Assert.assertNull;
/**
* Tests eager materialization and mutation of long byte arrays.
*
* @author Steve Ebersole
*/
public abstract class LongByteArrayTest extends BaseCoreFunctionalTestCase {
private static final int ARRAY_SIZE = 10000;
@Test
public void testBoundedLongByteArrayAccess() {
byte[] original = buildRecursively( ARRAY_SIZE, true );
byte[] changed = buildRecursively( ARRAY_SIZE, false );
byte[] empty = new byte[] {};
Session s = openSession();
s.beginTransaction();
LongByteArrayHolder entity = new LongByteArrayHolder();
s.save( entity );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = s.get( LongByteArrayHolder.class, entity.getId() );
assertNull( entity.getLongByteArray() );
entity.setLongByteArray( original );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = s.get( LongByteArrayHolder.class, entity.getId() );
Assert.assertEquals( ARRAY_SIZE, entity.getLongByteArray().length );
assertEquals( original, entity.getLongByteArray() );
entity.setLongByteArray( changed );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = s.get( LongByteArrayHolder.class, entity.getId() );
Assert.assertEquals( ARRAY_SIZE, entity.getLongByteArray().length );
assertEquals( changed, entity.getLongByteArray() );
entity.setLongByteArray( null );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = s.get( LongByteArrayHolder.class, entity.getId() );
assertNull( entity.getLongByteArray() );
entity.setLongByteArray( empty );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = s.get( LongByteArrayHolder.class, entity.getId() );
if ( entity.getLongByteArray() != null ) {
Assert.assertEquals( empty.length, entity.getLongByteArray().length );
assertEquals( empty, entity.getLongByteArray() );
}
s.delete( entity );
s.getTransaction().commit();
s.close();
}
@Test
public void testSaving() {
byte[] value = buildRecursively( ARRAY_SIZE, true );
Session s = openSession();
s.beginTransaction();
LongByteArrayHolder entity = new LongByteArrayHolder();
entity.setLongByteArray( value );
s.persist( entity );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
entity = ( LongByteArrayHolder ) s.get( LongByteArrayHolder.class, entity.getId() );
Assert.assertEquals( ARRAY_SIZE, entity.getLongByteArray().length );
assertEquals( value, entity.getLongByteArray() );
s.delete( entity );
s.getTransaction().commit();
s.close();
}
private byte[] buildRecursively(int size, boolean on) {
byte[] data = new byte[size];
data[0] = mask( on );
for ( int i = 0; i < size; i++ ) {
data[i] = mask( on );
on = !on;
}
return data;
}
private byte mask(boolean on) {
return on ? ( byte ) 1 : ( byte ) 0;
}
public static void assertEquals(byte[] val1, byte[] val2) {
if ( !Arrays.equals( val1, val2 ) ) {
throw new AssertionFailedError( "byte arrays did not match" );
}
}
}
| lgpl-2.1 |
xwiki/xwiki-platform | xwiki-platform-core/xwiki-platform-messagestream/xwiki-platform-messagestream-api/src/test/java/org/xwiki/messagestream/MessageStreamTest.java | 14751 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.messagestream;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.eventstream.Event;
import org.xwiki.eventstream.Event.Importance;
import org.xwiki.eventstream.EventFactory;
import org.xwiki.eventstream.EventStore;
import org.xwiki.eventstream.EventStream;
import org.xwiki.eventstream.EventStreamException;
import org.xwiki.eventstream.internal.DefaultEvent;
import org.xwiki.messagestream.internal.DefaultMessageStream;
import org.xwiki.model.ModelContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.ObjectReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.test.junit5.mockito.MockComponent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for the {@link org.xwiki.userstatus.internal.DefaultEvent default event} and
* {@link org.xwiki.messagestream.internal.DefaultMessageStream default event factory}.
*
* @version $Id$
*/
@ComponentTest
class MessageStreamTest
{
private static final DocumentReference CURRENT_USER = new DocumentReference("wiki", "XWiki", "JohnDoe");
private static final DocumentReference TARGET_USER = new DocumentReference("wiki", "XWiki", "JaneBuck");
private static final DocumentReference TARGET_GROUP = new DocumentReference("wiki", "XWiki", "MyFriends");
@MockComponent
private DocumentAccessBridge mockBridge;
@MockComponent
private QueryManager mockQueryManager;
@MockComponent
private EventStream mockEventStream;
@MockComponent
private EntityReferenceSerializer<String> mockSerializer;
@MockComponent
private EventFactory mockEventFactory;
@MockComponent
private ModelContext mockContext;
@MockComponent
private EventStore mockEventStore;
@InjectMockComponents
private DefaultMessageStream stream;
private Query mockQuery = mock(Query.class);
@BeforeEach
void beforeEach()
{
when(this.mockSerializer.serialize(CURRENT_USER)).thenReturn("wiki:XWiki.JohnDoe");
when(this.mockSerializer.serialize(TARGET_USER)).thenReturn("wiki:XWiki.JaneBuck");
when(this.mockSerializer.serialize(TARGET_GROUP)).thenReturn("wiki:XWiki.MyFriends");
}
private Event setupForNewMessage() throws ComponentLookupException, Exception
{
Event event = new DefaultEvent();
event.setId(UUID.randomUUID().toString());
when(this.mockEventFactory.createEvent()).thenReturn(event);
when(this.mockContext.getCurrentEntityReference()).thenReturn(new DocumentReference("wiki", "Space", "Page"));
return event;
}
private void verifyForNewMessage(Event event) throws EventStreamException
{
verify(this.mockEventFactory).createEvent();
verify(this.mockEventStore).saveEvent(event);
}
private Event setupForPublicMessage() throws Exception
{
Event e = setupForNewMessage();
when(this.mockBridge.getCurrentUserReference()).thenReturn(CURRENT_USER);
return e;
}
private Event setupForPersonalMessage() throws Exception
{
Event e = setupForNewMessage();
when(this.mockBridge.getCurrentUserReference()).thenReturn(CURRENT_USER);
return e;
}
private Event setupForDirectMessage() throws ComponentLookupException, Exception
{
Event e = setupForNewMessage();
when(this.mockBridge.exists(TARGET_USER)).thenReturn(true);
return e;
}
private Event setupForGroupMessage() throws ComponentLookupException, Exception
{
Event e = setupForNewMessage();
when(this.mockBridge.exists(TARGET_GROUP)).thenReturn(true);
return e;
}
private void setupForLimitQueries(int expectedLimit, int expectedOffset) throws ComponentLookupException, Exception
{
when(this.mockQuery.setLimit(expectedLimit)).thenReturn(mockQuery);
when(this.mockQuery.setOffset(expectedOffset)).thenReturn(mockQuery);
when(this.mockQueryManager.createQuery(anyString(), anyString())).thenReturn(mockQuery);
when(this.mockBridge.getCurrentUserReference()).thenReturn(CURRENT_USER);
when(this.mockEventStream.searchEvents(mockQuery)).thenReturn(null);
}
private void verifyLimitQueries(int expectedLimit, int expectedOffset) throws QueryException
{
verify(this.mockQuery).setLimit(expectedLimit);
verify(this.mockQuery).setOffset(expectedOffset);
verify(this.mockEventStream).searchEvents(this.mockQuery);
}
// Tests
@Test
void postPublicMessage() throws Exception
{
Event postedMessage = setupForPublicMessage();
this.stream.postPublicMessage("Hello World!");
assertEquals("Hello World!", postedMessage.getBody());
assertEquals(Importance.MINOR, postedMessage.getImportance());
assertEquals("publicMessage", postedMessage.getType());
assertEquals(CURRENT_USER, postedMessage.getRelatedEntity());
}
@Test
void postPublicMessageWithNullMessage() throws Exception
{
Event postedMessage = setupForPublicMessage();
this.stream.postPublicMessage(null);
assertEquals(null, postedMessage.getBody());
}
@Test
void postPublicMessageWithEmptyMessage() throws Exception
{
Event postedMessage = setupForPublicMessage();
this.stream.postPublicMessage("");
assertEquals("", postedMessage.getBody());
}
@Test
void postPublicMessageWithLongMessage() throws Exception
{
Event postedMessage = setupForPublicMessage();
this.stream.postPublicMessage(StringUtils.repeat('a', 10000));
assertEquals(StringUtils.repeat('a', 2000), postedMessage.getBody());
}
@Test
void postPersonalMessage() throws Exception
{
Event postedMessage = setupForPersonalMessage();
this.stream.postPersonalMessage("Hello World!");
assertEquals("Hello World!", postedMessage.getBody());
assertEquals(Importance.MEDIUM, postedMessage.getImportance());
assertEquals("personalMessage", postedMessage.getType());
assertEquals(CURRENT_USER, postedMessage.getRelatedEntity());
}
@Test
void postPersonalMessageWithNullMessage() throws Exception
{
Event postedMessage = setupForPersonalMessage();
this.stream.postPersonalMessage(null);
assertEquals(null, postedMessage.getBody());
}
@Test
void postPersonalMessageWithEmptyMessage() throws Exception
{
Event postedMessage = setupForPersonalMessage();
this.stream.postPersonalMessage("");
assertEquals("", postedMessage.getBody());
}
@Test
void postPersonalMessageWithLongMessage() throws Exception
{
Event postedMessage = setupForPersonalMessage();
this.stream.postPersonalMessage(StringUtils.repeat('a', 10000));
assertEquals(StringUtils.repeat('a', 2000), postedMessage.getBody());
}
@Test
void postDirectMessage() throws Exception
{
Event postedMessage = setupForDirectMessage();
this.stream.postDirectMessageToUser("Hello World!", TARGET_USER);
verifyForNewMessage(postedMessage);
assertEquals("Hello World!", postedMessage.getBody());
assertEquals(Importance.CRITICAL, postedMessage.getImportance());
assertEquals("directMessage", postedMessage.getType());
assertEquals("wiki:XWiki.JaneBuck", postedMessage.getStream());
assertEquals(new ObjectReference("XWiki.XWikiUsers", TARGET_USER), postedMessage.getRelatedEntity());
}
@Test
void postDirectMessageWithNullMessage() throws Exception
{
Event postedMessage = setupForDirectMessage();
this.stream.postDirectMessageToUser(null, TARGET_USER);
verifyForNewMessage(postedMessage);
assertEquals(null, postedMessage.getBody());
}
@Test
void postDirectMessageWithEmptyMessage() throws Exception
{
Event postedMessage = setupForDirectMessage();
this.stream.postDirectMessageToUser("", TARGET_USER);
verifyForNewMessage(postedMessage);
assertEquals("", postedMessage.getBody());
}
@Test
void postDirectMessageWithLongMessage() throws Exception
{
Event postedMessage = setupForDirectMessage();
this.stream.postDirectMessageToUser(StringUtils.repeat('a', 10000), TARGET_USER);
verifyForNewMessage(postedMessage);
assertEquals(StringUtils.repeat('a', 2000), postedMessage.getBody());
}
@Test
void postDirectMessageWithNonExistingTarget() throws Exception
{
DocumentReference targetUser = new DocumentReference("xwiki", "XWiki", "Nobody");
when(this.mockBridge.exists(targetUser)).thenReturn(false);
assertThrows(IllegalArgumentException.class,
() -> this.stream.postDirectMessageToUser("Hello Nobody!", targetUser));
}
@Test
void postGroupMessage() throws Exception
{
Event postedMessage = setupForGroupMessage();
this.stream.postMessageToGroup("Hello Friends!", TARGET_GROUP);
assertEquals("Hello Friends!", postedMessage.getBody());
assertEquals(Importance.MAJOR, postedMessage.getImportance());
assertEquals("groupMessage", postedMessage.getType());
assertEquals("wiki:XWiki.MyFriends", postedMessage.getStream());
assertEquals(new ObjectReference("XWiki.XWikiGroups", TARGET_GROUP), postedMessage.getRelatedEntity());
}
@Test
void postGroupMessageWithNonExistingTarget() throws Exception
{
DocumentReference targetGroup = new DocumentReference("xwiki", "XWiki", "Nobodies");
when(this.mockBridge.exists(targetGroup)).thenReturn(false);
assertThrows(IllegalArgumentException.class,
() -> this.stream.postMessageToGroup("Hello Nobodies!", targetGroup));
}
@Test
void getRecentPersonalMessages() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages();
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesForAuthor() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(CURRENT_USER);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithNegativeLimit() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(-4, 0);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithZeroLimit() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(0, 0);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithLimit1() throws Exception
{
setupForLimitQueries(1, 0);
this.stream.getRecentPersonalMessages(1, 0);
verifyLimitQueries(1, 0);
}
@Test
void getRecentPersonalMessagesWithLimit30() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(30, 0);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithLimit100() throws Exception
{
setupForLimitQueries(100, 0);
this.stream.getRecentPersonalMessages(100, 0);
verifyLimitQueries(100, 0);
}
@Test
void getRecentPersonalMessagesWithNegativeOffset() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(30, -4);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithNegativeLimitAndOffset() throws Exception
{
setupForLimitQueries(30, 0);
this.stream.getRecentPersonalMessages(-1, -1);
verifyLimitQueries(30, 0);
}
@Test
void getRecentPersonalMessagesWithZeroOffset() throws Exception
{
setupForLimitQueries(100, 0);
this.stream.getRecentPersonalMessages(100, 0);
verifyLimitQueries(100, 0);
}
@Test
void getRecentPersonalMessagesWithOffset1() throws Exception
{
setupForLimitQueries(20, 1);
this.stream.getRecentPersonalMessages(20, 1);
verifyLimitQueries(20, 1);
}
@Test
void getRecentPersonalMessagesWithOffset100() throws Exception
{
setupForLimitQueries(50, 100);
this.stream.getRecentPersonalMessages(50, 100);
verifyLimitQueries(50, 100);
}
@Test
void getRecentPersonalMessagesWhenQueryFails() throws Exception
{
setupForLimitQueries(30, 0);
doThrow(new QueryException("", null, null)).when(this.mockEventStream).searchEvents(this.mockQuery);
List<Event> result = this.stream.getRecentPersonalMessages();
assertNotNull(result);
assertTrue(result.isEmpty());
verifyLimitQueries(30, 0);
}
}
| lgpl-2.1 |
deegree/deegree3 | deegree-core/deegree-core-tile/src/test/java/org/deegree/tile/TileMatrixSetTest.java | 3864 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 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/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
http://www.occamlabs.de/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.tile;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Iterator;
import junit.framework.TestCase;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.GeometryFactory;
import org.deegree.geometry.metadata.SpatialMetadata;
import org.junit.Before;
import org.junit.Test;
/**
* <code>TileMatrixSetTest</code>
*
* @author <a href="mailto:schmitz@occamlabs.de">Andreas Schmitz</a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $
*/
public class TileMatrixSetTest extends TestCase {
private TileDataSet tms;
private Envelope env;
@Override
@Before
public void setUp() {
GeometryFactory fac = new GeometryFactory();
ICRS crs;
try {
crs = CRSManager.lookup( "EPSG:4326" );
env = fac.createEnvelope( -10, -10, 10, 10, crs );
SpatialMetadata smd = new SpatialMetadata( env, Collections.singletonList( crs ) );
TileMatrix md = new TileMatrix( "someid", smd, 256, 256, 1, 1, 1 );
TileDataLevel tm = mock( TileDataLevel.class );
Tile t = mock( Tile.class );
tm.getMetadata();
tm.getTile( 0, 0 );
when( tm.getMetadata() ).thenReturn( md );
when( tm.getTile( 0, 0 ) ).thenReturn( t );
TileMatrixSet metadata = new TileMatrixSet( "default", null, Collections.singletonList( md ), smd, null );
tms = new DefaultTileDataSet( Collections.singletonList( tm ), metadata, "image/png" );
} catch ( UnknownCRSException e ) {
throw new RuntimeException( e );
}
}
/**
* Test method for {@link org.deegree.tile.TileDataSet#getTiles(org.deegree.geometry.Envelope, double)}.
*/
@Test
public void testGetTiles() {
Iterator<Tile> iter = tms.getTiles( env, 1 );
assertNotNull( iter.next() );
}
/**
* Test method for {@link org.deegree.tile.TileDataSet#getTileDataLevels()}.
*/
@Test
public void testGetTileMatrices() {
assertNotNull( tms.getTileDataLevels() );
assertEquals( tms.getTileDataLevels().size(), 1 );
}
}
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-arcsde/src/main/java/org/deegree/io/sdeapi/SpatialQuery.java | 26858 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 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.io.sdeapi;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Vector;
import org.deegree.datatypes.Types;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
import org.deegree.framework.util.StringTools;
import org.deegree.model.spatialschema.Curve;
import org.deegree.model.spatialschema.Envelope;
import org.deegree.model.spatialschema.Geometry;
import org.deegree.model.spatialschema.GeometryFactory;
import org.deegree.model.spatialschema.MultiCurve;
import org.deegree.model.spatialschema.MultiPoint;
import org.deegree.model.spatialschema.MultiSurface;
import org.deegree.model.spatialschema.Point;
import org.deegree.model.spatialschema.Position;
import org.deegree.model.spatialschema.Surface;
import org.deegree.model.spatialschema.SurfaceInterpolation;
import org.deegree.model.spatialschema.SurfaceInterpolationImpl;
import org.deegree.model.table.DefaultTable;
import org.deegree.model.table.Table;
import org.deegree.model.table.TableException;
import com.esri.sde.sdk.client.SDEPoint;
import com.esri.sde.sdk.client.SeColumnDefinition;
import com.esri.sde.sdk.client.SeConnection;
import com.esri.sde.sdk.client.SeException;
import com.esri.sde.sdk.client.SeExtent;
import com.esri.sde.sdk.client.SeFilter;
import com.esri.sde.sdk.client.SeLayer;
import com.esri.sde.sdk.client.SeQuery;
import com.esri.sde.sdk.client.SeRow;
import com.esri.sde.sdk.client.SeShape;
import com.esri.sde.sdk.client.SeShapeFilter;
import com.esri.sde.sdk.client.SeSqlConstruct;
import com.esri.sde.sdk.client.SeTable;
/**
* This class handles a complete ArcSDE request: If instanciated, the class can open a
* connection/instance of the specified ArcSDE server, set a bounding box as a spatial filter to
* query the defined layer. The resultset of the query contains the geometries as well as the
* tabular data associated with them. The table is stored as a deegree Table object whereas the
* geometries are stored as an array of deegree GM_Objects. Depending on the datatype of the
* geometries, the array of GM_Objects might be GM_Point, GM_Curve etc.
* <p>
* Some bits of sample code to create a query:
* <p>
* <code>
* SpatialQuery sq = new SpatialQuery();<br>
* try {<br>
* sq.openConnection(server, instance, database, user, password);<br>
* sq.setLayer(layer);<br>
* sq.setSpatialFilter(minX, minY, maxX, maxY);<br>
* sp.runSpatialQuery();<br>
* GM_Object[] deegree_gm_obj = sq.getGeometries();<br>
* Table deegree_table = sq.getTable();<br>
* sq.closeConnection();<br>
* } catch ( SeException sexp ) {<br>
* }<br>
* </code>
*
* @author <a href="mailto:bedel@giub.uni-bonn.de">Markus Bedel</a>
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
* @version $Revision$ $Date$
*/
public class SpatialQuery {
private static final ILogger LOG = LoggerFactory.getLogger( SpatialQuery.class );
// Connection to SDE
private SeConnection conn = null;
// Currently opened Layer and associated Table
private SeLayer layer = null;
// Current Spatial Filter - a BoundingBox
private SeShape spatialFilter = null;
private SeTable table = null;
// The Query ResultObjects
private Geometry[] deegreeGeom = null;
/**
* Creates a new SpatialQuery object.
*
* @param server
* @param port
* @param database
* @param user
* @param password
*
* @throws SeException
*/
public SpatialQuery( String server, int port, String database, String user, String password ) throws SeException {
openConnection( server, port, database, user, password );
}
/**
* Connect to the ArcSDE server <br>
* throws SeException
*
* @param server
* @param port
* @param database
* @param user
* @param password
* @throws SeException
*/
public void openConnection( String server, int port, String database, String user, String password )
throws SeException {
conn = new SeConnection( server, port, database, user, password );
}
/**
* Close the current connection to the ArcSDE server <br>
* throws SeException
*
* @throws SeException
*/
public void closeConnection()
throws SeException {
conn.close();
}
/**
* Set a SDE layer to work on and appropriate table <br>
* throws SeException
*
* @param layername
* @throws SeException
*/
public void setLayer( String layername )
throws SeException {
Vector<?> layerList = conn.getLayers();
String spatialCol = null;
for ( int i = 0; i < layerList.size(); i++ ) {
SeLayer layer = (SeLayer) layerList.elementAt( i );
if ( layer.getQualifiedName().trim().equalsIgnoreCase( layername ) ) {
spatialCol = layer.getSpatialColumn();
break;
}
}
layer = new SeLayer( conn, layername, spatialCol );
table = new SeTable( conn, layer.getQualifiedName() );
}
/**
* Get the current SDE layer <br>
* returns null if it not yet set.
*
* @return null if it not yet set.
*/
public SeLayer getLayer() {
return layer;
}
/**
* Set a SpatialFilter to Query (BoundingBox) <br>
* throws SeException
*
* @param minx
* @param miny
* @param maxx
* @param maxy
* @throws SeException
*/
public void setSpatialFilter( double minx, double miny, double maxx, double maxy )
throws SeException {
Envelope layerBBox = GeometryFactory.createEnvelope( layer.getExtent().getMinX(), layer.getExtent().getMinY(),
layer.getExtent().getMaxX(), layer.getExtent().getMaxY(),
null );
Envelope query = GeometryFactory.createEnvelope( minx, miny, maxx, maxy, null );
query = query.createIntersection( layerBBox );
if ( query != null ) {
spatialFilter = new SeShape( layer.getCoordRef() );
SeExtent extent = new SeExtent( query.getMin().getX(), query.getMin().getY(), query.getMax().getX(),
query.getMax().getY() );
spatialFilter.generateRectangle( extent );
} else {
spatialFilter = null;
}
}
/**
* Get the current Spatial Filter <br>
* returns null if it not yet set.
*
* @return null if it not yet set.
*/
public SeShape getSpatialFilter() {
return spatialFilter;
}
/**
* Get GM_Object[] containing the queried Geometries <br>
* returns null if no query has been done yet.
*
* @return null if no query has been done yet.
*/
public Geometry[] getGeometries() {
return deegreeGeom;
}
/**
* Runs a spatial query against the opened layer using the specified spatial filter. <br>
* throws SeException
*
* @param cols
* @return the resulting table
* @throws SeException
* @throws DeegreeSeException
*/
public Table runSpatialQuery( String[] cols )
throws SeException, DeegreeSeException {
Table deegreeTable = null;
if ( spatialFilter != null ) {
SeShapeFilter[] filters = new SeShapeFilter[1];
filters[0] = new SeShapeFilter( layer.getQualifiedName(), layer.getSpatialColumn(), spatialFilter,
SeFilter.METHOD_ENVP );
SeColumnDefinition[] tableDef = table.describe();
if ( cols == null || cols.length == 0 ) {
cols = new String[tableDef.length];
for ( int i = 0; i < tableDef.length; i++ ) {
cols[i] = tableDef[i].getName();
}
}
SeSqlConstruct sqlCons = new SeSqlConstruct( layer.getQualifiedName() );
SeQuery spatialQuery = new SeQuery( conn, cols, sqlCons );
spatialQuery.prepareQuery();
spatialQuery.setSpatialConstraints( SeQuery.SE_OPTIMIZE, false, filters );
spatialQuery.execute();
SeRow row = spatialQuery.fetch();
int numRows = 0;
if ( row != null ) {
int numCols = row.getNumColumns();
// Fetch all the features that satisfied the query
deegreeTable = initTable( row );
ArrayList<Geometry> list = new ArrayList<Geometry>( 20000 );
Object[] tableObj = null;
while ( row != null ) {
int colNum = 0;
tableObj = new Object[deegreeTable.getColumnCount()];
for ( int i = 0; i < numCols; i++ ) {
SeColumnDefinition colDef = row.getColumnDef( i );
if ( row.getIndicator( (short) i ) != SeRow.SE_IS_NULL_VALUE ) {
switch ( colDef.getType() ) {
case SeColumnDefinition.TYPE_INT16:
tableObj[colNum++] = row.getShort( i );
break;
case SeColumnDefinition.TYPE_INT32:
tableObj[colNum++] = row.getInteger( i );
break;
case SeColumnDefinition.TYPE_FLOAT32:
tableObj[colNum++] = row.getFloat( i );
break;
case SeColumnDefinition.TYPE_FLOAT64:
tableObj[colNum++] = row.getDouble( i );
break;
case SeColumnDefinition.TYPE_STRING:
tableObj[colNum++] = row.getString( i );
break;
case SeColumnDefinition.TYPE_BLOB:
ByteArrayInputStream bis = (ByteArrayInputStream) row.getObject( i );
tableObj[colNum++] = bis;
break;
case SeColumnDefinition.TYPE_DATE:
tableObj[colNum++] = row.getTime( i ).getTime();
break;
case SeColumnDefinition.TYPE_RASTER:
LOG.logInfo( colDef.getName() + " : Cant handle this" );
break;
case SeColumnDefinition.TYPE_SHAPE:
SeShape spVal = row.getShape( i );
createGeometry( spVal, list );
break;
default:
LOG.logInfo( "Unknown Table DataType" );
break;
} // End switch(type)
} // End if
} // End for
numRows++;
try {
deegreeTable.appendRow( tableObj );
} catch ( TableException tex ) {
throw new DeegreeSeException( tex.toString() );
}
row = spatialQuery.fetch();
} // End while
spatialQuery.close();
deegreeGeom = list.toArray( new Geometry[list.size()] );
} else {
try {
deegreeTable = new DefaultTable( layer.getQualifiedName(), new String[] { "NONE" },
new int[] { Types.VARCHAR }, 2 );
} catch ( Exception e ) {
e.printStackTrace();
}
deegreeGeom = new Geometry[0];
}
} else {
try {
deegreeTable = new DefaultTable( layer.getQualifiedName(), new String[] { "NONE" },
new int[] { Types.VARCHAR }, 2 );
} catch ( Exception e ) {
e.printStackTrace();
}
deegreeGeom = new Geometry[0];
}
return deegreeTable;
} // End method runSpatialQuery
/**
* Initialize Table object - used with first row of the SpatialQuery This method sets the
* TableName, TableColumnNames and their DataTypes <br>
* throws SeException
*/
private Table initTable( SeRow row )
throws SeException, DeegreeSeException {
ArrayList<String> colNames = new ArrayList<String>( 50 );
ArrayList<Integer> colTypes = new ArrayList<Integer>( 50 );
Table deegreeTable = null;
SeColumnDefinition colDef = null;
for ( int i = 0; i < row.getNumColumns(); i++ ) {
try {
colDef = row.getColumnDef( i );
} catch ( SeException sexp ) {
sexp.printStackTrace();
throw new DeegreeSeException( sexp.toString() );
}
switch ( colDef.getType() ) {
case SeColumnDefinition.TYPE_INT16:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.SMALLINT ) );
break;
case SeColumnDefinition.TYPE_INT32:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.INTEGER ) );
break;
case SeColumnDefinition.TYPE_FLOAT32:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.FLOAT ) );
break;
case SeColumnDefinition.TYPE_FLOAT64:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.DOUBLE ) );
break;
case SeColumnDefinition.TYPE_STRING:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.VARCHAR ) );
break;
case SeColumnDefinition.TYPE_BLOB:
// there is an open issue with fetching blobs,
// look at this document:
// "ArcSDE 8.1 Java API - BLOB columns"
// http://support.esri.com/Search/KbDocument.asp?dbid=17068
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.ARRAY ) );
break;
case SeColumnDefinition.TYPE_DATE:
colNames.add( colDef.getName().toUpperCase() );
colTypes.add( new Integer( Types.DATE ) );
break;
default:
break;
}
}
String[] colN = new String[colNames.size()];
colN = colNames.toArray( colN );
int[] colT = new int[colTypes.size()];
for ( int i = 0; i < colT.length; i++ ) {
colT[i] = colTypes.get( i ).intValue();
}
try {
deegreeTable = new DefaultTable( layer.getQualifiedName(), colN, colT, 20000 );
} catch ( TableException tex ) {
tex.printStackTrace();
throw new DeegreeSeException( tex.toString() );
}
return deegreeTable;
} // End Method initTable
/**
* CreateGeometry - used with every row of the SpatialQuery Depending on the layers' geometries
* datatype different operations are made to create the appropriate object. <br>
* Available ArcSDE ShapeTypes: <br>
* TYPE_POINT (impl) <br>
* TYPE_MULTI_POINT (impl) <br>
* TYPE_SIMPLE_LINE (impl) <br>
* TYPE_MULTI_SIMPLE_LINE (impl) <br>
* TYPE_LINE (impl) <br>
* TYPE_MULTI_LINE (impl) <br>
* TYPE_POLYGON (impl) <br>
* TYPE_MULTI_POLYGON (impl) <br>
* TYPE_NIL (impl)
*
* <br>
* throws SeException
*/
private void createGeometry( SeShape shape, ArrayList<Geometry> list )
throws SeException, DeegreeSeException {
int shptype = shape.getType();
ArrayList<?> al = shape.getAllPoints( SeShape.TURN_DEFAULT, true );
// Retrieve the array of SDEPoints
SDEPoint[] points = (SDEPoint[]) al.get( 0 );
// Retrieve the part offsets array.
int[] partOffset = (int[]) al.get( 1 );
// Retrieve the sub-part offsets array.
int[] subPartOffset = (int[]) al.get( 2 );
int numPoints = shape.getNumOfPoints();
int numParts = shape.getNumParts();
switch ( shptype ) {
// a single point
case SeShape.TYPE_NIL:
Point gmPoint = GeometryFactory.createPoint( -9E9, -9E9, null );
list.add( gmPoint );
LOG.logInfo( "Found SeShape.TYPE_NIL." );
LOG.logInfo( "The queried layer does not have valid geometries" );
break;
// a single point
case SeShape.TYPE_POINT:
gmPoint = GeometryFactory.createPoint( points[0].getX(), points[0].getY(), null );
list.add( gmPoint );
break;
// an array of points
case SeShape.TYPE_MULTI_POINT:
Point[] gmPoints = new Point[numPoints];
for ( int pt = 0; pt < numPoints; pt++ ) {
gmPoints[pt] = GeometryFactory.createPoint( points[pt].getX(), points[pt].getY(), null );
}
try {
MultiPoint gmMultiPoint = GeometryFactory.createMultiPoint( gmPoints );
list.add( gmMultiPoint );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
break;
// a single line, simple as it does not intersect itself
case SeShape.TYPE_SIMPLE_LINE:
// or a single, non-simple line
case SeShape.TYPE_LINE:
Position[] gmSimpleLinePosition = new Position[numPoints];
for ( int pt = 0; pt < numPoints; pt++ ) {
gmSimpleLinePosition[pt] = GeometryFactory.createPosition( points[pt].getX(), points[pt].getY() );
}
try {
Curve gmCurve = GeometryFactory.createCurve( gmSimpleLinePosition, null );
list.add( gmCurve );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
break;
// an array of lines, simple as they do not intersect with themself
case SeShape.TYPE_MULTI_SIMPLE_LINE:
// or an array of non-simple lines
case SeShape.TYPE_MULTI_LINE:
Curve[] gmCurves = new Curve[numParts];
for ( int partNo = 0; partNo < numParts; partNo++ ) {
int lastPoint = shape.getNumPoints( partNo + 1, 1 ) + partOffset[partNo];
Position[] gmMultiSimpleLinePosition = new Position[shape.getNumPoints( partNo + 1, 1 )];
int i = 0;
for ( int pt = partOffset[partNo]; pt < lastPoint; pt++ ) {
gmMultiSimpleLinePosition[i] = GeometryFactory.createPosition( points[pt].getX(), points[pt].getY() );
i++;
}
try {
gmCurves[partNo] = GeometryFactory.createCurve( gmMultiSimpleLinePosition, null );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
}
try {
MultiCurve gmMultiCurve = GeometryFactory.createMultiCurve( gmCurves );
list.add( gmMultiCurve );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
break;
// a single polygon which might contain islands
case SeShape.TYPE_POLYGON:
int numSubParts = shape.getNumSubParts( 1 );
Position[] gmPolygonExteriorRing = new Position[shape.getNumPoints( 1, 1 )];
int kk = shape.getNumPoints( 1, 1 );
for ( int pt = 0; pt < kk; pt++ ) {
gmPolygonExteriorRing[pt] = GeometryFactory.createPosition( points[pt].getX(), points[pt].getY() );
}
Position[][] gmPolygonInteriorRings = null;
// if it is a donut create inner rings
if ( numSubParts > 1 ) {
gmPolygonInteriorRings = new Position[numSubParts - 1][];
int j = 0;
for ( int subPartNo = 1; subPartNo < numSubParts; subPartNo++ ) {
int lastPoint = shape.getNumPoints( 1, subPartNo + 1 ) + subPartOffset[subPartNo];
Position[] gmPolygonPosition = new Position[shape.getNumPoints( 1, subPartNo + 1 )];
int i = 0;
for ( int pt = subPartOffset[subPartNo]; pt < lastPoint; pt++ ) {
gmPolygonPosition[i] = GeometryFactory.createPosition( points[pt].getX(), points[pt].getY() );
i++;
}
gmPolygonInteriorRings[j] = gmPolygonPosition;
j++;
}
}
try {
Surface gmSurface = GeometryFactory.createSurface( gmPolygonExteriorRing, gmPolygonInteriorRings,
new SurfaceInterpolationImpl(), null );
list.add( gmSurface );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
break;
// an array of polygons which might contain islands
case SeShape.TYPE_MULTI_POLYGON:
Surface[] gmMultiPolygonSurface = getMultiPolygon( shape, points, partOffset, subPartOffset );
try {
MultiSurface gmMultiSurface = GeometryFactory.createMultiSurface( gmMultiPolygonSurface );
list.add( gmMultiSurface );
} catch ( Exception gme ) {
gme.printStackTrace();
throw new DeegreeSeException( gme.toString() );
}
break;
default:
LOG.logInfo( "Unknown GeometryType - ID: " + shape.getType() );
break;
} // End of switch
} // End Method createGeometry
/**
* @param shape
* @param points
* @param partOffset
* @param subPartOffset
* @throws SeException
*/
private Surface[] getMultiPolygon( SeShape shape, SDEPoint[] points, int[] partOffset, int[] subPartOffset )
throws SeException, DeegreeSeException {
Surface[] surfaces = new Surface[partOffset.length];
int hh = 0;
for ( int i = 0; i < partOffset.length; i++ ) {
// cnt = number of all rings of the current polygon (part)
int cnt = shape.getNumSubParts( i + 1 );
// exterior ring
int count = shape.getNumPoints( i + 1, 1 );
Position[] ex = new Position[count];
int off = subPartOffset[hh];
for ( int j = 0; j < count; j++ ) {
ex[j] = GeometryFactory.createPosition( points[j + off].getX(), points[j + off].getY() );
}
// interior ring
Position[][] inn = null;
if ( cnt > 1 ) {
inn = new Position[cnt - 1][];
}
hh++;
for ( int j = 1; j < cnt; j++ ) {
inn[j - 1] = new Position[shape.getNumPoints( i + 1, j + 1 )];
off = subPartOffset[hh];
for ( int k = 0; k < inn[j - 1].length; k++ ) {
inn[j - 1][k] = GeometryFactory.createPosition( points[j + off - 1].getX(),
points[j + off - 1].getY() );
}
hh++;
}
try {
SurfaceInterpolation si = new SurfaceInterpolationImpl();
surfaces[i] = GeometryFactory.createSurface( ex, inn, si, null );
} catch ( Exception e ) {
throw new DeegreeSeException( StringTools.stackTraceToString( e ) );
}
}
return surfaces;
}
} // End Class SpatialQueryEx
| lgpl-2.1 |
opensagres/xdocreport.eclipse | rap/org.eclipse.draw2d/src/org/eclipse/draw2d/text/CompositeBox.java | 1714 | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.draw2d.text;
/**
* A FlowBox that can contain other FlowBoxes. The contained FlowBoxes are
* called <i>fragments</i>.
*
* @author hudsonr
* @since 2.1
*/
public abstract class CompositeBox extends FlowBox {
int recommendedWidth = -1;
/**
* Adds the given box and updates properties of this composite box.
*
* @param box
* the child being added
*/
public abstract void add(FlowBox box);
abstract int getBottomMargin();
/**
* Returns the recommended width for this CompositeBox.
*
* @return the recommended width
*/
public int getRecommendedWidth() {
return recommendedWidth;
}
abstract int getTopMargin();
/**
* Sets the recommended width for this CompositeBox.
*
* @param w
* the width
*/
public void setRecommendedWidth(int w) {
recommendedWidth = w;
}
/**
* Positions the box vertically by setting the y coordinate for the top of
* the content of the line. For internal use only.
*
* @param top
* the y coordinate
* @since 3.1
*/
public abstract void setLineTop(int top);
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | engine/core/src/test/java/org/pentaho/reporting/engine/classic/core/modules/gui/base/ParameterReportControllerPaneTest.java | 2984 | /*
* 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.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.modules.gui.base;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.pentaho.reporting.engine.classic.core.parameters.AbstractParameter;
import org.pentaho.reporting.engine.classic.core.parameters.ParameterAttributeNames;
import org.pentaho.reporting.engine.classic.core.parameters.PlainParameter;
/**
* Created by dima.prokopenko@gmail.com on 9/20/2016.
*/
public class ParameterReportControllerPaneTest {
private AbstractParameter entry = new PlainParameter( "junit_parameter" );
private ParameterReportControllerPane pane = new ParameterReportControllerPane();
@Before
public void before() {
entry.setParameterAttribute( ParameterAttributeNames.Core.NAMESPACE,
ParameterAttributeNames.Core.LABEL, "labelValue" );
}
@Test
public void computeSwingLabelTest() {
entry.setParameterAttribute( ParameterAttributeNames.Swing.NAMESPACE,
ParameterAttributeNames.Swing.LABEL, "swingName" );
String label = pane.computeLabel( entry );
assertNotNull( label );
assertEquals( "swingName", label );
}
@Test
public void computeLabelTest() {
String label = pane.computeLabel( entry );
assertNotNull( label );
assertEquals( "labelValue", label );
}
@Test
public void computeTranslatedTest() {
AbstractParameter entry = mock( AbstractParameter.class );
when( entry.getParameterAttribute(
anyString(),
eq( ParameterAttributeNames.Swing.LABEL ),
any()
) ).thenReturn( null );
when( entry.getTranslatedParameterAttribute(
anyString(),
eq( ParameterAttributeNames.Core.LABEL ),
any()
) ).thenReturn( "label" );
String label = pane.computeLabel( entry );
assertNotNull( label );
assertEquals( "label", label );
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/jpa/ql/FunctionKeywordTest.java | 884 | /*
* 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.jpa.ql;
import org.hibernate.Session;
import org.junit.Test;
import org.hibernate.test.jpa.AbstractJPATest;
/**
* Test use of the JPA 2.1 FUNCTION keyword.
*
* @author Steve Ebersole
*/
public class FunctionKeywordTest extends AbstractJPATest {
@Test
public void basicFixture() {
Session s = openSession();
s.createQuery( "select i from Item i where substring( i.name, 1, 3 ) = 'abc'" )
.list();
s.close();
}
@Test
public void basicTest() {
Session s = openSession();
s.createQuery( "select i from Item i where function( 'substring', i.name, 1, 3 ) = 'abc'" )
.list();
s.close();
}
}
| lgpl-2.1 |
gpiancastelli/tuprolog-5 | src/alice/tuprolog/lib/InvalidObjectIdException.java | 1157 | /*
* tuProlog - Copyright (C) 2001-2002 aliCE team at deis.unibo.it
*
* 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 alice.tuprolog.lib;
import alice.tuprolog.PrologException;
/**
* This exception is raised when a not valid identifier is used
* to register an object in the JavaLibrary
*
* @see JavaLibrary
*/
public class InvalidObjectIdException extends PrologException {
private static final long serialVersionUID = 7495034598262848218L;
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/shimple/ShimpleTransformer.java | 3026 | package soot.shimple;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Navindra Umanee <navindra@cs.mcgill.ca>
* %%
* 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 java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.MethodSource;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.options.Options;
/**
* Traverses all methods, in all classes from the Scene, and transforms them to Shimple. Typically used for whole-program
* analysis on Shimple.
*
* @author Navindra Umanee
**/
public class ShimpleTransformer extends SceneTransformer {
private static final Logger logger = LoggerFactory.getLogger(ShimpleTransformer.class);
public ShimpleTransformer(Singletons.Global g) {
}
public static ShimpleTransformer v() {
return G.v().soot_shimple_ShimpleTransformer();
}
protected void internalTransform(String phaseName, Map options) {
if (Options.v().verbose()) {
logger.debug("Transforming all classes in the Scene to Shimple...");
}
// *** FIXME: Add debug output to indicate which class/method is being shimplified.
// *** FIXME: Is ShimpleTransformer the right solution? The call graph may deem
// some classes unreachable.
Iterator classesIt = Scene.v().getClasses().iterator();
while (classesIt.hasNext()) {
SootClass sClass = (SootClass) classesIt.next();
if (sClass.isPhantom()) {
continue;
}
Iterator methodsIt = sClass.getMethods().iterator();
while (methodsIt.hasNext()) {
SootMethod method = (SootMethod) methodsIt.next();
if (!method.isConcrete()) {
continue;
}
if (method.hasActiveBody()) {
Body body = method.getActiveBody();
ShimpleBody sBody = null;
if (body instanceof ShimpleBody) {
sBody = (ShimpleBody) body;
if (!sBody.isSSA()) {
sBody.rebuild();
}
} else {
sBody = Shimple.v().newBody(body);
}
method.setActiveBody(sBody);
} else {
MethodSource ms = new ShimpleMethodSource(method.getSource());
method.setSource(ms);
}
}
}
}
}
| lgpl-2.1 |
geotools/geotools | modules/library/opengis/src/main/java/org/opengis/geometry/coordinate/BSplineSurface.java | 2974 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2011, Open Source Geospatial Foundation (OSGeo)
* (C) 2003-2005, Open Geospatial Consortium Inc.
*
* All Rights Reserved. http://www.opengis.org/legal/
*/
package org.opengis.geometry.coordinate;
import static org.opengis.annotation.Obligation.MANDATORY;
import static org.opengis.annotation.Obligation.OPTIONAL;
import static org.opengis.annotation.Specification.ISO_19107;
import java.util.List;
import org.opengis.annotation.UML;
/**
* A rational or polynomial parametric surface that is represented by control points, basis
* functions and possibly weights. If the weights are all equal then the spline is piecewise
* polynomial. If they are not equal, then the spline is piecewise rational. If the boolean {@link
* #isPolynomial isPolynomial} is set to {@code true} then the weights shall all be set to 1.
*
* @version <A HREF="http://www.opengeospatial.org/standards/as">ISO 19107</A>
* @author Martin Desruisseaux (IRD)
* @since GeoAPI 2.1
*/
@UML(identifier = "GM_BSplineSurface", specification = ISO_19107)
public interface BSplineSurface extends GriddedSurface {
/**
* The algebraic degree of the basis functions for the first and second parameter. If only one
* value is given, then the two degrees are equal.
*
* @return The degrees as an array of length 1 or 2.
*/
@UML(identifier = "degree", obligation = MANDATORY, specification = ISO_19107)
int[] getDegrees();
/**
* Identifies particular types of surface which this spline is being used to approximate. It is
* for information only, used to capture the original intention. If no such approximation is
* intended, then this method returns {@code null}.
*
* @return The type of surface, or {@code null} if this information is not available.
*/
@UML(identifier = "surfaceForm", obligation = OPTIONAL, specification = ISO_19107)
BSplineSurfaceForm getSurfaceForm();
/**
* Returns two sequences of distinct knots used to define the B-spline basis functions for the
* two parameters. Recall that the knot data type holds information on knot multiplicity.
*
* @return The sequence of knots as an array of length 2.
*/
@UML(identifier = "knot", obligation = MANDATORY, specification = ISO_19107)
List<Knot>[] getKnots();
/**
* Gives the type of knot distribution used in defining this spline. This is for information
* only and is set according to the different construction-functions.
*
* @return The type of knot distribution, or {@code null} if none.
*/
@UML(identifier = "knotSpec", obligation = OPTIONAL, specification = ISO_19107)
KnotType getKnotSpec();
/** Returns {@code true} if this is a polynomial spline. */
@UML(identifier = "isPolynomial", obligation = MANDATORY, specification = ISO_19107)
boolean isPolynomial();
}
| lgpl-2.1 |
geotools/geotools | modules/plugin/jdbc/jdbc-db2/src/test/java/org/geotools/data/db2/DB2PrimaryKeyTestSetup.java | 13269 | /*
* 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
* 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 License for more details.
*/
package org.geotools.data.db2;
import java.sql.Connection;
import java.sql.SQLException;
import org.geotools.jdbc.JDBCPrimaryKeyTestSetup;
@SuppressWarnings("PMD.JUnit4TestShouldUseTestAnnotation") // not yet a JUnit4 test
public class DB2PrimaryKeyTestSetup extends JDBCPrimaryKeyTestSetup {
protected DB2PrimaryKeyTestSetup() {
super(new DB2TestSetup());
}
@Override
protected void createAutoGeneratedPrimaryKeyTable() throws Exception {
try (Connection con = getDataSource().getConnection()) {
String stmt =
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"auto\" (\"key\" int generated always as identity (start with 1, increment by 1),\"name\" varchar(255), \"geom\" DB2GSE.ST_GEOMETRY, primary key (\"key\"))";
con.prepareStatement(stmt).execute();
DB2Util.executeRegister(DB2TestUtil.SCHEMA, "auto", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"auto\" (\"name\",\"geom\") VALUES ('one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"auto\" (\"name\",\"geom\") VALUES ('two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"auto\" (\"name\",\"geom\") VALUES ('three',NULL)")
.execute();
}
}
private String getSquenceName() {
return "seq_key_SEQUENCE";
}
private String getSquenceNameQuoted() {
return DB2TestUtil.SCHEMA_QUOTED + ".\"" + getSquenceName() + "\"";
}
@Override
protected void createSequencedPrimaryKeyTable() throws Exception {
try (Connection con = getDataSource().getConnection()) {
con.prepareStatement(
"CREATE SEQUENCE "
+ getSquenceNameQuoted()
+ " AS INTEGER start with 1")
.execute();
con.prepareStatement(
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"seq\" (\"key\" int not null,\"name\" varchar(255), \"geom\" DB2GSE.ST_GEOMETRY, primary key (\"key\"))")
.execute();
DB2Util.executeRegister(DB2TestUtil.SCHEMA, "seq", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"seq\" VALUES (next value for "
+ getSquenceNameQuoted()
+ ",'one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"seq\" VALUES (next value for "
+ getSquenceNameQuoted()
+ ",'two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"seq\" VALUES (next value for "
+ getSquenceNameQuoted()
+ ",'three',NULL)")
.execute();
}
}
@Override
protected void createNonIncrementingPrimaryKeyTable() throws Exception {
try (Connection con = getDataSource().getConnection()) {
con.prepareStatement(
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"noninc\" (\"key\" int not null,\"name\" varchar(255), \"geom\" DB2GSE.ST_GEOMETRY, primary key (\"key\"))")
.execute();
DB2Util.executeRegister(DB2TestUtil.SCHEMA, "noninc", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"noninc\" VALUES (1,'one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"noninc\" VALUES (2,'two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"noninc\" VALUES (3,'three',NULL)")
.execute();
}
}
@Override
protected void createMultiColumnPrimaryKeyTable() throws Exception {
try (Connection con = getDataSource().getConnection()) {
con.prepareStatement(
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"multi\" (\"key1\" int not null, \"key2\" varchar(255) not null,\"name\" varchar(255) , \"geom\" DB2GSE.ST_GEOMETRY, primary key (\"key1\",\"key2\"))")
.execute();
DB2Util.executeRegister(DB2TestUtil.SCHEMA, "multi", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"multi\" VALUES (1,'x','one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"multi\" VALUES (2,'y','two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"multi\" VALUES (3,'z','three',NULL)")
.execute();
}
}
@Override
protected void createNullPrimaryKeyTable() throws Exception {
// set up table
try (Connection con = getDataSource().getConnection()) {
con.prepareStatement(
"CREATE TABLE "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nokey\" ( \"name\" varchar(255) )")
.execute();
// insert data
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nokey\" (\"name\") VALUES ( 'one' )")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nokey\" (\"name\") VALUES ( 'two' )")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nokey\" (\"name\") VALUES ( 'three' )")
.execute();
}
}
@Override
protected void createNonFirstColumnPrimaryKey() throws Exception {
try (Connection con = getDataSource().getConnection()) {
String stmt =
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nonfirst\" (\"name\" varchar(255), \"key\" int generated always as identity (start with 1, increment by 1), \"geom\" DB2GSE.ST_GEOMETRY, primary key (\"key\"))";
con.prepareStatement(stmt).execute();
DB2Util.executeRegister(
DB2TestUtil.SCHEMA, "nonfirst", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nonfirst\" (\"name\",\"geom\") VALUES ('one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nonfirst\" (\"name\",\"geom\") VALUES ('two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"nonfirst\" (\"name\",\"geom\") VALUES ('three',NULL)")
.execute();
}
}
private String getUniqueIndexName() {
return "uniq_key_INDEX";
}
private String getUniqueIndexNameQuoted() {
return DB2TestUtil.SCHEMA_QUOTED + ".\"" + getUniqueIndexName() + "\"";
}
@Override
protected void createUniqueIndexTable() throws Exception {
try (Connection con = getDataSource().getConnection()) {
con.prepareStatement(
"create table "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"uniq\" (\"key\" int not null,\"name\" varchar(255), \"geom\" DB2GSE.ST_GEOMETRY)")
.execute();
con.prepareStatement(
"CREATE UNIQUE INDEX "
+ getUniqueIndexNameQuoted()
+ " ON "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"uniq\"(\"key\")")
.execute();
DB2Util.executeRegister(DB2TestUtil.SCHEMA, "uniq", "geom", DB2TestUtil.SRSNAME, con);
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"uniq\" VALUES (1,'one',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"uniq\" VALUES (2,'two',NULL)")
.execute();
con.prepareStatement(
"INSERT INTO "
+ DB2TestUtil.SCHEMA_QUOTED
+ ".\"uniq\" VALUES (3,'three',NULL)")
.execute();
}
}
@Override
protected void dropAutoGeneratedPrimaryKeyTable() throws Exception {
dropSpatialTable("auto");
}
@Override
protected void dropSequencedPrimaryKeyTable() throws Exception {
dropSpatialTable("seq");
try (Connection con = getDataSource().getConnection()) {
DB2TestUtil.dropSequence(DB2TestUtil.SCHEMA, getSquenceName(), con);
} catch (SQLException e) {
}
}
@Override
protected void dropNonIncrementingPrimaryKeyTable() throws Exception {
dropSpatialTable("noninc");
}
@Override
protected void dropMultiColumnPrimaryKeyTable() throws Exception {
dropSpatialTable("multi");
}
private void dropSpatialTable(String tableName) throws Exception {
try (Connection con = getDataSource().getConnection()) {
DB2Util.executeUnRegister(DB2TestUtil.SCHEMA, tableName, "goem", con);
DB2TestUtil.dropTable(DB2TestUtil.SCHEMA, tableName, con);
} catch (SQLException e) {
}
}
@Override
protected void dropNullPrimaryKeyTable() throws Exception {
dropSpatialTable("nokey");
}
@Override
protected void dropUniqueIndexTable() throws Exception {
dropSpatialTable("uniq");
}
@Override
protected void dropNonFirstPrimaryKeyTable() throws Exception {
dropSpatialTable("nonfirst");
}
}
| lgpl-2.1 |
kerenby/nabus | src/org/jitsi/nabus/device/Camera.java | 1525 | package org.jitsi.nabus.device;
import org.jitsi.impl.neomedia.device.MediaDeviceImpl;
import org.jitsi.nabus.access.CameraAccess;
import org.jitsi.service.neomedia.MediaType;
import org.jitsi.service.neomedia.device.MediaDevice;
import org.jitsi.service.neomedia.format.MediaFormat;
import javax.media.CaptureDeviceInfo;
import java.awt.*;
import java.util.List;
/**
* Created by Sergey on 11/2/2014.
*/
public class Camera implements CameraAccess {
private MediaDevice device;
private CaptureDeviceInfo captureDeviceInfo;
private int frameRate;
private Dimension size;
public Camera(CaptureDeviceInfo captureDeviceInfo) {
this.device = new MediaDeviceImpl(captureDeviceInfo, MediaType.VIDEO);
this.captureDeviceInfo = captureDeviceInfo;
}
public String getName() {
return captureDeviceInfo.getName();
}
public MediaDevice getDevice() {
return this.device;
}
public MediaFormat getMediaFormat() {
return this.device.getFormat();
}
@Override
public void setFrameRate(int frameRate) {
this.frameRate = frameRate;
}
@Override
public List<Dimension> getAvailableCaptureSizes() {
return null;
}
@Override
public void setCaptureSize(Dimension size) {
this.size = size;
}
@Override
public void crateScreenShot() {
}
@Override
public void startRecording(String cameraDataHandler) {
}
@Override
public void stopRecording() {
}
}
| lgpl-2.1 |
kevin-chen-hw/LDAE | com.huawei.soa.ldae/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java | 49256 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.hql.internal.ast;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.QueryException;
import org.hibernate.engine.internal.JoinSequence;
import org.hibernate.engine.internal.ParameterBinder;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.hql.internal.antlr.HqlSqlBaseWalker;
import org.hibernate.hql.internal.antlr.HqlSqlTokenTypes;
import org.hibernate.hql.internal.antlr.HqlTokenTypes;
import org.hibernate.hql.internal.antlr.SqlTokenTypes;
import org.hibernate.hql.internal.ast.tree.AggregateNode;
import org.hibernate.hql.internal.ast.tree.AssignmentSpecification;
import org.hibernate.hql.internal.ast.tree.CollectionFunction;
import org.hibernate.hql.internal.ast.tree.ConstructorNode;
import org.hibernate.hql.internal.ast.tree.DeleteStatement;
import org.hibernate.hql.internal.ast.tree.DotNode;
import org.hibernate.hql.internal.ast.tree.FromClause;
import org.hibernate.hql.internal.ast.tree.FromElement;
import org.hibernate.hql.internal.ast.tree.FromElementFactory;
import org.hibernate.hql.internal.ast.tree.FromReferenceNode;
import org.hibernate.hql.internal.ast.tree.IdentNode;
import org.hibernate.hql.internal.ast.tree.IndexNode;
import org.hibernate.hql.internal.ast.tree.InsertStatement;
import org.hibernate.hql.internal.ast.tree.IntoClause;
import org.hibernate.hql.internal.ast.tree.MethodNode;
import org.hibernate.hql.internal.ast.tree.OperatorNode;
import org.hibernate.hql.internal.ast.tree.ParameterContainer;
import org.hibernate.hql.internal.ast.tree.ParameterNode;
import org.hibernate.hql.internal.ast.tree.QueryNode;
import org.hibernate.hql.internal.ast.tree.ResolvableNode;
import org.hibernate.hql.internal.ast.tree.RestrictableStatement;
import org.hibernate.hql.internal.ast.tree.ResultVariableRefNode;
import org.hibernate.hql.internal.ast.tree.SelectClause;
import org.hibernate.hql.internal.ast.tree.SelectExpression;
import org.hibernate.hql.internal.ast.tree.UpdateStatement;
import org.hibernate.hql.internal.ast.util.ASTPrinter;
import org.hibernate.hql.internal.ast.util.ASTUtil;
import org.hibernate.hql.internal.ast.util.AliasGenerator;
import org.hibernate.hql.internal.ast.util.JoinProcessor;
import org.hibernate.hql.internal.ast.util.LiteralProcessor;
import org.hibernate.hql.internal.ast.util.NodeTraverser;
import org.hibernate.hql.internal.ast.util.SessionFactoryHelper;
import org.hibernate.hql.internal.ast.util.SyntheticAndFactory;
import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.id.BulkInsertionCapableIdentifierGenerator;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.param.CollectionFilterKeyParameterSpecification;
import org.hibernate.param.NamedParameterSpecification;
import org.hibernate.param.ParameterSpecification;
import org.hibernate.param.PositionalParameterSpecification;
import org.hibernate.param.VersionTypeSeedParameterSpecification;
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.Queryable;
import org.hibernate.sql.JoinType;
import org.hibernate.type.AssociationType;
import org.hibernate.type.ComponentType;
import org.hibernate.type.DbTimestampType;
import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
import org.hibernate.usertype.UserVersionType;
import antlr.ASTFactory;
import antlr.RecognitionException;
import antlr.SemanticException;
import antlr.collections.AST;
/**
* Implements methods used by the HQL->SQL tree transform grammar (a.k.a. the second phase).
* <ul>
* <li>Isolates the Hibernate API-specific code from the ANTLR generated code.</li>
* <li>Handles the SQL fragments generated by the persisters in order to create the SELECT and FROM clauses,
* taking into account the joins and projections that are implied by the mappings (persister/queryable).</li>
* <li>Uses SqlASTFactory to create customized AST nodes.</li>
* </ul>
*
* @see SqlASTFactory
*/
public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, ParameterBinder.NamedParameterSource {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( HqlSqlWalker.class );
private final QueryTranslatorImpl queryTranslatorImpl;
private final HqlParser hqlParser;
private final SessionFactoryHelper sessionFactoryHelper;
private final Map tokenReplacements;
private final AliasGenerator aliasGenerator = new AliasGenerator();
private final LiteralProcessor literalProcessor;
private final ParseErrorHandler parseErrorHandler;
private final ASTPrinter printer;
private final String collectionFilterRole;
private FromClause currentFromClause;
private SelectClause selectClause;
/**
* Maps each top-level result variable to its SelectExpression;
* (excludes result variables defined in subqueries)
*/
private Map<String, SelectExpression> selectExpressionsByResultVariable = new HashMap<String, SelectExpression>();
private Set<Serializable> querySpaces = new HashSet<Serializable>();
private int parameterCount;
private Map namedParameters = new HashMap();
private ArrayList<ParameterSpecification> parameters = new ArrayList<ParameterSpecification>();
private int numberOfParametersInSetClause;
private int positionalParameterCount;
private ArrayList assignmentSpecifications = new ArrayList();
private JoinType impliedJoinType = JoinType.INNER_JOIN;
/**
* Create a new tree transformer.
*
* @param qti Back pointer to the query translator implementation that is using this tree transform.
* @param sfi The session factory implementor where the Hibernate mappings can be found.
* @param parser A reference to the phase-1 parser
* @param tokenReplacements Registers the token replacement map with the walker. This map will
* be used to substitute function names and constants.
* @param collectionRole The collection role name of the collection used as the basis for the
* filter, NULL if this is not a collection filter compilation.
*/
public HqlSqlWalker(
QueryTranslatorImpl qti,
SessionFactoryImplementor sfi,
HqlParser parser,
Map tokenReplacements,
String collectionRole) {
setASTFactory( new SqlASTFactory( this ) );
// Initialize the error handling delegate.
this.parseErrorHandler = new ErrorCounter( qti.getQueryString() );
this.queryTranslatorImpl = qti;
this.sessionFactoryHelper = new SessionFactoryHelper( sfi );
this.literalProcessor = new LiteralProcessor( this );
this.tokenReplacements = tokenReplacements;
this.collectionFilterRole = collectionRole;
this.hqlParser = parser;
this.printer = new ASTPrinter( SqlTokenTypes.class );
}
// handle trace logging ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private int traceDepth;
@Override
public void traceIn(String ruleName, AST tree) {
if ( !LOG.isTraceEnabled() ) {
return;
}
if ( inputState.guessing > 0 ) {
return;
}
String prefix = StringHelper.repeat( '-', ( traceDepth++ * 2 ) ) + "-> ";
String traceText = ruleName + " (" + buildTraceNodeName( tree ) + ")";
LOG.trace( prefix + traceText );
}
private String buildTraceNodeName(AST tree) {
return tree == null
? "???"
: tree.getText() + " [" + printer.getTokenTypeName( tree.getType() ) + "]";
}
@Override
public void traceOut(String ruleName, AST tree) {
if ( !LOG.isTraceEnabled() ) {
return;
}
if ( inputState.guessing > 0 ) {
return;
}
String prefix = "<-" + StringHelper.repeat( '-', ( --traceDepth * 2 ) ) + " ";
LOG.trace( prefix + ruleName );
}
@Override
protected void prepareFromClauseInputTree(AST fromClauseInput) {
if ( !isSubQuery() ) {
// // inject param specifications to account for dynamic filter param values
// if ( ! getEnabledFilters().isEmpty() ) {
// Iterator filterItr = getEnabledFilters().values().iterator();
// while ( filterItr.hasNext() ) {
// FilterImpl filter = ( FilterImpl ) filterItr.next();
// if ( ! filter.getFilterDefinition().getParameterNames().isEmpty() ) {
// Iterator paramItr = filter.getFilterDefinition().getParameterNames().iterator();
// while ( paramItr.hasNext() ) {
// String parameterName = ( String ) paramItr.next();
// // currently param filters *only* work with single-column parameter types;
// // if that limitation is ever lifted, this logic will need to change to account for that
// ParameterNode collectionFilterKeyParameter = ( ParameterNode ) astFactory.create( PARAM, "?" );
// DynamicFilterParameterSpecification paramSpec = new DynamicFilterParameterSpecification(
// filter.getName(),
// parameterName,
// filter.getFilterDefinition().getParameterType( parameterName ),
// positionalParameterCount++
// );
// collectionFilterKeyParameter.setHqlParameterSpecification( paramSpec );
// parameters.add( paramSpec );
// }
// }
// }
// }
if ( isFilter() ) {
// Handle collection-filter compilation.
// IMPORTANT NOTE: This is modifying the INPUT (HQL) tree, not the output tree!
QueryableCollection persister = sessionFactoryHelper.getCollectionPersister( collectionFilterRole );
Type collectionElementType = persister.getElementType();
if ( !collectionElementType.isEntityType() ) {
throw new QueryException( "collection of values in filter: this" );
}
String collectionElementEntityName = persister.getElementPersister().getEntityName();
ASTFactory inputAstFactory = hqlParser.getASTFactory();
AST fromElement = inputAstFactory.create( HqlTokenTypes.FILTER_ENTITY, collectionElementEntityName );
ASTUtil.createSibling( inputAstFactory, HqlTokenTypes.ALIAS, "this", fromElement );
fromClauseInput.addChild( fromElement );
// Show the modified AST.
LOG.debug( "prepareFromClauseInputTree() : Filter - Added 'this' as a from element..." );
queryTranslatorImpl.showHqlAst( hqlParser.getAST() );
// Create a parameter specification for the collection filter...
Type collectionFilterKeyType = sessionFactoryHelper.requireQueryableCollection( collectionFilterRole )
.getKeyType();
ParameterNode collectionFilterKeyParameter = (ParameterNode) astFactory.create( PARAM, "?" );
CollectionFilterKeyParameterSpecification collectionFilterKeyParameterSpec = new CollectionFilterKeyParameterSpecification(
collectionFilterRole, collectionFilterKeyType, positionalParameterCount++
);
collectionFilterKeyParameter.setHqlParameterSpecification( collectionFilterKeyParameterSpec );
parameters.add( collectionFilterKeyParameterSpec );
}
}
}
public boolean isFilter() {
return collectionFilterRole != null;
}
public String getCollectionFilterRole() {
return collectionFilterRole;
}
public SessionFactoryHelper getSessionFactoryHelper() {
return sessionFactoryHelper;
}
public Map getTokenReplacements() {
return tokenReplacements;
}
public AliasGenerator getAliasGenerator() {
return aliasGenerator;
}
public FromClause getCurrentFromClause() {
return currentFromClause;
}
public ParseErrorHandler getParseErrorHandler() {
return parseErrorHandler;
}
@Override
public void reportError(RecognitionException e) {
parseErrorHandler.reportError( e ); // Use the delegate.
}
@Override
public void reportError(String s) {
parseErrorHandler.reportError( s ); // Use the delegate.
}
@Override
public void reportWarning(String s) {
parseErrorHandler.reportWarning( s );
}
/**
* Returns the set of unique query spaces (a.k.a.
* table names) that occurred in the query.
*
* @return A set of table names (Strings).
*/
public Set<Serializable> getQuerySpaces() {
return querySpaces;
}
@Override
protected AST createFromElement(String path, AST alias, AST propertyFetch) throws SemanticException {
FromElement fromElement = currentFromClause.addFromElement( path, alias );
fromElement.setAllPropertyFetch( propertyFetch != null );
return fromElement;
}
@Override
protected AST createFromFilterElement(AST filterEntity, AST alias) throws SemanticException {
FromElement fromElement = currentFromClause.addFromElement( filterEntity.getText(), alias );
FromClause fromClause = fromElement.getFromClause();
QueryableCollection persister = sessionFactoryHelper.getCollectionPersister( collectionFilterRole );
// Get the names of the columns used to link between the collection
// owner and the collection elements.
String[] keyColumnNames = persister.getKeyColumnNames();
String fkTableAlias = persister.isOneToMany()
? fromElement.getTableAlias()
: fromClause.getAliasGenerator().createName( collectionFilterRole );
JoinSequence join = sessionFactoryHelper.createJoinSequence();
join.setRoot( persister, fkTableAlias );
if ( !persister.isOneToMany() ) {
join.addJoin(
(AssociationType) persister.getElementType(),
fromElement.getTableAlias(),
JoinType.INNER_JOIN,
persister.getElementColumnNames( fkTableAlias )
);
}
join.addCondition( fkTableAlias, keyColumnNames, " = ?" );
fromElement.setJoinSequence( join );
fromElement.setFilter( true );
LOG.debug( "createFromFilterElement() : processed filter FROM element." );
return fromElement;
}
@Override
protected void createFromJoinElement(
AST path,
AST alias,
int joinType,
AST fetchNode,
AST propertyFetch,
AST with) throws SemanticException {
boolean fetch = fetchNode != null;
if ( fetch && isSubQuery() ) {
throw new QueryException( "fetch not allowed in subquery from-elements" );
}
// The path AST should be a DotNode, and it should have been evaluated already.
if ( path.getType() != SqlTokenTypes.DOT ) {
throw new SemanticException( "Path expected for join!" );
}
DotNode dot = (DotNode) path;
JoinType hibernateJoinType = JoinProcessor.toHibernateJoinType( joinType );
dot.setJoinType( hibernateJoinType ); // Tell the dot node about the join type.
dot.setFetch( fetch );
// Generate an explicit join for the root dot node. The implied joins will be collected and passed up
// to the root dot node.
dot.resolve( true, false, alias == null ? null : alias.getText() );
final FromElement fromElement;
if ( dot.getDataType() != null && dot.getDataType().isComponentType() ) {
if ( dot.getDataType().isAnyType() ) {
throw new SemanticException( "An AnyType attribute cannot be join fetched" );
// ^^ because the discriminator (aka, the "meta columns") must be known to the SQL in
// a non-parameterized way.
}
FromElementFactory factory = new FromElementFactory(
getCurrentFromClause(),
dot.getLhs().getFromElement(),
dot.getPropertyPath(),
alias == null ? null : alias.getText(),
null,
false
);
fromElement = factory.createComponentJoin( (ComponentType) dot.getDataType() );
}
else {
fromElement = dot.getImpliedJoin();
fromElement.setAllPropertyFetch( propertyFetch != null );
if ( with != null ) {
if ( fetch ) {
throw new SemanticException( "with-clause not allowed on fetched associations; use filters" );
}
handleWithFragment( fromElement, with );
}
}
if ( LOG.isDebugEnabled() ) {
LOG.debug( "createFromJoinElement() : " + getASTPrinter().showAsString( fromElement, "-- join tree --" ) );
}
}
private void handleWithFragment(FromElement fromElement, AST hqlWithNode) throws SemanticException {
try {
withClause( hqlWithNode );
AST hqlSqlWithNode = returnAST;
if ( LOG.isDebugEnabled() ) {
LOG.debug(
"handleWithFragment() : " + getASTPrinter().showAsString(
hqlSqlWithNode,
"-- with clause --"
)
);
}
WithClauseVisitor visitor = new WithClauseVisitor( fromElement, queryTranslatorImpl );
NodeTraverser traverser = new NodeTraverser( visitor );
traverser.traverseDepthFirst( hqlSqlWithNode );
String withClauseJoinAlias = visitor.getJoinAlias();
if ( withClauseJoinAlias == null ) {
withClauseJoinAlias = fromElement.getCollectionTableAlias();
}
else {
FromElement referencedFromElement = visitor.getReferencedFromElement();
if ( referencedFromElement != fromElement ) {
LOG.warnf(
"with-clause expressions do not reference the from-clause element to which the " +
"with-clause was associated. The query may not work as expected [%s]",
queryTranslatorImpl.getQueryString()
);
}
}
SqlGenerator sql = new SqlGenerator( getSessionFactoryHelper().getFactory() );
sql.whereExpr( hqlSqlWithNode.getFirstChild() );
fromElement.setWithClauseFragment( withClauseJoinAlias, "(" + sql.getSQL() + ")" );
}
catch (SemanticException e) {
throw e;
}
catch (InvalidWithClauseException e) {
throw e;
}
catch (Exception e) {
throw new SemanticException( e.getMessage() );
}
}
private static class WithClauseVisitor implements NodeTraverser.VisitationStrategy {
private final FromElement joinFragment;
private final QueryTranslatorImpl queryTranslatorImpl;
private FromElement referencedFromElement;
private String joinAlias;
public WithClauseVisitor(FromElement fromElement, QueryTranslatorImpl queryTranslatorImpl) {
this.joinFragment = fromElement;
this.queryTranslatorImpl = queryTranslatorImpl;
}
public void visit(AST node) {
// TODO : currently expects that the individual with expressions apply to the same sql table join.
// This may not be the case for joined-subclass where the property values
// might be coming from different tables in the joined hierarchy. At some
// point we should expand this to support that capability. However, that has
// some difficulties:
// 1) the biggest is how to handle ORs when the individual comparisons are
// linked to different sql joins.
// 2) here we would need to track each comparison individually, along with
// the join alias to which it applies and then pass that information
// back to the FromElement so it can pass it along to the JoinSequence
if ( node instanceof DotNode ) {
DotNode dotNode = (DotNode) node;
FromElement fromElement = dotNode.getFromElement();
if ( referencedFromElement != null ) {
if ( fromElement != referencedFromElement ) {
throw new HibernateException( "with-clause referenced two different from-clause elements" );
}
}
else {
referencedFromElement = fromElement;
joinAlias = extractAppliedAlias( dotNode );
// TODO : temporary
// needed because currently persister is the one that
// creates and renders the join fragments for inheritance
// hierarchies...
if ( !joinAlias.equals( referencedFromElement.getTableAlias() ) ) {
throw new InvalidWithClauseException(
"with clause can only reference columns in the driving table",
queryTranslatorImpl.getQueryString()
);
}
}
}
else if ( node instanceof ParameterNode ) {
applyParameterSpecification( ( (ParameterNode) node ).getHqlParameterSpecification() );
}
else if ( node instanceof ParameterContainer ) {
applyParameterSpecifications( (ParameterContainer) node );
}
}
private void applyParameterSpecifications(ParameterContainer parameterContainer) {
if ( parameterContainer.hasEmbeddedParameters() ) {
ParameterSpecification[] specs = parameterContainer.getEmbeddedParameters();
for ( ParameterSpecification spec : specs ) {
applyParameterSpecification( spec );
}
}
}
private void applyParameterSpecification(ParameterSpecification paramSpec) {
joinFragment.addEmbeddedParameter( paramSpec );
}
private String extractAppliedAlias(DotNode dotNode) {
return dotNode.getText().substring( 0, dotNode.getText().indexOf( '.' ) );
}
public FromElement getReferencedFromElement() {
return referencedFromElement;
}
public String getJoinAlias() {
return joinAlias;
}
}
/**
* Sets the current 'FROM' context.
*
* @param fromNode The new 'FROM' context.
* @param inputFromNode The from node from the input AST.
*/
@Override
protected void pushFromClause(AST fromNode, AST inputFromNode) {
FromClause newFromClause = (FromClause) fromNode;
newFromClause.setParentFromClause( currentFromClause );
currentFromClause = newFromClause;
}
/**
* Returns to the previous 'FROM' context.
*/
private void popFromClause() {
currentFromClause = currentFromClause.getParentFromClause();
}
@Override
protected void lookupAlias(AST aliasRef)
throws SemanticException {
FromElement alias = currentFromClause.getFromElement( aliasRef.getText() );
FromReferenceNode aliasRefNode = (FromReferenceNode) aliasRef;
aliasRefNode.setFromElement( alias );
}
@Override
protected void setImpliedJoinType(int joinType) {
impliedJoinType = JoinProcessor.toHibernateJoinType( joinType );
}
public JoinType getImpliedJoinType() {
return impliedJoinType;
}
@Override
protected AST lookupProperty(AST dot, boolean root, boolean inSelect) throws SemanticException {
DotNode dotNode = (DotNode) dot;
FromReferenceNode lhs = dotNode.getLhs();
AST rhs = lhs.getNextSibling();
switch ( rhs.getType() ) {
case SqlTokenTypes.ELEMENTS:
case SqlTokenTypes.INDICES:
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"lookupProperty() %s => %s(%s)",
dotNode.getPath(),
rhs.getText(),
lhs.getPath()
);
}
CollectionFunction f = (CollectionFunction) rhs;
// Re-arrange the tree so that the collection function is the root and the lhs is the path.
f.setFirstChild( lhs );
lhs.setNextSibling( null );
dotNode.setFirstChild( f );
resolve( lhs ); // Don't forget to resolve the argument!
f.resolve( inSelect ); // Resolve the collection function now.
return f;
default:
// Resolve everything up to this dot, but don't resolve the placeholders yet.
dotNode.resolveFirstChild();
return dotNode;
}
}
@Override
protected boolean isNonQualifiedPropertyRef(AST ident) {
final String identText = ident.getText();
if ( currentFromClause.isFromElementAlias( identText ) ) {
return false;
}
List fromElements = currentFromClause.getExplicitFromElements();
if ( fromElements.size() == 1 ) {
final FromElement fromElement = (FromElement) fromElements.get( 0 );
try {
LOG.tracev( "Attempting to resolve property [{0}] as a non-qualified ref", identText );
return fromElement.getPropertyMapping( identText ).toType( identText ) != null;
}
catch (QueryException e) {
// Should mean that no such property was found
}
}
return false;
}
@Override
protected AST lookupNonQualifiedProperty(AST property) throws SemanticException {
final FromElement fromElement = (FromElement) currentFromClause.getExplicitFromElements().get( 0 );
AST syntheticDotNode = generateSyntheticDotNodeForNonQualifiedPropertyRef( property, fromElement );
return lookupProperty( syntheticDotNode, false, getCurrentClauseType() == HqlSqlTokenTypes.SELECT );
}
private AST generateSyntheticDotNodeForNonQualifiedPropertyRef(AST property, FromElement fromElement) {
AST dot = getASTFactory().create( DOT, "{non-qualified-property-ref}" );
// TODO : better way?!?
( (DotNode) dot ).setPropertyPath( ( (FromReferenceNode) property ).getPath() );
IdentNode syntheticAlias = (IdentNode) getASTFactory().create( IDENT, "{synthetic-alias}" );
syntheticAlias.setFromElement( fromElement );
syntheticAlias.setResolved();
dot.setFirstChild( syntheticAlias );
dot.addChild( property );
return dot;
}
@Override
protected void processQuery(AST select, AST query) throws SemanticException {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "processQuery() : %s", query.toStringTree() );
}
try {
QueryNode qn = (QueryNode) query;
// Was there an explicit select expression?
boolean explicitSelect = select != null && select.getNumberOfChildren() > 0;
// Add in the EntityGraph attribute nodes.
if ( queryTranslatorImpl.getEntityGraphQueryHint() != null ) {
qn.getFromClause().getFromElements().addAll(
queryTranslatorImpl.getEntityGraphQueryHint().toFromElements( qn.getFromClause(), this )
);
}
if ( !explicitSelect ) {
// No explicit select expression; render the id and properties
// projection lists for every persister in the from clause into
// a single 'token node'.
//TODO: the only reason we need this stuff now is collection filters,
// we should get rid of derived select clause completely!
createSelectClauseFromFromClause( qn );
}
else {
// Use the explicitly declared select expression; determine the
// return types indicated by each select token
useSelectClause( select );
}
// After that, process the JOINs.
// Invoke a delegate to do the work, as this is farily complex.
JoinProcessor joinProcessor = new JoinProcessor( this );
joinProcessor.processJoins( qn );
// Attach any mapping-defined "ORDER BY" fragments
Iterator itr = qn.getFromClause().getProjectionList().iterator();
while ( itr.hasNext() ) {
final FromElement fromElement = (FromElement) itr.next();
// if ( fromElement.isFetch() && fromElement.isCollectionJoin() ) {
if ( fromElement.isFetch() && fromElement.getQueryableCollection() != null ) {
// Does the collection referenced by this FromElement
// specify an order-by attribute? If so, attach it to
// the query's order-by
if ( fromElement.getQueryableCollection().hasOrdering() ) {
String orderByFragment = fromElement
.getQueryableCollection()
.getSQLOrderByString( fromElement.getCollectionTableAlias() );
qn.getOrderByClause().addOrderFragment( orderByFragment );
}
if ( fromElement.getQueryableCollection().hasManyToManyOrdering() ) {
String orderByFragment = fromElement.getQueryableCollection()
.getManyToManyOrderByString( fromElement.getTableAlias() );
qn.getOrderByClause().addOrderFragment( orderByFragment );
}
}
}
}
finally {
popFromClause();
}
}
protected void postProcessDML(RestrictableStatement statement) throws SemanticException {
statement.getFromClause().resolve();
FromElement fromElement = (FromElement) statement.getFromClause().getFromElements().get( 0 );
Queryable persister = fromElement.getQueryable();
// Make #@%$^#^&# sure no alias is applied to the table name
fromElement.setText( persister.getTableName() );
// // append any filter fragments; the EMPTY_MAP is used under the assumption that
// // currently enabled filters should not affect this process
// if ( persister.getDiscriminatorType() != null ) {
// new SyntheticAndFactory( getASTFactory() ).addDiscriminatorWhereFragment(
// statement,
// persister,
// java.util.Collections.EMPTY_MAP,
// fromElement.getTableAlias()
// );
// }
if ( persister.getDiscriminatorType() != null || !queryTranslatorImpl.getEnabledFilters().isEmpty() ) {
new SyntheticAndFactory( this ).addDiscriminatorWhereFragment(
statement,
persister,
queryTranslatorImpl.getEnabledFilters(),
fromElement.getTableAlias()
);
}
}
@Override
protected void postProcessUpdate(AST update) throws SemanticException {
UpdateStatement updateStatement = (UpdateStatement) update;
postProcessDML( updateStatement );
}
@Override
protected void postProcessDelete(AST delete) throws SemanticException {
postProcessDML( (DeleteStatement) delete );
}
@Override
protected void postProcessInsert(AST insert) throws SemanticException, QueryException {
InsertStatement insertStatement = (InsertStatement) insert;
insertStatement.validate();
SelectClause selectClause = insertStatement.getSelectClause();
Queryable persister = insertStatement.getIntoClause().getQueryable();
if ( !insertStatement.getIntoClause().isExplicitIdInsertion() ) {
// the insert did not explicitly reference the id. See if
// 1) that is allowed
// 2) whether we need to alter the SQL tree to account for id
final IdentifierGenerator generator = persister.getIdentifierGenerator();
if ( !BulkInsertionCapableIdentifierGenerator.class.isInstance( generator ) ) {
throw new QueryException(
"Invalid identifier generator encountered for implicit id handling as part of bulk insertions"
);
}
final BulkInsertionCapableIdentifierGenerator capableGenerator =
BulkInsertionCapableIdentifierGenerator.class.cast( generator );
if ( !capableGenerator.supportsBulkInsertionIdentifierGeneration() ) {
throw new QueryException(
"Identifier generator reported it does not support implicit id handling as part of bulk insertions"
);
}
final String fragment = capableGenerator.determineBulkInsertionIdentifierGenerationSelectFragment(
sessionFactoryHelper.getFactory().getDialect()
);
if ( fragment != null ) {
// we got a fragment from the generator, so alter the sql tree...
//
// first, wrap the fragment as a node
AST fragmentNode = getASTFactory().create( HqlSqlTokenTypes.SQL_TOKEN, fragment );
// next, rearrange the SQL tree to add the fragment node as the first select expression
AST originalFirstSelectExprNode = selectClause.getFirstChild();
selectClause.setFirstChild( fragmentNode );
fragmentNode.setNextSibling( originalFirstSelectExprNode );
// finally, prepend the id column name(s) to the insert-spec
insertStatement.getIntoClause().prependIdColumnSpec();
}
}
if ( sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect() ) {
AST child = selectClause.getFirstChild();
int i = 0;
while ( child != null ) {
if ( child instanceof ParameterNode ) {
// infer the parameter type from the type listed in the INSERT INTO clause
( (ParameterNode) child ).setExpectedType(
insertStatement.getIntoClause()
.getInsertionTypes()[selectClause.getParameterPositions().get( i )]
);
i++;
}
child = child.getNextSibling();
}
}
final boolean includeVersionProperty = persister.isVersioned() &&
!insertStatement.getIntoClause().isExplicitVersionInsertion() &&
persister.isVersionPropertyInsertable();
if ( includeVersionProperty ) {
// We need to seed the version value as part of this bulk insert
VersionType versionType = persister.getVersionType();
AST versionValueNode = null;
if ( sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect() ) {
int[] sqlTypes = versionType.sqlTypes( sessionFactoryHelper.getFactory() );
if ( sqlTypes == null || sqlTypes.length == 0 ) {
throw new IllegalStateException( versionType.getClass() + ".sqlTypes() returns null or empty array" );
}
if ( sqlTypes.length > 1 ) {
throw new IllegalStateException(
versionType.getClass() +
".sqlTypes() returns > 1 element; only single-valued versions are allowed."
);
}
versionValueNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
( (ParameterNode) versionValueNode ).setHqlParameterSpecification( paramSpec );
parameters.add( 0, paramSpec );
if ( sessionFactoryHelper.getFactory().getDialect().requiresCastingOfParametersInSelectClause() ) {
// we need to wrtap the param in a cast()
MethodNode versionMethodNode = (MethodNode) getASTFactory().create(
HqlSqlTokenTypes.METHOD_CALL,
"("
);
AST methodIdentNode = getASTFactory().create( HqlSqlTokenTypes.IDENT, "cast" );
versionMethodNode.addChild( methodIdentNode );
versionMethodNode.initializeMethodNode( methodIdentNode, true );
AST castExprListNode = getASTFactory().create( HqlSqlTokenTypes.EXPR_LIST, "exprList" );
methodIdentNode.setNextSibling( castExprListNode );
castExprListNode.addChild( versionValueNode );
versionValueNode.setNextSibling(
getASTFactory().create(
HqlSqlTokenTypes.IDENT,
sessionFactoryHelper.getFactory().getDialect().getTypeName( sqlTypes[0] )
)
);
processFunction( versionMethodNode, true );
versionValueNode = versionMethodNode;
}
}
else {
if ( isIntegral( versionType ) ) {
try {
Object seedValue = versionType.seed( null );
versionValueNode = getASTFactory().create( HqlSqlTokenTypes.SQL_TOKEN, seedValue.toString() );
}
catch (Throwable t) {
throw new QueryException( "could not determine seed value for version on bulk insert [" + versionType + "]" );
}
}
else if ( isDatabaseGeneratedTimestamp( versionType ) ) {
String functionName = sessionFactoryHelper.getFactory()
.getDialect()
.getCurrentTimestampSQLFunctionName();
versionValueNode = getASTFactory().create( HqlSqlTokenTypes.SQL_TOKEN, functionName );
}
else {
throw new QueryException( "cannot handle version type [" + versionType + "] on bulk inserts with dialects not supporting parameters in insert-select statements" );
}
}
AST currentFirstSelectExprNode = selectClause.getFirstChild();
selectClause.setFirstChild( versionValueNode );
versionValueNode.setNextSibling( currentFirstSelectExprNode );
insertStatement.getIntoClause().prependVersionColumnSpec();
}
if ( insertStatement.getIntoClause().isDiscriminated() ) {
String sqlValue = insertStatement.getIntoClause().getQueryable().getDiscriminatorSQLValue();
AST discrimValue = getASTFactory().create( HqlSqlTokenTypes.SQL_TOKEN, sqlValue );
insertStatement.getSelectClause().addChild( discrimValue );
}
}
private boolean isDatabaseGeneratedTimestamp(Type type) {
// currently only the Hibernate-supplied DbTimestampType is supported here
return DbTimestampType.class.isAssignableFrom( type.getClass() );
}
private boolean isIntegral(Type type) {
return Long.class.isAssignableFrom( type.getReturnedClass() )
|| Integer.class.isAssignableFrom( type.getReturnedClass() )
|| long.class.isAssignableFrom( type.getReturnedClass() )
|| int.class.isAssignableFrom( type.getReturnedClass() );
}
private void useSelectClause(AST select) throws SemanticException {
selectClause = (SelectClause) select;
selectClause.initializeExplicitSelectClause( currentFromClause );
}
private void createSelectClauseFromFromClause(QueryNode qn) throws SemanticException {
AST select = astFactory.create( SELECT_CLAUSE, "{derived select clause}" );
AST sibling = qn.getFromClause();
qn.setFirstChild( select );
select.setNextSibling( sibling );
selectClause = (SelectClause) select;
selectClause.initializeDerivedSelectClause( currentFromClause );
LOG.debug( "Derived SELECT clause created." );
}
@Override
protected void resolve(AST node) throws SemanticException {
if ( node != null ) {
// This is called when it's time to fully resolve a path expression.
ResolvableNode r = (ResolvableNode) node;
if ( isInFunctionCall() ) {
r.resolveInFunctionCall( false, true );
}
else {
r.resolve( false, true ); // Generate implicit joins, only if necessary.
}
}
}
@Override
protected void resolveSelectExpression(AST node) throws SemanticException {
// This is called when it's time to fully resolve a path expression.
int type = node.getType();
switch ( type ) {
case DOT: {
DotNode dot = (DotNode) node;
dot.resolveSelectExpression();
break;
}
case ALIAS_REF: {
// Notify the FROM element that it is being referenced by the select.
FromReferenceNode aliasRefNode = (FromReferenceNode) node;
//aliasRefNode.resolve( false, false, aliasRefNode.getText() ); //TODO: is it kosher to do it here?
aliasRefNode.resolve( false, false ); //TODO: is it kosher to do it here?
FromElement fromElement = aliasRefNode.getFromElement();
if ( fromElement != null ) {
fromElement.setIncludeSubclasses( true );
}
break;
}
default: {
break;
}
}
}
@Override
protected void beforeSelectClause() throws SemanticException {
// Turn off includeSubclasses on all FromElements.
FromClause from = getCurrentFromClause();
List fromElements = from.getFromElements();
for ( Iterator iterator = fromElements.iterator(); iterator.hasNext(); ) {
FromElement fromElement = (FromElement) iterator.next();
fromElement.setIncludeSubclasses( false );
}
}
@Override
protected AST generatePositionalParameter(AST inputNode) throws SemanticException {
if ( namedParameters.size() > 0 ) {
throw new SemanticException(
"cannot define positional parameter after any named parameters have been defined"
);
}
LOG.warnf(
"[DEPRECATION] Encountered positional parameter near line %s, column %s. Positional parameter " +
"are considered deprecated; use named parameters or JPA-style positional parameters instead.",
inputNode.getLine(),
inputNode.getColumn()
);
ParameterNode parameter = (ParameterNode) astFactory.create( PARAM, "?" );
PositionalParameterSpecification paramSpec = new PositionalParameterSpecification(
inputNode.getLine(),
inputNode.getColumn(),
positionalParameterCount++
);
parameter.setHqlParameterSpecification( paramSpec );
parameters.add( paramSpec );
return parameter;
}
@Override
protected AST generateNamedParameter(AST delimiterNode, AST nameNode) throws SemanticException {
String name = nameNode.getText();
trackNamedParameterPositions( name );
// create the node initially with the param name so that it shows
// appropriately in the "original text" attribute
ParameterNode parameter = (ParameterNode) astFactory.create( NAMED_PARAM, name );
parameter.setText( "?" );
NamedParameterSpecification paramSpec = new NamedParameterSpecification(
delimiterNode.getLine(),
delimiterNode.getColumn(),
name
);
parameter.setHqlParameterSpecification( paramSpec );
parameters.add( paramSpec );
return parameter;
}
private void trackNamedParameterPositions(String name) {
Integer loc = parameterCount++;
Object o = namedParameters.get( name );
if ( o == null ) {
namedParameters.put( name, loc );
}
else if ( o instanceof Integer ) {
ArrayList list = new ArrayList( 4 );
list.add( o );
list.add( loc );
namedParameters.put( name, list );
}
else {
( (ArrayList) o ).add( loc );
}
}
@Override
protected void processConstant(AST constant) throws SemanticException {
literalProcessor.processConstant(
constant,
true
); // Use the delegate, resolve identifiers as FROM element aliases.
}
@Override
protected void processBoolean(AST constant) throws SemanticException {
literalProcessor.processBoolean( constant ); // Use the delegate.
}
@Override
protected void processNumericLiteral(AST literal) {
literalProcessor.processNumeric( literal );
}
@Override
protected void processIndex(AST indexOp) throws SemanticException {
IndexNode indexNode = (IndexNode) indexOp;
indexNode.resolve( true, true );
}
@Override
protected void processFunction(AST functionCall, boolean inSelect) throws SemanticException {
MethodNode methodNode = (MethodNode) functionCall;
methodNode.resolve( inSelect );
}
@Override
protected void processAggregation(AST node, boolean inSelect) throws SemanticException {
AggregateNode aggregateNode = (AggregateNode) node;
aggregateNode.resolve();
}
@Override
protected void processConstructor(AST constructor) throws SemanticException {
ConstructorNode constructorNode = (ConstructorNode) constructor;
constructorNode.prepare();
}
@Override
protected void setAlias(AST selectExpr, AST ident) {
( (SelectExpression) selectExpr ).setAlias( ident.getText() );
// only put the alias (i.e., result variable) in selectExpressionsByResultVariable
// if is not defined in a subquery.
if ( !isSubQuery() ) {
selectExpressionsByResultVariable.put( ident.getText(), (SelectExpression) selectExpr );
}
}
@Override
protected boolean isOrderExpressionResultVariableRef(AST orderExpressionNode) throws SemanticException {
// ORDER BY is not supported in a subquery
// TODO: should an exception be thrown if an ORDER BY is in a subquery?
if ( !isSubQuery() &&
orderExpressionNode.getType() == IDENT &&
selectExpressionsByResultVariable.containsKey( orderExpressionNode.getText() ) ) {
return true;
}
return false;
}
@Override
protected void handleResultVariableRef(AST resultVariableRef) throws SemanticException {
if ( isSubQuery() ) {
throw new SemanticException(
"References to result variables in subqueries are not supported."
);
}
( (ResultVariableRefNode) resultVariableRef ).setSelectExpression(
selectExpressionsByResultVariable.get( resultVariableRef.getText() )
);
}
/**
* Returns the locations of all occurrences of the named parameter.
*/
public int[] getNamedParameterLocations(String name) throws QueryException {
Object o = namedParameters.get( name );
if ( o == null ) {
throw new QueryException(
QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name,
queryTranslatorImpl.getQueryString()
);
}
if ( o instanceof Integer ) {
return new int[] {(Integer) o};
}
else {
return ArrayHelper.toIntArray( (ArrayList) o );
}
}
public void addQuerySpaces(Serializable[] spaces) {
querySpaces.addAll( Arrays.asList( spaces ) );
}
public Type[] getReturnTypes() {
return selectClause.getQueryReturnTypes();
}
public String[] getReturnAliases() {
return selectClause.getQueryReturnAliases();
}
public SelectClause getSelectClause() {
return selectClause;
}
public FromClause getFinalFromClause() {
FromClause top = currentFromClause;
while ( top.getParentFromClause() != null ) {
top = top.getParentFromClause();
}
return top;
}
public boolean isShallowQuery() {
// select clauses for insert statements should alwasy be treated as shallow
return getStatementType() == INSERT || queryTranslatorImpl.isShallowQuery();
}
public Map getEnabledFilters() {
return queryTranslatorImpl.getEnabledFilters();
}
public LiteralProcessor getLiteralProcessor() {
return literalProcessor;
}
public ASTPrinter getASTPrinter() {
return printer;
}
public ArrayList<ParameterSpecification> getParameters() {
return parameters;
}
public int getNumberOfParametersInSetClause() {
return numberOfParametersInSetClause;
}
@Override
protected void evaluateAssignment(AST eq) throws SemanticException {
prepareLogicOperator( eq );
Queryable persister = getCurrentFromClause().getFromElement().getQueryable();
evaluateAssignment( eq, persister, -1 );
}
private void evaluateAssignment(AST eq, Queryable persister, int targetIndex) {
if ( persister.isMultiTable() ) {
// no need to even collect this information if the persister is considered multi-table
AssignmentSpecification specification = new AssignmentSpecification( eq, persister );
if ( targetIndex >= 0 ) {
assignmentSpecifications.add( targetIndex, specification );
}
else {
assignmentSpecifications.add( specification );
}
numberOfParametersInSetClause += specification.getParameters().length;
}
}
public ArrayList getAssignmentSpecifications() {
return assignmentSpecifications;
}
@Override
protected AST createIntoClause(String path, AST propertySpec) throws SemanticException {
Queryable persister = (Queryable) getSessionFactoryHelper().requireClassPersister( path );
IntoClause intoClause = (IntoClause) getASTFactory().create( INTO, persister.getEntityName() );
intoClause.setFirstChild( propertySpec );
intoClause.initialize( persister );
addQuerySpaces( persister.getQuerySpaces() );
return intoClause;
}
@Override
protected void prepareVersioned(AST updateNode, AST versioned) throws SemanticException {
UpdateStatement updateStatement = (UpdateStatement) updateNode;
FromClause fromClause = updateStatement.getFromClause();
if ( versioned != null ) {
// Make sure that the persister is versioned
Queryable persister = fromClause.getFromElement().getQueryable();
if ( !persister.isVersioned() ) {
throw new SemanticException( "increment option specified for update of non-versioned entity" );
}
VersionType versionType = persister.getVersionType();
if ( versionType instanceof UserVersionType ) {
throw new SemanticException( "user-defined version types not supported for increment option" );
}
AST eq = getASTFactory().create( HqlSqlTokenTypes.EQ, "=" );
AST versionPropertyNode = generateVersionPropertyNode( persister );
eq.setFirstChild( versionPropertyNode );
AST versionIncrementNode = null;
if ( isTimestampBasedVersion( versionType ) ) {
versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
( (ParameterNode) versionIncrementNode ).setHqlParameterSpecification( paramSpec );
parameters.add( 0, paramSpec );
}
else {
// Not possible to simply re-use the versionPropertyNode here as it causes
// OOM errors due to circularity :(
versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PLUS, "+" );
versionIncrementNode.setFirstChild( generateVersionPropertyNode( persister ) );
versionIncrementNode.addChild( getASTFactory().create( HqlSqlTokenTypes.IDENT, "1" ) );
}
eq.addChild( versionIncrementNode );
evaluateAssignment( eq, persister, 0 );
AST setClause = updateStatement.getSetClause();
AST currentFirstSetElement = setClause.getFirstChild();
setClause.setFirstChild( eq );
eq.setNextSibling( currentFirstSetElement );
}
}
private boolean isTimestampBasedVersion(VersionType versionType) {
final Class javaType = versionType.getReturnedClass();
return Date.class.isAssignableFrom( javaType )
|| Calendar.class.isAssignableFrom( javaType );
}
private AST generateVersionPropertyNode(Queryable persister) throws SemanticException {
String versionPropertyName = persister.getPropertyNames()[persister.getVersionProperty()];
AST versionPropertyRef = getASTFactory().create( HqlSqlTokenTypes.IDENT, versionPropertyName );
AST versionPropertyNode = lookupNonQualifiedProperty( versionPropertyRef );
resolve( versionPropertyNode );
return versionPropertyNode;
}
@Override
protected void prepareLogicOperator(AST operator) throws SemanticException {
( (OperatorNode) operator ).initialize();
}
@Override
protected void prepareArithmeticOperator(AST operator) throws SemanticException {
( (OperatorNode) operator ).initialize();
}
@Override
protected void validateMapPropertyExpression(AST node) throws SemanticException {
try {
FromReferenceNode fromReferenceNode = (FromReferenceNode) node;
QueryableCollection collectionPersister = fromReferenceNode.getFromElement().getQueryableCollection();
if ( !Map.class.isAssignableFrom( collectionPersister.getCollectionType().getReturnedClass() ) ) {
throw new SemanticException( "node did not reference a map" );
}
}
catch (SemanticException se) {
throw se;
}
catch (Throwable t) {
throw new SemanticException( "node did not reference a map" );
}
}
public Set<String> getTreatAsDeclarationsByPath(String path) {
return hqlParser.getTreatMap().get( path );
}
public static void panic() {
throw new QueryException( "TreeWalker: panic" );
}
}
| lgpl-2.1 |
wctaiwan/joeq | Clazz/jq_StaticMethod.java | 2933 | // jq_StaticMethod.java, created Mon Feb 5 23:23:20 2001 by joewhaley
// Copyright (C) 2001-3 John Whaley <jwhaley@alum.mit.edu>
// Licensed under the terms of the GNU LGPL; see COPYING for details.
package Clazz;
//friend jq_ClassLoader;
import Bootstrap.PrimordialClassLoader;
import Main.jq;
import UTF.Utf8;
import Util.Assert;
/*
* @author John Whaley <jwhaley@alum.mit.edu>
* @version $Id: jq_StaticMethod.java,v 1.18 2003/05/12 10:05:13 joewhaley Exp $
*/
public class jq_StaticMethod extends jq_Method {
// clazz, name, desc, access_flags are inherited
protected jq_StaticMethod(jq_Class clazz, jq_NameAndDesc nd) {
super(clazz, nd);
}
// ONLY TO BE CALLED BY jq_ClassLoader!!!
static jq_StaticMethod newStaticMethod(jq_Class clazz, jq_NameAndDesc nd) {
return new jq_StaticMethod(clazz, nd);
}
protected void parseMethodSignature() {
Utf8.MethodDescriptorIterator i = nd.getDesc().getParamDescriptors();
// count them up
int num = 0, words = 0;
while (i.hasNext()) { i.nextUtf8(); ++num; }
// get them for real
param_types = new jq_Type[num];
i = nd.getDesc().getParamDescriptors();
for (int j=0; j<num; ++j) {
Utf8 pd = i.nextUtf8();
param_types[j] = PrimordialClassLoader.getOrCreateType(clazz.getClassLoader(), pd);
++words;
if ((param_types[j] == jq_Primitive.LONG) ||
(param_types[j] == jq_Primitive.DOUBLE)) ++words;
}
param_words = words;
Utf8 rd = i.getReturnDescriptor();
return_type = PrimordialClassLoader.getOrCreateType(clazz.getClassLoader(), rd);
}
public final boolean needsDynamicLink(jq_Method method) {
if (getDeclaringClass().needsDynamicLink(method)) return true;
if (!jq.RunningNative) return false;
return (state < STATE_SFINITIALIZED);
}
public final boolean isStatic() { return true; }
public boolean isClassInitializer() { return false; }
public final jq_Member resolve() { return resolve1(); }
public jq_StaticMethod resolve1() {
this.clazz.load();
if (this.state >= STATE_LOADED) return this;
// this reference may be to a superclass or superinterface.
jq_StaticMethod m = this.clazz.getStaticMethod(nd);
if (m != null) return m;
throw new NoSuchMethodError(this.toString());
}
public final void prepare() { Assert._assert(state == STATE_LOADED); state = STATE_PREPARED; }
public final void unprepare() { Assert._assert(state == STATE_PREPARED); state = STATE_LOADED; }
public void accept(jq_MethodVisitor mv) {
mv.visitStaticMethod(this);
super.accept(mv);
}
public static final jq_Class _class;
static {
_class = (jq_Class)PrimordialClassLoader.loader.getOrCreateBSType("LClazz/jq_StaticMethod;");
}
}
| lgpl-2.1 |
animesh-kumar/codechef | November2014CodeChallenge/src/Fombinatorial.java | 1399 | import java.util.Scanner;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Fombinatorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
OutputStreamWriter outputStream = new OutputStreamWriter(System.out);
PrintWriter pw = new PrintWriter(outputStream);
long t = in.nextLong(); // Number of test cases
// loop over all test cases
for (long i = 0; i < t; i++) {
long n = in.nextLong(); // N value
long m = in.nextLong(); // Modulo value
long q = in.nextLong(); // Q is number of r values that have to come
// Read all the r values
for (long j = 0; j < q; j++) {
long r = in.nextLong();
// Calculate the difference between n and r
long diff = n - r;
// Formula F(n) / F(r) * F(N-r)
long divisor1 = 1;// Use them to reduce the calculations
long divisor2 = 1;
long product = 1;
for (long k = 2; k <= n; k++) {
product = product * power(k, k);
if (k == r) {
divisor1 = product;
} else if (k == diff) {
divisor2 = product;
}
}
// Calculate the quotient
long quotient = product / divisor1;
quotient = quotient / divisor2;
long result = quotient % m;
pw.println(result);
}
}
in.close();
pw.close();
}
static long power(long base, long powr) {
if (powr == 0)
return 1;
return base * power(base, --powr);
}
} | lgpl-2.1 |
99sono/wildfly | testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/eap620/DomainAdjuster620.java | 5962 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat Middleware LLC, 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.test.integration.domain.mixed.eap620;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.operations.common.Util.createRemoveOperation;
import static org.jboss.as.controller.operations.common.Util.getUndefineAttributeOperation;
import static org.jboss.as.controller.operations.common.Util.getWriteAttributeOperation;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.test.integration.domain.mixed.eap630.DomainAdjuster630;
import org.jboss.dmr.ModelNode;
/**
* Does adjustments to the domain model for 6.2.0 legacy slaves
*
* @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a>
*/
public class DomainAdjuster620 extends DomainAdjuster630 {
@Override
protected List<ModelNode> adjustForVersion(final DomainClient client, PathAddress profileAddress, boolean withMasterServers) throws Exception {
List<ModelNode> list = super.adjustForVersion(client, profileAddress, withMasterServers);
list.addAll(adjustLogging(profileAddress.append(SUBSYSTEM, "logging")));
list.add(getWriteAttributeOperation(profileAddress.append(SUBSYSTEM, "datasources").append("data-source","ExampleDS"), "statistics-enabled", new ModelNode("true")));
return list;
}
private List<ModelNode> adjustLogging(PathAddress subsystem) throws Exception {
List<ModelNode> list = new ArrayList<>();
//Named formatters don't exist
list.add(getUndefineAttributeOperation(subsystem.append("console-handler", "CONSOLE"), "named-formatter"));
list.add(getWriteAttributeOperation(subsystem.append("console-handler", "CONSOLE"), "formatter",
new ModelNode("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n")));
list.add(getUndefineAttributeOperation(subsystem.append("periodic-rotating-file-handler", "FILE"), "named-formatter"));
list.add(getWriteAttributeOperation(subsystem.append("periodic-rotating-file-handler", "FILE"), "formatter", new ModelNode("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n")));
list.add(createRemoveOperation(subsystem.append("pattern-formatter", "PATTERN")));
list.add(createRemoveOperation(subsystem.append("pattern-formatter", "COLOR-PATTERN")));
return list;
}
@Override
public void adjustInfinispanStatisticsEnabled(final List<ModelNode> list, final PathAddress subsystem, boolean isFullHa) {
//Statistics need to be enabled for all cache containers and caches
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "server")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "web")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "ejb")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "hibernate")));
if (isFullHa) {
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "server").append("replicated-cache", "default")));
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "web").append("distributed-cache", "dist")));
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "ejb").append("distributed-cache", "dist")));
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "hibernate").append("invalidation-cache", "entity")));
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "hibernate").append("local-cache", "local-query")));
list.add(setStatisticsEnabledTrue(
subsystem.append("cache-container", "hibernate").append("replicated-cache", "timestamps")));
} else {
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "server").append("local-cache", "default")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "web").append("local-cache", "passivation")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "ejb").append("local-cache", "passivation")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "hibernate").append("local-cache", "entity")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "hibernate").append("local-cache", "local-query")));
list.add(setStatisticsEnabledTrue(subsystem.append("cache-container", "hibernate").append("local-cache", "timestamps")));
}
}
private ModelNode setStatisticsEnabledTrue(final PathAddress addr) {
return getWriteAttributeOperation(addr, "statistics-enabled", true);
}
} | lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsk/itemk150.java | 159 | package fr.toss.FF7itemsk;
public class itemk150 extends FF7itemskbase {
public itemk150(int id) {
super(id);
setUnlocalizedName("itemk150");
}
}
| lgpl-2.1 |
CheeseL0ver/Ore-TTM | build/tmp/recompSrc/cpw/mods/fml/relauncher/ModListHelper.java | 4953 | package cpw.mods.fml.relauncher;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.Level;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class ModListHelper {
public static class JsonModList {
public String repositoryRoot;
public List<String> modRef;
public String parentList;
}
private static File mcDirectory;
private static Set<File> visitedFiles = Sets.newHashSet();
public static final Map<String,File> additionalMods = Maps.newLinkedHashMap();
static void parseModList(File minecraftDirectory)
{
FMLRelaunchLog.fine("Attempting to load commandline specified mods, relative to %s", minecraftDirectory.getAbsolutePath());
mcDirectory = minecraftDirectory;
@SuppressWarnings("unchecked")
Map<String,String> args = (Map<String, String>) Launch.blackboard.get("launchArgs");
String listFile = args.get("--modListFile");
if (listFile != null)
{
parseListFile(listFile);
}
String extraMods = args.get("--mods");
if (extraMods != null)
{
String[] split = extraMods.split(",");
for (String modFile : split)
{
tryAddFile(modFile, null, modFile);
}
}
}
private static void parseListFile(String listFile) {
File f;
try
{
f = new File(mcDirectory, listFile).getCanonicalFile();
} catch (IOException e2)
{
FMLRelaunchLog.log(Level.INFO, e2, "Unable to canonicalize path %s relative to %s", listFile, mcDirectory.getAbsolutePath());
return;
}
if (!f.exists())
{
FMLRelaunchLog.info("Failed to find modList file %s", f.getAbsolutePath());
return;
}
if (visitedFiles.contains(f))
{
FMLRelaunchLog.severe("There appears to be a loop in the modListFile hierarchy. You shouldn't do this!");
throw new RuntimeException("Loop detected, impossible to load modlistfile");
}
String json;
try {
json = Files.asCharSource(f, Charsets.UTF_8).read();
} catch (IOException e1) {
FMLRelaunchLog.log(Level.INFO, e1, "Failed to read modList json file %s.", listFile);
return;
}
Gson gsonParser = new Gson();
JsonModList modList;
try {
modList = gsonParser.fromJson(json, JsonModList.class);
} catch (JsonSyntaxException e) {
FMLRelaunchLog.log(Level.INFO, e, "Failed to parse modList json file %s.", listFile);
return;
}
visitedFiles.add(f);
// We visit parents before children, so the additionalMods list is sorted from parent to child
if (modList.parentList != null)
{
parseListFile(modList.parentList);
}
File repoRoot = new File(modList.repositoryRoot);
if (!repoRoot.exists())
{
FMLRelaunchLog.info("Failed to find the specified repository root %s", modList.repositoryRoot);
return;
}
for (String s : modList.modRef)
{
StringBuilder fileName = new StringBuilder();
StringBuilder genericName = new StringBuilder();
String[] parts = s.split(":");
fileName.append(parts[0].replace('.', File.separatorChar));
genericName.append(parts[0]);
fileName.append(File.separatorChar);
fileName.append(parts[1]).append(File.separatorChar);
genericName.append(":").append(parts[1]);
fileName.append(parts[2]).append(File.separatorChar);
fileName.append(parts[1]).append('-').append(parts[2]);
if (parts.length == 4)
{
fileName.append('-').append(parts[3]);
genericName.append(":").append(parts[3]);
}
fileName.append(".jar");
tryAddFile(fileName.toString(), repoRoot, genericName.toString());
}
}
private static void tryAddFile(String modFileName, File repoRoot, String descriptor) {
File modFile = repoRoot != null ? new File(repoRoot,modFileName) : new File(mcDirectory, modFileName);
if (!modFile.exists())
{
FMLRelaunchLog.info("Failed to find mod file %s (%s)", descriptor, modFile.getAbsolutePath());
}
else
{
FMLRelaunchLog.fine("Adding %s (%s) to the mod list", descriptor, modFile.getAbsolutePath());
additionalMods.put(descriptor, modFile);
}
}
} | lgpl-2.1 |
aldocuevas/test | pos/source_code/src/com/boutique/view/FrmBusquedaProducto.java | 936 | package com.boutique.view;
import javax.swing.*;
/**
* <p>Title: boutique management</p>
*
* <p>Description: Sistema de administracion de boitiques</p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: SESTO</p>
*
* @author Aldo Antonio Cuevas Alvarez
* @version 1.0
*/
public class FrmBusquedaProducto
extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
// BorderLayout borderLayout1 = new BorderLayout();
PnlProductos pnlProductos1 = new PnlProductos();
public FrmBusquedaProducto() {
try {
jbInit();
}
catch (Exception exception) {
exception.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setTitle("Busqueda de productos");
this.getContentPane().add(pnlProductos1, java.awt.BorderLayout.CENTER);
this.pack();
}
}
| lgpl-2.1 |
TheAwesomeGem/MineFantasy | src/main/java/minefantasy/block/tileentity/TileEntityTanningRack.java | 7646 | package minefantasy.block.tileentity;
import java.util.Random;
import minefantasy.api.IMFCrafter;
import minefantasy.api.leatherwork.EnumToolType;
import minefantasy.api.tanner.LeathercuttingRecipes;
import minefantasy.api.tanner.TanningRecipes;
import minefantasy.system.network.PacketManagerMF;
import minefantasy.system.network.PacketUserMF;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.packet.Packet;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import com.google.common.io.ByteArrayDataInput;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
*
* @author Anonymous Productions
*
* Sources are provided for educational reasons.
* though small bits of code, or methods can be used in your own creations.
*/
public class TileEntityTanningRack extends TileEntity implements PacketUserMF, IMFCrafter, IInventory{
private int ticksExisted;
public int direction;
public float progress;
private ItemStack hungItem;
Random rand = new Random();
public TileEntityTanningRack() {
}
public boolean canTan()
{
return TanningRecipes.instance().getTanningResult(getHung()) != null;
}
public boolean canCut()
{
return LeathercuttingRecipes.instance().getCuttingResult(getHung()) != null;
}
public void setHung(ItemStack item)
{
hungItem = item;
}
public boolean use(EntityPlayer player, EnumToolType toolType, float quality)
{
if (canTan() && toolType == EnumToolType.KNIFE)
{
worldObj.playSoundEffect(xCoord+0.5, yCoord+0.5, zCoord+0.5, "step.cloth", 1.0F, 1.0F);
progress += quality;
if(progress >= getMaxProgress())
{
progress = 0.0F;
if(!worldObj.isRemote)
{
setHung(TanningRecipes.instance().getTanningResult(getHung()));
syncItem();
}
if(player.getHeldItem() != null)
{
player.getHeldItem().damageItem(1, player);
}
return true;
}
}
if (canCut() && toolType == EnumToolType.CUTTER)
{
worldObj.playSoundEffect(xCoord+0.5, yCoord+0.5, zCoord+0.5, "mob.sheep.shear", 0.5F, 0.65F);
progress += quality;
if(progress >= getMaxProgress())
{
progress = 0.0F;
if(!worldObj.isRemote)
{
int rs;
ItemStack result = LeathercuttingRecipes.instance().getCuttingResult(getHung()).copy();
rs = result.stackSize * hungItem.stackSize;
setHung(result);
hungItem.stackSize = rs;
this.retrieveItem(player);
syncItem();
}
if(player.getHeldItem() != null)
{
player.getHeldItem().damageItem(1, player);
}
return true;
}
}
return false;
}
private float getMaxProgress()
{
return 50F;
}
@Override
public void updateEntity()
{
super.updateEntity();
ticksExisted ++;
sendPacketToClients();
if(ticksExisted % 20 == 0)
{
syncItem();
}
if(!canCraft())
{
progress = 0.0F;
}
}
public boolean canHang()
{
return getHung() == null;
}
public void hang(ItemStack item)
{
setHung(item);
Random rand = new Random();
worldObj.playSoundEffect(xCoord, yCoord, zCoord, "mob.horse.leather", rand .nextFloat() + 1.5F, (rand.nextFloat()*0.4F) + 0.8F);
syncItem();
}
public ItemStack getHung()
{
return hungItem;
}
/**
* Writes a tile entity to NBT.
*/
public void writeToNBT(NBTTagCompound tag)
{
super.writeToNBT(tag);
if(getHung() != null)
{
NBTTagCompound slot = new NBTTagCompound();
this.hungItem.writeToNBT(slot);
tag.setTag("Hung", slot);
}
tag.setInteger("Dir", direction);
tag.setFloat("Progress", progress);
}
public void readFromNBT(NBTTagCompound tag)
{
super.readFromNBT(tag);
if(tag.hasKey("Hung"))
{
hungItem = ItemStack.loadItemStackFromNBT((NBTTagCompound) tag.getTag("Hung"));
}
direction = tag.getInteger("Dir");
progress = tag.getFloat("Progress");
}
private void sendPacketToClients() {
if(!worldObj.isRemote)
{
try
{
Packet packet = PacketManagerMF.getPacketIntegerArray(this, new int[]{direction, (int)progress*100});
FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendPacketToAllPlayers(packet);
} catch(NullPointerException e)
{
System.out.println("MineFantasy: Lost Client connection");
}
}
}
@Override
public void recievePacket(ByteArrayDataInput data)
{
direction = data.readInt();
int p = data.readInt();
progress = (float)p / 100F;
}
public boolean canHang(ItemStack itemstack)
{
return TanningRecipes.instance().getTanningResult(itemstack)!= null ||
LeathercuttingRecipes.instance().getCuttingResult(itemstack)!= null;
}
public void syncItem()
{
if(!worldObj.isRemote)
{
Packet packet = PacketManagerMF.getPacketItemStackArray(this, 0, getHung());
try
{
FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendPacketToAllPlayers(packet);
} catch(NullPointerException e)
{
System.out.println("MineFantasy: Client connection lost");
return;
}
}
}
@Override
public int getSizeInventory() {
return 1;
}
@Override
public ItemStack getStackInSlot(int i) {
return getHung();
}
@Override
public ItemStack decrStackSize(int i, int j) {
getHung().stackSize --;
if(getHung().stackSize <= 0)
{
setHung(null);
}
return getHung();
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return null;
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack)
{
setHung(itemstack);
}
@Override
public String getInvName()
{
return null;
}
@Override
public boolean isInvNameLocalized()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
return false;
}
@Override
public void openChest() {}
@Override
public void closeChest() {}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack)
{
return false;
}
public void retrieveItem(EntityPlayer player)
{
if(player.worldObj.isRemote)
{
return;
}
double x = player.posX;
double y = player.posY;
double z = player.posZ;
EntityItem drop = new EntityItem(worldObj, x+0.5D, y+0.5D, z+0.5D, getHung().copy());
worldObj.spawnEntityInWorld(drop);
hang(null);
}
private boolean canCraft()
{
return canTan() || canCut();
}
@Override
@SideOnly(Side.CLIENT)
public boolean shouldRenderCraftMetre()
{
return canCraft();
}
@Override
@SideOnly(Side.CLIENT)
public int getProgressBar(int i)
{
return (int)((float)i / 50F * progress);
}
@Override
public String getResultName()
{
return "";
}
@Override
@SideOnly(Side.CLIENT)
public void setTempResult(ItemStack item)
{
}
} | lgpl-2.1 |
johann-petrak/gateplugin-Evaluation | src/main/java/gate/plugin/evaluation/api/NilTreatment.java | 993 | /*
* Copyright (c) 2015-2018 University of Sheffield.
*
* This file is part of gateplugin-Evaluation
* (see https://github.com/GateNLP/gateplugin-Evaluation).
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package gate.plugin.evaluation.api;
/**
*
* @author Johann Petrak
*/
public enum NilTreatment {
NO_NILS, NIL_IS_ABSENT
//, NIL_CLUSTERS
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/toolkits/scalar/LocalPacker.java | 6842 | package soot.toolkits.scalar;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* 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 java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.IdentityUnit;
import soot.Local;
import soot.PhaseOptions;
import soot.Singletons;
import soot.Type;
import soot.Unit;
import soot.ValueBox;
import soot.jimple.GroupIntPair;
import soot.options.Options;
import soot.util.DeterministicHashMap;
/**
* A BodyTransformer that attemps to minimize the number of local variables used in Body by 'reusing' them when possible.
* Implemented as a singleton. For example the code:
*
* for(int i; i < k; i++); for(int j; j < k; j++);
*
* would be transformed into: for(int i; i < k; i++); for(int i; i < k; i++);
*
* assuming to further conflicting uses of i and j.
*
* Note: LocalSplitter is corresponds to the inverse transformation.
*
* @see BodyTransformer
* @see Body
* @see LocalSplitter
*/
public class LocalPacker extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LocalPacker.class);
public LocalPacker(Singletons.Global g) {
}
public static LocalPacker v() {
return G.v().soot_toolkits_scalar_LocalPacker();
}
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
boolean isUnsplit = PhaseOptions.getBoolean(options, "unsplit-original-locals");
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Packing locals...");
}
Map<Local, Object> localToGroup = new DeterministicHashMap<Local, Object>(body.getLocalCount() * 2 + 1, 0.7f);
// A group represents a bunch of locals which may potentially interfere
// with each other
// 2 separate groups can not possibly interfere with each other
// (coloring say ints and doubles)
Map<Object, Integer> groupToColorCount = new HashMap<Object, Integer>(body.getLocalCount() * 2 + 1, 0.7f);
Map<Local, Integer> localToColor = new HashMap<Local, Integer>(body.getLocalCount() * 2 + 1, 0.7f);
Map<Local, Local> localToNewLocal;
// Assign each local to a group, and set that group's color count to 0.
{
for (Local l : body.getLocals()) {
Type g = l.getType();
localToGroup.put(l, g);
if (!groupToColorCount.containsKey(g)) {
groupToColorCount.put(g, 0);
}
}
}
// Assign colors to the parameter locals.
{
for (Unit s : body.getUnits()) {
if (s instanceof IdentityUnit && ((IdentityUnit) s).getLeftOp() instanceof Local) {
Local l = (Local) ((IdentityUnit) s).getLeftOp();
Object group = localToGroup.get(l);
int count = groupToColorCount.get(group).intValue();
localToColor.put(l, new Integer(count));
count++;
groupToColorCount.put(group, new Integer(count));
}
}
}
// Call the graph colorer.
if (isUnsplit) {
FastColorer.unsplitAssignColorsToLocals(body, localToGroup, localToColor, groupToColorCount);
} else {
FastColorer.assignColorsToLocals(body, localToGroup, localToColor, groupToColorCount);
}
// Map each local to a new local.
{
List<Local> originalLocals = new ArrayList<Local>(body.getLocals());
localToNewLocal = new HashMap<Local, Local>(body.getLocalCount() * 2 + 1, 0.7f);
Map<GroupIntPair, Local> groupIntToLocal = new HashMap<GroupIntPair, Local>(body.getLocalCount() * 2 + 1, 0.7f);
body.getLocals().clear();
Set<String> usedLocalNames = new HashSet<>();
for (Local original : originalLocals) {
Object group = localToGroup.get(original);
int color = localToColor.get(original).intValue();
GroupIntPair pair = new GroupIntPair(group, color);
Local newLocal;
if (groupIntToLocal.containsKey(pair)) {
newLocal = (Local) groupIntToLocal.get(pair);
} else {
newLocal = (Local) original.clone();
newLocal.setType((Type) group);
// Icky fix. But I guess it works. -PL
// It is no substitute for really understanding the
// problem, though. I'll leave that to someone
// who really understands the local naming stuff.
// Does such a person exist?
// I'll just leave this comment as folklore for future
// generations. The problem with it is that you can end up
// with different locals that share the same name which can
// lead to all sorts of funny results. (SA, 2017-03-02)
int signIndex = newLocal.getName().indexOf("#");
if (signIndex != -1)
newLocal.setName(newLocal.getName().substring(0, signIndex));
// If we have a split local, let's find a better name for it
// int signIndex = newLocal.getName().indexOf("#");
// if (signIndex != -1) {
// String newName = newLocal.getName().substring(0, signIndex);
// if (usedLocalNames.add(newName)) {
// newLocal.setName(newName);
// } else {
// // just leave it alone for now
// }
// }
groupIntToLocal.put(pair, newLocal);
body.getLocals().add(newLocal);
}
localToNewLocal.put(original, newLocal);
}
}
// Go through all valueBoxes of this method and perform changes
{
for (Unit s : body.getUnits()) {
for (ValueBox box : s.getUseBoxes()) {
if (box.getValue() instanceof Local) {
Local l = (Local) box.getValue();
box.setValue((Local) localToNewLocal.get(l));
}
}
for (ValueBox box : s.getDefBoxes()) {
if (box.getValue() instanceof Local) {
Local l = (Local) box.getValue();
box.setValue((Local) localToNewLocal.get(l));
}
}
}
}
}
}
| lgpl-2.1 |
cacheonix/cacheonix-core | src/org/cacheonix/impl/cache/storage/disk/DummyDiskStorage.java | 3866 | /*
* Cacheonix Systems licenses this file to You under the LGPL 2.1
* (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
*
* 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.cacheonix.impl.cache.storage.disk;
/**
* This is a dummy disk storage that does not do anything. It can be see as a storage of maxim size 0 bytes.
*/
public final class DummyDiskStorage implements DiskStorage {
/**
* Storage name
*/
private final String name;
/**
* Constructor.
*
* @param name this storage name.
*/
public DummyDiskStorage(final String name) {
this.name = name;
}
/**
* @param startupInfo - object (container) which could carry Storage specific initialization information
* @return <code>true</code> if <b>Storage</b> successfully initialized and <code>false</code> in case of failure
*/
public boolean initialize(final Object startupInfo) {
return true;
}
/**
* <b>shutdown</b> - closing and cleaning (when indicated by deleteStorageContents) Storage resource
*
* @param deleteStorageContents - boolean which indicates if storage should be erased after shutdown (true) or
* persistent (false)
*/
public void shutdown(final boolean deleteStorageContents) {
}
/**
* <b>put</b> puts cache object with key and value into Storage.
*
* @param key - serializable object for key
* @param value - serializable object for value
* @return always null
*/
public StoredObject put(final Object key, final Object value) {
return null;
}
/**
* <b>get</b> gets value object from specific storage. Entry in the storage is <u>not remove</u>.
*
* @param key - is specific for system key object. In case of disk storage for example it will be StorageObject which
* will carry long Position for the disk cell
* @return always null
*/
public Object get(final Object key) {
return null;
}
/**
* <b>restore</b> gets value object from specific storage. Entry in the storage is <u>removed</u>.
*
* @param key - is specific for system key object. In case of disk storage for example it will be StorageObject which
* will carry long </u>position</u> for the disk cell
* @return always null
*/
public Object restore(final Object key) {
return null;
}
/**
* <b>remove</b> removes object associated with specific key from the storage
*
* @param key - is specific for system key object. In case of disk storage for example it will be StorageObject which
* will carry long <u>position</u> for the disk cell
* @return always false
*/
public boolean remove(final Object key) {
return false;
}
/**
* <b>getName</b> get name for the Storage
*
* @return <u>String</u> with the Storage name
*/
public String getName() {
return name;
}
/**
* <b>size</b> gets size allocated for Storage
*
* @return <u>long</u> size value
*/
public long size() {
return 0L; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Clears the storage from all objects.
*/
public void clear() {
}
public String toString() {
return "DummyDiskStorage{" +
"name='" + name + '\'' +
'}';
}
}
| lgpl-2.1 |
jensopetersen/exist | test/src/org/exist/security/SecurityManagerRoundtripTest.java | 7416 | package org.exist.security;
import java.util.Arrays;
import org.exist.test.ExistWebServer;
import org.exist.xmldb.UserManagementService;
import org.junit.Rule;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.junit.runners.Parameterized;
import org.exist.security.internal.aider.GroupAider;
import org.exist.security.internal.aider.UserAider;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.xmldb.api.base.XMLDBException;
/**
* Ensures that security manager data, accounts, groups (and associations)
* are correctly persisted across database restarts
*
* @author Adam Retter <adam@existsolutions.com.com>
*/
@RunWith (Parameterized.class)
public class SecurityManagerRoundtripTest {
@Rule
public final ExistWebServer existWebServer = new ExistWebServer(true, true);
private static final String PORT_PLACEHOLDER = "${PORT}";
@Parameters(name = "{0}")
public static java.util.Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "local", "xmldb:exist://" },
{ "remote", "xmldb:exist://localhost:" + PORT_PLACEHOLDER + "/xmlrpc" }
});
}
@Parameter
public String apiName;
@Parameter(value = 1)
public String baseUri;
private final String getBaseUri() {
return baseUri.replace(PORT_PLACEHOLDER, Integer.toString(existWebServer.getPort()));
}
@Test
public void checkGroupMembership() throws XMLDBException, PermissionDeniedException {
Collection root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
UserManagementService ums = (UserManagementService)root.getService("UserManagementService", "1.0");
final String group1Name = "testGroup1";
final String group2Name = "testGroup2";
final String userName = "testUser";
Group group1 = new GroupAider(group1Name);
Group group2 = new GroupAider(group2Name);
Account user = new UserAider(userName, group1);
try {
ums.addGroup(group1);
ums.addGroup(group2);
ums.addAccount(user);
ums.getAccount(userName);
user.addGroup(group2);
ums.updateAccount(user);
/*** RESTART THE SERVER ***/
existWebServer.restart();
/**************************/
root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
ums = (UserManagementService)root.getService("UserManagementService", "1.0");
user = ums.getAccount(userName);
assertNotNull(user);
Group defaultGroup = user.getDefaultGroup();
assertNotNull(defaultGroup);
assertEquals(group1Name, defaultGroup.getName());
String groups[] = user.getGroups();
assertNotNull(groups);
assertEquals(2, groups.length);
assertEquals(group1Name, groups[0]);
assertEquals(group2Name, groups[1]);
} finally {
//cleanup
try { ums.removeGroup(group1); } catch(Exception e) {}
try { ums.removeGroup(group2); } catch(Exception e) {}
try { ums.removeAccount(user); } catch(Exception e) {}
}
}
@Test
public void checkPrimaryGroupRemainsDBA() throws XMLDBException, PermissionDeniedException {
Collection root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
UserManagementService ums = (UserManagementService)root.getService("UserManagementService", "1.0");
final String group1Name = "testGroup1";
final String group2Name = "testGroup2";
final String userName = "testUser";
Group group1 = new GroupAider(group1Name);
Group group2 = new GroupAider(group2Name);
Account user = new UserAider(userName, ums.getGroup(SecurityManager.DBA_GROUP)); //set users primary group as DBA
try {
ums.addGroup(group1);
ums.addGroup(group2);
ums.addAccount(user);
ums.getAccount(userName);
user.addGroup(group1);
user.addGroup(group2);
ums.updateAccount(user);
/*** RESTART THE SERVER ***/
existWebServer.restart();
/**************************/
root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
ums = (UserManagementService)root.getService("UserManagementService", "1.0");
user = ums.getAccount(userName);
assertNotNull(user);
Group defaultGroup = user.getDefaultGroup();
assertNotNull(defaultGroup);
assertEquals(SecurityManager.DBA_GROUP, defaultGroup.getName());
String groups[] = user.getGroups();
assertNotNull(groups);
assertEquals(3, groups.length);
assertEquals(SecurityManager.DBA_GROUP, groups[0]);
assertEquals(group1Name, groups[1]);
assertEquals(group2Name, groups[2]);
} finally {
//cleanup
try { ums.removeGroup(group1); } catch(Exception e) {}
try { ums.removeGroup(group2); } catch(Exception e) {}
try { ums.removeAccount(user); } catch(Exception e) {}
}
}
@Test
public void checkPrimaryGroupStability() throws XMLDBException, PermissionDeniedException {
Collection root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
UserManagementService ums = (UserManagementService)root.getService("UserManagementService", "1.0");
final String group1Name = "testGroupA";
final String group2Name = "testGroupB";
final String userName = "testUserA";
Group group1 = new GroupAider(group1Name);
Group group2 = new GroupAider(group2Name);
Account user = new UserAider(userName, group1); //set users primary group as group1
try {
ums.addGroup(group1);
ums.addGroup(group2);
ums.addAccount(user);
ums.getAccount(userName);
user.addGroup(group2Name);
ums.updateAccount(user);
/*** RESTART THE SERVER ***/
existWebServer.restart();
/**************************/
root = DatabaseManager.getCollection(getBaseUri() + "/db", "admin", "");
ums = (UserManagementService)root.getService("UserManagementService", "1.0");
user = ums.getAccount(userName);
assertNotNull(user);
Group defaultGroup = user.getDefaultGroup();
assertNotNull(defaultGroup);
assertEquals(group1Name, defaultGroup.getName());
String groups[] = user.getGroups();
assertNotNull(groups);
assertEquals(2, groups.length);
assertEquals(group1Name, groups[0]);
assertEquals(group2Name, groups[1]);
} finally {
//cleanup
try { ums.removeGroup(group1); } catch(Exception e) {}
try { ums.removeGroup(group2); } catch(Exception e) {}
try { ums.removeAccount(user); } catch(Exception e) {}
}
}
}
| lgpl-2.1 |
emmanuelbernard/hibernate-ogm-old | hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/UrlType.java | 2277 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.ogm.type;
import java.net.MalformedURLException;
import java.net.URL;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.Mapping;
import org.hibernate.ogm.type.descriptor.PassThroughGridTypeDescriptor;
import org.hibernate.ogm.type.descriptor.StringMappedGridTypeDescriptor;
import org.hibernate.type.descriptor.java.UrlTypeDescriptor;
/**
* @author Nicolas Helleringer
*/
public class UrlType extends AbstractGenericBasicType<URL> {
public static final UrlType INSTANCE = new UrlType();
public UrlType() {
super( StringMappedGridTypeDescriptor.INSTANCE, UrlTypeDescriptor.INSTANCE );
}
@Override
public String getName() {
return "url";
}
@Override
protected boolean registerUnderJavaType() {
return false;
}
@Override
public int getColumnSpan(Mapping mapping) throws MappingException {
return 1;
}
@Override
public String toString(URL value) throws HibernateException{
return value.toString();
}
@Override
public URL fromStringValue(String string) throws HibernateException {
try {
return new URL(string);
} catch (MalformedURLException e) {
throw new HibernateException("Unable to rebuild URL from String", e);
}
}
}
| lgpl-2.1 |
falko0000/moduleEProc | ProtocolContracts/ProtocolContracts-api/src/main/java/tj/protocol/contracts/service/persistence/ProtocolContractsPersistence.java | 10437 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* 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.
*/
package tj.protocol.contracts.service.persistence;
import aQute.bnd.annotation.ProviderType;
import com.liferay.portal.kernel.service.persistence.BasePersistence;
import tj.protocol.contracts.exception.NoSuchProtocolContractsException;
import tj.protocol.contracts.model.ProtocolContracts;
/**
* The persistence interface for the protocol contracts service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author Brian Wing Shun Chan
* @see tj.protocol.contracts.service.persistence.impl.ProtocolContractsPersistenceImpl
* @see ProtocolContractsUtil
* @generated
*/
@ProviderType
public interface ProtocolContractsPersistence extends BasePersistence<ProtocolContracts> {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this interface directly. Always use {@link ProtocolContractsUtil} to access the protocol contracts persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface.
*/
/**
* Returns the protocol contracts where izvewenie_id = ? or throws a {@link NoSuchProtocolContractsException} if it could not be found.
*
* @param izvewenie_id the izvewenie_id
* @return the matching protocol contracts
* @throws NoSuchProtocolContractsException if a matching protocol contracts could not be found
*/
public ProtocolContracts findByIzvewenieId(long izvewenie_id)
throws NoSuchProtocolContractsException;
/**
* Returns the protocol contracts where izvewenie_id = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
*
* @param izvewenie_id the izvewenie_id
* @return the matching protocol contracts, or <code>null</code> if a matching protocol contracts could not be found
*/
public ProtocolContracts fetchByIzvewenieId(long izvewenie_id);
/**
* Returns the protocol contracts where izvewenie_id = ? or returns <code>null</code> if it could not be found, optionally using the finder cache.
*
* @param izvewenie_id the izvewenie_id
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the matching protocol contracts, or <code>null</code> if a matching protocol contracts could not be found
*/
public ProtocolContracts fetchByIzvewenieId(long izvewenie_id,
boolean retrieveFromCache);
/**
* Removes the protocol contracts where izvewenie_id = ? from the database.
*
* @param izvewenie_id the izvewenie_id
* @return the protocol contracts that was removed
*/
public ProtocolContracts removeByIzvewenieId(long izvewenie_id)
throws NoSuchProtocolContractsException;
/**
* Returns the number of protocol contractses where izvewenie_id = ?.
*
* @param izvewenie_id the izvewenie_id
* @return the number of matching protocol contractses
*/
public int countByIzvewenieId(long izvewenie_id);
/**
* Caches the protocol contracts in the entity cache if it is enabled.
*
* @param protocolContracts the protocol contracts
*/
public void cacheResult(ProtocolContracts protocolContracts);
/**
* Caches the protocol contractses in the entity cache if it is enabled.
*
* @param protocolContractses the protocol contractses
*/
public void cacheResult(
java.util.List<ProtocolContracts> protocolContractses);
/**
* Creates a new protocol contracts with the primary key. Does not add the protocol contracts to the database.
*
* @param protocol_contracts_id the primary key for the new protocol contracts
* @return the new protocol contracts
*/
public ProtocolContracts create(long protocol_contracts_id);
/**
* Removes the protocol contracts with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param protocol_contracts_id the primary key of the protocol contracts
* @return the protocol contracts that was removed
* @throws NoSuchProtocolContractsException if a protocol contracts with the primary key could not be found
*/
public ProtocolContracts remove(long protocol_contracts_id)
throws NoSuchProtocolContractsException;
public ProtocolContracts updateImpl(ProtocolContracts protocolContracts);
/**
* Returns the protocol contracts with the primary key or throws a {@link NoSuchProtocolContractsException} if it could not be found.
*
* @param protocol_contracts_id the primary key of the protocol contracts
* @return the protocol contracts
* @throws NoSuchProtocolContractsException if a protocol contracts with the primary key could not be found
*/
public ProtocolContracts findByPrimaryKey(long protocol_contracts_id)
throws NoSuchProtocolContractsException;
/**
* Returns the protocol contracts with the primary key or returns <code>null</code> if it could not be found.
*
* @param protocol_contracts_id the primary key of the protocol contracts
* @return the protocol contracts, or <code>null</code> if a protocol contracts with the primary key could not be found
*/
public ProtocolContracts fetchByPrimaryKey(long protocol_contracts_id);
@Override
public java.util.Map<java.io.Serializable, ProtocolContracts> fetchByPrimaryKeys(
java.util.Set<java.io.Serializable> primaryKeys);
/**
* Returns all the protocol contractses.
*
* @return the protocol contractses
*/
public java.util.List<ProtocolContracts> findAll();
/**
* Returns a range of all the protocol contractses.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link ProtocolContractsModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of protocol contractses
* @param end the upper bound of the range of protocol contractses (not inclusive)
* @return the range of protocol contractses
*/
public java.util.List<ProtocolContracts> findAll(int start, int end);
/**
* Returns an ordered range of all the protocol contractses.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link ProtocolContractsModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of protocol contractses
* @param end the upper bound of the range of protocol contractses (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of protocol contractses
*/
public java.util.List<ProtocolContracts> findAll(int start, int end,
com.liferay.portal.kernel.util.OrderByComparator<ProtocolContracts> orderByComparator);
/**
* Returns an ordered range of all the protocol contractses.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link ProtocolContractsModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of protocol contractses
* @param end the upper bound of the range of protocol contractses (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of protocol contractses
*/
public java.util.List<ProtocolContracts> findAll(int start, int end,
com.liferay.portal.kernel.util.OrderByComparator<ProtocolContracts> orderByComparator,
boolean retrieveFromCache);
/**
* Removes all the protocol contractses from the database.
*/
public void removeAll();
/**
* Returns the number of protocol contractses.
*
* @return the number of protocol contractses
*/
public int countAll();
} | lgpl-2.1 |
automenta/jadehell | src/main/java/FIPA/ReceivedObjectHelper.java | 2706 | /*
* File: ./FIPA/RECEIVEDOBJECTHELPER.JAVA
* From: FIPA.IDL
* Date: Mon Sep 04 15:08:50 2000
* By: idltojava Java IDL 1.2 Nov 10 1997 13:52:11
*/
package FIPA;
public class ReceivedObjectHelper {
// It is useless to have instances of this class
private ReceivedObjectHelper() { }
public static void write(org.omg.CORBA.portable.OutputStream out, ReceivedObject that) {
out.write_string(that.by);
out.write_string(that.from);
DateTimeHelper.write(out, that.date);
out.write_string(that.id);
out.write_string(that.via);
}
public static ReceivedObject read(org.omg.CORBA.portable.InputStream in) {
ReceivedObject that = new ReceivedObject();
that.by = in.read_string();
that.from = in.read_string();
that.date = DateTimeHelper.read(in);
that.id = in.read_string();
that.via = in.read_string();
return that;
}
public static ReceivedObject extract(org.omg.CORBA.Any a) {
org.omg.CORBA.portable.InputStream in = a.create_input_stream();
return read(in);
}
public static void insert(org.omg.CORBA.Any a, ReceivedObject that) {
org.omg.CORBA.portable.OutputStream out = a.create_output_stream();
write(out, that);
a.read_value(out.create_input_stream(), type());
}
private static org.omg.CORBA.TypeCode _tc;
synchronized public static org.omg.CORBA.TypeCode type() {
int _memberCount = 5;
org.omg.CORBA.StructMember[] _members = null;
if (_tc == null) {
_members= new org.omg.CORBA.StructMember[5];
_members[0] = new org.omg.CORBA.StructMember(
"by",
org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string),
null);
_members[1] = new org.omg.CORBA.StructMember(
"from",
org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string),
null);
_members[2] = new org.omg.CORBA.StructMember(
"date",
DateTimeHelper.type(),
null);
_members[3] = new org.omg.CORBA.StructMember(
"id",
org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string),
null);
_members[4] = new org.omg.CORBA.StructMember(
"via",
org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_string),
null);
_tc = org.omg.CORBA.ORB.init().create_struct_tc(id(), "ReceivedObject", _members);
}
return _tc;
}
public static String id() {
return "IDL:FIPA/ReceivedObject:1.0";
}
}
| lgpl-2.1 |
dheid/wings3 | wings-demos/demo-wingset/src/main/java/wingset/DynamicLayoutExample.java | 22595 | /*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package wingset;
import org.wings.SBorderLayout;
import org.wings.SBoxLayout;
import org.wings.SComboBox;
import org.wings.SComponent;
import org.wings.SConstants;
import org.wings.SDimension;
import org.wings.SFlowDownLayout;
import org.wings.SFlowLayout;
import org.wings.SGridBagLayout;
import org.wings.SGridLayout;
import org.wings.SLabel;
import org.wings.SLayoutManager;
import org.wings.SPanel;
import org.wings.border.SBorder;
import org.wings.border.SLineBorder;
import java.awt.*;
/**
* A quickhack example to show the capabilities of the dynamic wings layout managers.
*
* @author bschmid
*/
public class DynamicLayoutExample extends WingSetPane {
private final SPanel[] demoPanels = {new BorderLayoutDemoPanel(),
new FlowLayoutDemoPanel(),
new GridBagDemoPanel(),
new GridLayoutDemoPanel(),
new BoxLayoutDemoPanel()};
private final static Object[] demoManagerNames = {"SBorderLayout",
"SFlowLayout/SFlowDownLayout",
"SGridBagLayout",
"SGridLayout",
"SBoxLayout"};
private final SComboBox selectLayoutManager = new SComboBox(demoManagerNames);
protected SPanel panel;
private ComponentControls controls;
@Override
protected SComponent createControls() {
controls = new LayoutControls();
return controls;
}
@Override
protected SComponent createExample() {
panel = new SPanel(new SBorderLayout(10, 10));
panel.setPreferredSize(SDimension.FULLWIDTH);
panel.add(demoPanels[0], SBorderLayout.CENTER);
return panel;
}
private static class BorderLayoutDemoPanel extends SPanel {
private int i = 0;
private static final Color[] COLORS = new Color[] {
Color.GRAY,
new Color(255, 150, 150),
new Color(255, 255, 150),
new Color(150, 255, 150),
new Color(150, 255, 255),
new Color(150, 150, 255),
};
public BorderLayoutDemoPanel() {
super(new SFlowDownLayout());
add(createDescriptionLabel("The box layout allows to position a component in various regions of a panel: " +
"NORTH, SOUTH, EAST, WEST and CENTER.\n" +
"Normally these sections are invisible but we encouloured them here for demonstration the component" +
"alignment inside the cells."));
add(new SLabel("\nA default SBorderLayout"));
SPanel borderDemoPanel1 = new SPanel(new SBorderLayout());
borderDemoPanel1.add(wrapIntoColouredPane(createDummyLabel(0)), SBorderLayout.NORTH);
borderDemoPanel1.add(wrapIntoColouredPane(createDummyLabel(1)), SBorderLayout.SOUTH);
borderDemoPanel1.add(wrapIntoColouredPane(createDummyLabel(2)), SBorderLayout.EAST);
borderDemoPanel1.add(wrapIntoColouredPane(createDummyLabel(3)), SBorderLayout.WEST);
borderDemoPanel1.add(wrapIntoColouredPane(createDummyLabel(4)), SBorderLayout.CENTER);
add(borderDemoPanel1);
borderDemoPanel1.setPreferredSize(new SDimension(800, 150));
borderDemoPanel1.setBackground(new Color(210, 210, 210));
}
private SComponent wrapIntoColouredPane(SComponent c) {
SPanel colouredPanel = new SPanel(new SBoxLayout(null, SBoxLayout.VERTICAL));
colouredPanel.add(c);
colouredPanel.setPreferredSize(SDimension.FULLAREA);
colouredPanel.setVerticalAlignment(c.getVerticalAlignment());
colouredPanel.setHorizontalAlignment(c.getHorizontalAlignment());
colouredPanel.setBackground(COLORS[i++ % COLORS.length]);
return colouredPanel;
}
}
private static class BoxLayoutDemoPanel extends SPanel {
public BoxLayoutDemoPanel() {
super(new SFlowDownLayout());
add(createDescriptionLabel("The box layout is a simple version of gridlayout. It allows you to arrange " +
"components in a simple line - either horizontally or vertically aligned. Look at SFlowLayout " +
"if you require a wrapping horizontal alignment."));
add(new SLabel("\nHorizontal box layout with padding & border"));
SBoxLayout horizontalLayout = new SBoxLayout(null, SBoxLayout.HORIZONTAL);
horizontalLayout.setHgap(10);
horizontalLayout.setVgap(10);
horizontalLayout.setBorder(1);
add(createPanel(horizontalLayout, 4));
add(new SLabel("\nVertical vanilla box layout"));
SBoxLayout verticalLayout = new SBoxLayout(null, SBoxLayout.VERTICAL);
add(createPanel(verticalLayout, 4));
}
}
private static class FlowLayoutDemoPanel extends SPanel {
public FlowLayoutDemoPanel() {
super(new SFlowDownLayout());
add(createDescriptionLabel("Demonstration of flowing layout managers SFlowLayout and SFlowDownLayout\n" +
"Try out to resize the browser window to smaller/larger size. These labels below should 'flow'. " +
"This means they should break into the next line if the space is not sufficient to display them" +
"in the current line.\nPlease note that some component alignments won't work correctly " +
"due to restrictions of the rendering engines."));
// SFlowLayout
add(new SLabel(" "));
add(createDescriptionLabel("SFlowLayout"));
add(new SLabel("SFlowLayout - Layout Alignment: default (SFlowLayout.LEFT) - Container alignment: default"));
add(createPanel(new SFlowLayout(SFlowLayout.LEFT), 4));
add(new SLabel("\nSFlowLayout - Alignment: SFlowLayout.CENTER - Container alignment: center"));
final SPanel panel2 = createPanel(new SFlowLayout(SFlowLayout.CENTER), 4);
panel2.setHorizontalAlignment(CENTER);
add(panel2);
add(new SLabel("\nSFlowLayout - Alignment: SFlowLayout.RIGHT - Container alignment: right"));
final SPanel panel3 = createPanel(new SFlowLayout(SFlowLayout.RIGHT), 4);
panel3.setHorizontalAlignment(RIGHT);
add(panel3);
// SFlowDownLayout
add(new SLabel(" "));
add(createDescriptionLabel("SFlowDownLayout"));
add(new SLabel("SFlowDownLayout - Container alignment: default"));
add(createPanel(new SFlowDownLayout(), 4));
add(new SLabel("\nSFlowDownLayout - Container alignment: center"));
final SPanel panel4 = createPanel(new SFlowDownLayout(), 3);
panel4.setHorizontalAlignment(CENTER);
add(panel4);
add(new SLabel("\nSFlowDownLayout - Container alignment: right"));
final SPanel panel5 = createPanel(new SFlowDownLayout(), 4);
panel5.setHorizontalAlignment(RIGHT);
add(panel5);
}
}
private static class GridLayoutDemoPanel extends SPanel {
public GridLayoutDemoPanel() {
super(new SFlowDownLayout());
add(createDescriptionLabel("The grid layout is a simple way to arrange your components in a tabular manner.\n" +
"The example below adds 9 components in a 3-columned grid layout."));
add(new SLabel("\nGrid Layout panel with 3 colums, border, 10px horizontal gap, 40 vertical gap"));
SGridLayout layout1 = new SGridLayout(3);
layout1.setBorder(1);
layout1.setHgap(10);
layout1.setVgap(40);
add(createPanel(layout1, 12));
}
}
private static class GridBagDemoPanel extends SPanel {
public GridBagDemoPanel() {
setLayout(new SFlowDownLayout());
add(createDescriptionLabel("The SGridBagLayout is a powerful layout manager to align components " +
"in a very complex manner. "));
addRemainderDemo();
addPredefinedGridXAndXDemo();
addRandomAddngWithPreDefinedGridXandY();
addWeightBasedDemo();
addGridWidthRelativeDemo();
addGridHeightRelativeDemo();
}
private void addGridHeightRelativeDemo() {
SGridBagLayout layout;
SPanel p;
GridBagConstraints c;
add(new SLabel("\nVertical adding with gridheight=RELATIVE"));
layout = new SGridBagLayout();
layout.setBorder(1);
p = new SPanel(layout);
add(p);
c = new GridBagConstraints();
c.gridx = 0;
p.add(new SLabel("1"), c);
p.add(new SLabel("2"), c);
p.add(new SLabel("3"), c);
p.add(new SLabel("4"), c);
c.gridheight = GridBagConstraints.RELATIVE;
p.add(new SLabel("5"), c);
c.gridheight = 1;
p.add(new SLabel("end #1"), c);
c.gridx = 1;
p.add(new SLabel("6"), c);
p.add(new SLabel("7"), c);
p.add(new SLabel("8"), c);
c.gridheight = GridBagConstraints.RELATIVE;
p.add(new SLabel("9"), c);
c.gridheight = 1;
p.add(new SLabel("end #2"), c);
c.gridx = 2;
p.add(new SLabel("10"), c);
p.add(new SLabel("11"), c);
c.gridheight = GridBagConstraints.RELATIVE;
p.add(new SLabel("12"), c);
c.gridheight = 1;
p.add(new SLabel("end #3"), c);
c.gridx = 3;
p.add(new SLabel("13"), c);
c.gridheight = GridBagConstraints.RELATIVE;
p.add(new SLabel("14"), c);
c.gridheight = 1;
p.add(new SLabel("end #4"), c);
c.gridx = 4;
c.gridheight = GridBagConstraints.RELATIVE;
p.add(new SLabel("15"), c);
c.gridheight = 1;
p.add(new SLabel("end #5"), c);
}
private void addGridWidthRelativeDemo() {
SGridBagLayout layout;
SPanel p;
GridBagConstraints c;
add(new SLabel("\nAdding with gridwidth=RELATIVE"));
layout = new SGridBagLayout();
layout.setBorder(1);
p = new SPanel(layout);
add(p);
c = new GridBagConstraints();
p.add(new SLabel("1"), c);
p.add(new SLabel("2"), c);
p.add(new SLabel("3"), c);
p.add(new SLabel("4"), c);
c.gridwidth = GridBagConstraints.RELATIVE;
p.add(new SLabel("5"), c);
c.gridwidth = 1;
p.add(new SLabel("end #1"), c);
p.add(new SLabel("6"), c);
p.add(new SLabel("7"), c);
p.add(new SLabel("8"), c);
c.gridwidth = GridBagConstraints.RELATIVE;
p.add(new SLabel("9"), c);
c.gridwidth = 1;
p.add(new SLabel("end #2"), c);
p.add(new SLabel("10"), c);
p.add(new SLabel("11"), c);
c.gridwidth = GridBagConstraints.RELATIVE;
p.add(new SLabel("12"), c);
c.gridwidth = 1;
p.add(new SLabel("end #3"), c);
p.add(new SLabel("13"), c);
c.gridwidth = GridBagConstraints.RELATIVE;
p.add(new SLabel("14"), c);
c.gridwidth = 1;
p.add(new SLabel("end #4"), c);
c.gridwidth = GridBagConstraints.RELATIVE;
p.add(new SLabel("15"), c);
c.gridwidth = 1;
p.add(new SLabel("end #5"), c);
}
private void addWeightBasedDemo() {
SGridBagLayout layout;
SPanel p;
GridBagConstraints c;
add(new SLabel("\nUsing weight"));
layout = new SGridBagLayout();
layout.setBorder(1);
p = new SPanel(layout);
add(p);
p.setPreferredSize(new SDimension(500, 500));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
p.add(new SLabel("1"), c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1;
c.weighty = 0;
p.add(new SLabel("2"), c);
c.gridx = 2;
c.gridy = 0;
c.weightx = 2;
c.weighty = 0;
p.add(new SLabel("3"), c);
c.gridx = 3;
c.gridy = 0;
c.weightx = 1;
c.weighty = 0;
p.add(new SLabel("4"), c);
c.gridx = 4;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
p.add(new SLabel("5"), c);
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 1;
p.add(new SLabel("6"), c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
p.add(new SLabel("7"), c);
c.gridx = 2;
c.gridy = 1;
c.weightx = 2;
c.weighty = 1;
p.add(new SLabel("8"), c);
c.gridx = 3;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
p.add(new SLabel("9"), c);
c.gridx = 4;
c.gridy = 1;
c.weightx = 0;
c.weighty = 1;
p.add(new SLabel("10"), c);
c.gridx = 0;
c.gridy = 2;
c.weightx = 0;
c.weighty = 2;
p.add(new SLabel("11"), c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 1;
c.weighty = 2;
p.add(new SLabel("12"), c);
c.gridx = 2;
c.gridy = 2;
c.weightx = 2;
c.weighty = 2;
p.add(new SLabel("13"), c);
c.gridx = 3;
c.gridy = 2;
c.weightx = 1;
c.weighty = 2;
p.add(new SLabel("14"), c);
c.gridx = 4;
c.gridy = 2;
c.weightx = 0;
c.weighty = 2;
p.add(new SLabel("15"), c);
c.gridx = 0;
c.gridy = 3;
c.weightx = 0;
c.weighty = 1;
p.add(new SLabel("16"), c);
c.gridx = 1;
c.gridy = 3;
c.weightx = 1;
c.weighty = 1;
p.add(new SLabel("17"), c);
c.gridx = 2;
c.gridy = 3;
c.weightx = 2;
c.weighty = 1;
p.add(new SLabel("18"), c);
c.gridx = 3;
c.gridy = 3;
c.weightx = 1;
c.weighty = 1;
p.add(new SLabel("19"), c);
c.gridx = 4;
c.gridy = 3;
c.weightx = 0;
c.weighty = 1;
p.add(new SLabel("20"), c);
c.gridx = 0;
c.gridy = 4;
c.weightx = 0;
c.weighty = 0;
p.add(new SLabel("21"), c);
c.gridx = 1;
c.gridy = 4;
c.weightx = 1;
c.weighty = 0;
p.add(new SLabel("22"), c);
c.gridx = 2;
c.gridy = 4;
c.weightx = 2;
c.weighty = 0;
p.add(new SLabel("23"), c);
c.gridx = 3;
c.gridy = 4;
c.weightx = 1;
c.weighty = 0;
p.add(new SLabel("24"), c);
c.gridx = 4;
c.gridy = 4;
c.weightx = 0;
c.weighty = 0;
p.add(new SLabel("25"), c);
}
private void addRandomAddngWithPreDefinedGridXandY() {
SGridBagLayout layout;
SPanel p;
GridBagConstraints c;
add(new SLabel("\nRandom adding with pre-defined gridx+gridy"));
layout = new SGridBagLayout();
layout.setBorder(1);
p = new SPanel(layout);
add(p);
c = new GridBagConstraints();
c.gridx = 4;
c.gridy = 0;
p.add(new SLabel("1"), c);
c.gridx = 3;
c.gridy = 1;
p.add(new SLabel("2"), c);
c.gridx = 2;
c.gridy = 2;
p.add(new SLabel("3"), c);
c.gridx = 1;
c.gridy = 3;
p.add(new SLabel("4"), c);
c.gridx = 0;
c.gridy = 4;
p.add(new SLabel("5"), c);
}
private void addPredefinedGridXAndXDemo() {
SGridBagLayout layout;
SPanel p;
GridBagConstraints c;
add(new SLabel("\nVertical adding using pre-defined gridx"));
layout = new SGridBagLayout();
layout.setBorder(1);
p = new SPanel(layout);
add(p);
c = new GridBagConstraints();
// 1st column
c.gridx = 0;
c.gridheight = GridBagConstraints.REMAINDER;
p.add(new SLabel("1"), c);
// 2nd column
c.gridx = 1;
c.gridheight = 1;
p.add(new SLabel("2"), c);
c.gridheight = GridBagConstraints.REMAINDER;
p.add(new SLabel("3"), c);
c.gridheight = 1;
// 3rd column
c.gridx = 2;
c.gridheight = 1;
p.add(new SLabel("4"), c);
p.add(new SLabel("5"), c);
c.gridheight = GridBagConstraints.REMAINDER;
p.add(new SLabel("6"), c);
// 4th column
c.gridx = 3;
c.gridheight = 1;
p.add(new SLabel("7"), c);
p.add(new SLabel("8"), c);
p.add(new SLabel("9"), c);
c.gridheight = GridBagConstraints.REMAINDER;
p.add(new SLabel("10"), c);
}
private void addRemainderDemo() {
add(new SLabel("\nHorizontal adding using REMAINDER"));
SGridBagLayout layout = new SGridBagLayout();
layout.setBorder(1);
SPanel p = new SPanel(layout);
p.setPreferredSize(new SDimension(300, 100));
p.setBackground(Color.red);
add(p);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
p.add(new SLabel("1"), c);
c.gridwidth = 1;
p.add(new SLabel("2"), c);
c.gridwidth = GridBagConstraints.REMAINDER;
p.add(new SLabel("3"), c);
c.gridwidth = 1;
p.add(new SLabel("4"), c);
p.add(new SLabel("5"), c);
c.gridwidth = GridBagConstraints.REMAINDER;
p.add(new SLabel("6"), c);
c.gridwidth = 1;
p.add(new SLabel("7"), c);
p.add(new SLabel("8"), c);
p.add(new SLabel("9"), c);
c.gridwidth = GridBagConstraints.REMAINDER;
p.add(new SLabel("10"), c);
}
}
/** Returns a formatted component describing the current layout exampel. */
private static SComponent createDescriptionLabel(String description) {
SLabel multiLineLabel = new SLabel();
//multiLineLabel.setEditable(false);
multiLineLabel.setWordWrap(true);
multiLineLabel.setPreferredSize(SDimension.FULLWIDTH);
multiLineLabel.setText(description);
multiLineLabel.setBorder(new SLineBorder(Color.gray, 1));
multiLineLabel.setBackground(new Color(255, 255, 150));
return multiLineLabel;
}
/**
* Creates a new panel with desired amount of dummy labels on it.
*/
private static SPanel createPanel(SLayoutManager layout, int amountOfDummyLabels) {
final SPanel panel = new SPanel(layout);
panel.setBackground(new Color(210, 210, 210));
for (int i = 0; i < amountOfDummyLabels; i++) {
panel.add(createDummyLabel(i));
}
return panel;
}
/* Create a dummy label with a specific label, color, border and alignment depending on index. */
private static SLabel createDummyLabel(int i) {
final String[] texts = {"[%] A short component (Top/Left)",
"[%] A longer, unbreakable label for wrapping demo (Default)",
"[%] Another short one (Right/Bottom)",
"[%] A 2-line\nlabel (Center/Center)"};
final SBorder greenLineBorder = new SLineBorder(2);
greenLineBorder.setColor(Color.red);
final SLabel label = new SLabel(texts[i % 4].replace('%', Integer.toString((i + 1)).charAt(0)));
label.setBorder(greenLineBorder);
label.setBackground(new Color(0xEE,0xEE,0xEE));
if (i % texts.length == 0) {
label.setVerticalAlignment(TOP);
label.setHorizontalAlignment(LEFT);
} else if (i % texts.length == 1)
;
else if (i % texts.length == 2) {
label.setHorizontalAlignment(RIGHT);
label.setVerticalAlignment(BOTTOM);
} else if (i % texts.length == 3) {
label.setHorizontalAlignment(CENTER);
label.setVerticalAlignment(CENTER);
}
return label;
}
class LayoutControls
extends ComponentControls {
public LayoutControls() {
globalControls.setVisible(false);
selectLayoutManager.addItemListener(e -> {
panel.remove(0);
panel.add(demoPanels[selectLayoutManager.getSelectedIndex()]);
});
selectLayoutManager.setHorizontalAlignment(SConstants.LEFT_ALIGN);
addControl(new SLabel(" choose layout manager"));
addControl(selectLayoutManager);
}
}
}
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-tools/xwiki-platform-tool-packager-plugin/src/main/java/org/xwiki/tool/packager/internal/MavenBuildJarExtensionHandler.java | 1768 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.tool.packager.internal;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.extension.InstallException;
import org.xwiki.extension.LocalExtension;
import org.xwiki.extension.jar.internal.handler.JarExtensionHandler;
import org.xwiki.job.Request;
/**
* Override {@link JarExtensionHandler} to skip the actual JAR/Components registration which does not make sense in a
* Maven build (assuming the install job is used to generate a database).
*
* @version $Id$
* @since 9.5RC1
*/
@Component(hints = { JarExtensionHandler.JAR, JarExtensionHandler.WEBJAR })
@Singleton
public class MavenBuildJarExtensionHandler extends JarExtensionHandler
{
@Override
public void install(LocalExtension localExtension, String namespace, Request request) throws InstallException
{
// Do nothing
}
}
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/internal/plugin/image/ThumbnailatorImageProcessor.java | 2785 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.internal.plugin.image;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import net.coobird.thumbnailator.Thumbnails;
/**
* Image processor implementation based on the Thumbnailator library.
*
* @version $Id$
* @since 8.4.4
* @since 9.0RC1
*/
@Component
@Singleton
@Named("thumbnailator")
public class ThumbnailatorImageProcessor extends DefaultImageProcessor
{
@Override
public void writeImage(RenderedImage image, String mimeType, float quality, OutputStream out) throws IOException
{
if (image instanceof BufferedImage) {
Thumbnails.of((BufferedImage) image).scale(1).outputFormat(getFormatNameForMimeType(mimeType))
.outputQuality(quality).toOutputStream(out);
} else {
super.writeImage(image, mimeType, quality, out);
}
}
@Override
public RenderedImage scaleImage(Image image, int width, int height)
{
if (image instanceof BufferedImage) {
try {
return Thumbnails.of((BufferedImage) image).size(width, height).asBufferedImage();
} catch (IOException e) {
}
}
return super.scaleImage(image, width, height);
}
private String getFormatNameForMimeType(String mimeType)
{
Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(mimeType);
if (imageReaders.hasNext()) {
try {
return imageReaders.next().getFormatName();
} catch (IOException e) {
}
}
return mimeType;
}
}
| lgpl-2.1 |
solmix/datax | generator/core/src/main/java/org/solmix/generator/codegen/mybatis/javamapper/elements/annotated/AnnotatedSelectByExampleWithBLOBsMethodGenerator.java | 4098 | /**
* Copyright 2006-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.solmix.generator.codegen.mybatis.javamapper.elements.annotated;
import static org.solmix.generator.api.OutputUtilities.javaIndent;
import java.util.Iterator;
import org.solmix.generator.api.IntrospectedColumn;
import org.solmix.generator.api.java.FullyQualifiedJavaType;
import org.solmix.generator.api.java.Interface;
import org.solmix.generator.api.java.Method;
import org.solmix.generator.codegen.mybatis.javamapper.elements.SelectByExampleWithBLOBsMethodGenerator;
/**
*
* @author Jeff Butler
*/
public class AnnotatedSelectByExampleWithBLOBsMethodGenerator extends SelectByExampleWithBLOBsMethodGenerator {
public AnnotatedSelectByExampleWithBLOBsMethodGenerator() {
super();
}
@Override
public void addMapperAnnotations(Interface interfaze, Method method) {
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(introspectedTable.getMyBatis3SqlProviderType());
StringBuilder sb = new StringBuilder();
sb.append("@SelectProvider(type=");
sb.append(fqjt.getShortName());
sb.append(".class, method=\"");
sb.append(introspectedTable.getSelectByExampleWithBLOBsStatementId());
sb.append("\")");
method.addAnnotation(sb.toString());
if (introspectedTable.isConstructorBased()) {
method.addAnnotation("@ConstructorArgs({");
} else {
method.addAnnotation("@Results({");
}
Iterator<IntrospectedColumn> iterPk = introspectedTable.getPrimaryKeyColumns().iterator();
Iterator<IntrospectedColumn> iterNonPk = introspectedTable.getNonPrimaryKeyColumns().iterator();
while (iterPk.hasNext()) {
IntrospectedColumn introspectedColumn = iterPk.next();
sb.setLength(0);
javaIndent(sb, 1);
sb.append(getResultAnnotation(interfaze, introspectedColumn, true,
introspectedTable.isConstructorBased()));
if (iterPk.hasNext() || iterNonPk.hasNext()) {
sb.append(',');
}
method.addAnnotation(sb.toString());
}
while (iterNonPk.hasNext()) {
IntrospectedColumn introspectedColumn = iterNonPk.next();
sb.setLength(0);
javaIndent(sb, 1);
sb.append(getResultAnnotation(interfaze, introspectedColumn, false,
introspectedTable.isConstructorBased()));
if (iterNonPk.hasNext()) {
sb.append(',');
}
method.addAnnotation(sb.toString());
}
method.addAnnotation("})");
}
@Override
public void addExtraImports(Interface interfaze) {
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.SelectProvider"));
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.type.JdbcType"));
if (introspectedTable.isConstructorBased()) {
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Arg"));
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.ConstructorArgs"));
} else {
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Result"));
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Results"));
}
}
}
| lgpl-2.1 |
solmix/datax | generator/core/src/main/java/org/solmix/generator/api/IntrospectedColumn.java | 9461 | /**
* Copyright 2006-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.solmix.generator.api;
import java.sql.Types;
import java.util.Properties;
import org.solmix.generator.api.java.FullyQualifiedJavaType;
import org.solmix.generator.config.ColumnInfo;
import org.solmix.generator.config.DomainInfo;
/**
* This class holds information about an introspected column. The class has
* utility methods useful for generating iBATIS objects.
*
* @author Jeff Butler
*/
public class IntrospectedColumn {
protected String actualColumnName;
protected int jdbcType;
protected String jdbcTypeName;
protected String nativeSqlType;
protected boolean nullable;
protected int length;
protected int scale;
protected boolean identity;
protected boolean isSequenceColumn;
protected String javaProperty;
protected FullyQualifiedJavaType fullyQualifiedJavaType;
protected String tableAlias;
protected String typeHandler;
protected DomainInfo domain;
protected boolean isColumnNameDelimited;
protected IntrospectedTable introspectedTable;
protected Properties properties;
// any database comment associated with this column. May be null
protected String remarks;
protected String defaultValue;
/**
* true if the JDBC driver reports that this column is auto-increment.
*/
protected boolean isAutoIncrement;
/**
* true if the JDBC driver reports that this column is generated.
*/
protected boolean isGeneratedColumn;
/**
* True if there is a column override that defines this column as GENERATED ALWAYS.
*/
protected boolean isGeneratedAlways;
private ColumnInfo columnInfo;
/**
* Constructs a Column definition. This object holds all the information
* about a column that is required to generate Java objects and SQL maps;
*/
public IntrospectedColumn() {
super();
properties = new Properties();
}
public int getJdbcType() {
return jdbcType;
}
public void setJdbcType(int jdbcType) {
this.jdbcType = jdbcType;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public boolean isNullable() {
return nullable;
}
public void setNullable(boolean nullable) {
this.nullable = nullable;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
/*
* This method is primarily used for debugging, so we don't externalize the
* strings
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Actual Column Name: ");
sb.append(actualColumnName);
sb.append(", JDBC Type: ");
sb.append(jdbcType);
sb.append(", Nullable: ");
sb.append(nullable);
sb.append(", Length: ");
sb.append(length);
sb.append(", Scale: ");
sb.append(scale);
sb.append(", Identity: ");
sb.append(identity);
return sb.toString();
}
public void setActualColumnName(String actualColumnName) {
this.actualColumnName = actualColumnName;
isColumnNameDelimited = stringContainsSpace(actualColumnName);
}
public static boolean stringContainsSpace(String s) {
return s != null && s.indexOf(' ') != -1;
}
/**
* @return Returns the identity.
*/
public boolean isIdentity() {
return identity;
}
/**
* @param identity
* The identity to set.
*/
public void setIdentity(boolean identity) {
this.identity = identity;
}
public boolean isBLOBColumn() {
String typeName = getJdbcTypeName();
return "BINARY".equals(typeName) || "BLOB".equals(typeName) //$NON-NLS-2$
|| "CLOB".equals(typeName) || "LONGNVARCHAR".equals(typeName) //$NON-NLS-2$
|| "LONGVARBINARY".equals(typeName) || "LONGVARCHAR".equals(typeName) //$NON-NLS-2$
|| "NCLOB".equals(typeName) || "VARBINARY".equals(typeName); //$NON-NLS-2$
}
public boolean isStringColumn() {
return fullyQualifiedJavaType.equals(FullyQualifiedJavaType
.getStringInstance());
}
public boolean isJdbcCharacterColumn() {
return jdbcType == Types.CHAR || jdbcType == Types.CLOB
|| jdbcType == Types.LONGVARCHAR || jdbcType == Types.VARCHAR
|| jdbcType == Types.LONGNVARCHAR || jdbcType == Types.NCHAR
|| jdbcType == Types.NCLOB || jdbcType == Types.NVARCHAR;
}
public String getJavaProperty() {
return getJavaProperty(null);
}
public String getJavaProperty(String prefix) {
if (prefix == null) {
return javaProperty;
}
StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append(javaProperty);
return sb.toString();
}
public void setJavaProperty(String javaProperty) {
this.javaProperty = javaProperty;
}
public boolean isJDBCDateColumn() {
return fullyQualifiedJavaType.equals(FullyQualifiedJavaType
.getDateInstance())
&& "DATE".equalsIgnoreCase(jdbcTypeName);
}
public boolean isJDBCTimeColumn() {
return fullyQualifiedJavaType.equals(FullyQualifiedJavaType
.getDateInstance())
&& "TIME".equalsIgnoreCase(jdbcTypeName);
}
public String getTypeHandler() {
return typeHandler;
}
public void setTypeHandler(String typeHandler) {
this.typeHandler = typeHandler;
}
public String getActualColumnName() {
return actualColumnName;
}
public void setColumnNameDelimited(boolean isColumnNameDelimited) {
this.isColumnNameDelimited = isColumnNameDelimited;
}
public boolean isColumnNameDelimited() {
return isColumnNameDelimited;
}
public String getJdbcTypeName() {
if (jdbcTypeName == null) {
return "OTHER";
}
return jdbcTypeName;
}
public void setJdbcTypeName(String jdbcTypeName) {
this.jdbcTypeName = jdbcTypeName;
}
public FullyQualifiedJavaType getFullyQualifiedJavaType() {
return fullyQualifiedJavaType;
}
public void setFullyQualifiedJavaType(
FullyQualifiedJavaType fullyQualifiedJavaType) {
this.fullyQualifiedJavaType = fullyQualifiedJavaType;
}
public String getTableAlias() {
return tableAlias;
}
public void setTableAlias(String tableAlias) {
this.tableAlias = tableAlias;
}
public DomainInfo getDomain() {
return domain;
}
public void setDomain(DomainInfo domain) {
this.domain=domain;
}
public IntrospectedTable getIntrospectedTable() {
return introspectedTable;
}
public void setIntrospectedTable(IntrospectedTable introspectedTable) {
this.introspectedTable = introspectedTable;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties.putAll(properties);
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean isSequenceColumn() {
return isSequenceColumn;
}
public void setSequenceColumn(boolean isSequenceColumn) {
this.isSequenceColumn = isSequenceColumn;
}
public boolean isAutoIncrement() {
return isAutoIncrement;
}
public void setAutoIncrement(boolean isAutoIncrement) {
this.isAutoIncrement = isAutoIncrement;
}
public boolean isGeneratedColumn() {
return isGeneratedColumn;
}
public void setGeneratedColumn(boolean isGeneratedColumn) {
this.isGeneratedColumn = isGeneratedColumn;
}
public boolean isGeneratedAlways() {
return isGeneratedAlways;
}
public void setGeneratedAlways(boolean isGeneratedAlways) {
this.isGeneratedAlways = isGeneratedAlways;
}
public String getNativeSqlType() {
return nativeSqlType;
}
public void setNativeSqlType(String nativeSqlType) {
this.nativeSqlType = nativeSqlType;
}
public void setColumnInfo(ColumnInfo c) {
this.columnInfo=c;
}
public ColumnInfo getColumnInfo() {
return columnInfo;
}
}
| lgpl-2.1 |
esig/dss | specs-validation-report/src/main/java/eu/europa/esig/validationreport/ValidationReportUtils.java | 2544 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* 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 eu.europa.esig.validationreport;
import eu.europa.esig.trustedlist.TrustedListUtils;
import eu.europa.esig.validationreport.jaxb.ObjectFactory;
import eu.europa.esig.xmldsig.XSDAbstractUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.util.List;
/**
* ETSI Validation Report Utils
*/
public final class ValidationReportUtils extends XSDAbstractUtils {
/** The Object Factory to use */
public static final ObjectFactory OBJECT_FACTORY = new ObjectFactory();
/** The ETSI Validation Report XSD schema location */
public static final String VALIDATION_REPORT_SCHEMA_LOCATION = "/xsd/1910202xmlSchema.xsd";
/** Singleton */
private static ValidationReportUtils singleton;
/** JAXBContext */
private JAXBContext jc;
private ValidationReportUtils() {
}
/**
* Returns instance of {@code ValidationReportUtils}
*
* @return {@link ValidationReportUtils}
*/
public static ValidationReportUtils getInstance() {
if (singleton == null) {
singleton = new ValidationReportUtils();
}
return singleton;
}
@Override
public JAXBContext getJAXBContext() throws JAXBException {
if (jc == null) {
jc = JAXBContext.newInstance(ObjectFactory.class);
}
return jc;
}
@Override
public List<Source> getXSDSources() {
List<Source> xsdSources = TrustedListUtils.getInstance().getXSDSources();
xsdSources.add(new StreamSource(ValidationReportUtils.class.getResourceAsStream(VALIDATION_REPORT_SCHEMA_LOCATION)));
return xsdSources;
}
}
| lgpl-2.1 |
demoiselle/signer | policy-engine/src/main/java/org/demoiselle/signer/policy/engine/asn1/etsi/SignerAndVerifierRules.java | 3142 | /*
* Demoiselle Framework
* Copyright (C) 2016 SERPRO
* ----------------------------------------------------------------------------
* This file is part of Demoiselle Framework.
*
* Demoiselle Framework is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License version 3
* along with this program; if not, see <http://www.gnu.org/licenses/>
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
* ----------------------------------------------------------------------------
* Este arquivo é parte do Framework Demoiselle.
*
* O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
* do Software Livre (FSF).
*
* Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
* GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
* APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
* para maiores detalhes.
*
* Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
* "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
* ou escreva para a Fundação do Software Livre (FSF) Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
*/
package org.demoiselle.signer.policy.engine.asn1.etsi;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.demoiselle.signer.policy.engine.asn1.ASN1Object;
/**
* The SignerAndVerifierRules consists of signer rule and
* verification rules as defined below:
*
* <pre>
* SignerAndVerifierRules ::= SEQUENCE {
* signerRules {@link SignerRules},
* verifierRules {@link VerifierRules}
* }
* </pre>
*
* @see ASN1Sequence
* @see ASN1Primitive
*/
public class SignerAndVerifierRules extends ASN1Object {
private SignerRules signerRules;
private VerifierRules verifierRules;
public SignerRules getSignerRules() {
return signerRules;
}
public void setSignerRules(SignerRules signerRules) {
this.signerRules = signerRules;
}
public VerifierRules getVerifierRules() {
return verifierRules;
}
public void setVerifierRules(VerifierRules verifierRules) {
this.verifierRules = verifierRules;
}
@Override
public void parse(ASN1Primitive derObject) {
ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
this.signerRules = new SignerRules();
this.signerRules.parse(derSequence.getObjectAt(0).toASN1Primitive());
this.verifierRules = new VerifierRules();
this.verifierRules.parse(derSequence.getObjectAt(1).toASN1Primitive());
}
}
| lgpl-3.0 |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v2/src/main/java/com/foo/rest/examples/spring/namedresource/NamedResourceApplication.java | 1044 | package com.foo.rest.examples.spring.namedresource;
import com.foo.rest.examples.spring.SwaggerConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
/**
* Created by arcand on 01.03.17.
*/
@EnableSwagger2
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class NamedResourceApplication extends SwaggerConfiguration {
public static void main(String[] args){
SpringApplication.run(NamedResourceApplication.class, args);
}
}
| lgpl-3.0 |
umr-dbs/xxl-usecases | src/xxl/core/xxql/usecases/ref/linq/cursors/XXLinqCursor.java | 2957 | /* XXL: The eXtensible and fleXible Library for data processing
Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger
Head of the Database Research Group
Department of Mathematics and Computer Science
University of Marburg
Germany
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
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, see <http://www.gnu.org/licenses/>.
http://code.google.com/p/xxl/
*/
package xxl.core.xxql.usecases.ref.linq.cursors;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.NoSuchElementException;
import xxl.core.cursors.Cursor;
import xxl.core.cursors.MetaDataCursor;
import xxl.core.cursors.mappers.Mapper;
import xxl.core.functions.Function;
import xxl.core.relational.tuples.ArrayTuple;
import xxl.core.relational.tuples.Tuple;
import xxl.core.xxql.usecases.ref.linq.column.XXLinqColumn;
import xxl.core.xxql.usecases.ref.linq.metadata.XXLinqMetadata;
import xxl.core.xxql.usecases.ref.linq.pred.XXLinqPredicate;
public abstract class XXLinqCursor implements MetaDataCursor<Tuple, XXLinqMetadata>,
Iterable<Tuple> {
//protected XXLinqMetadata metadata;
protected Function<Tuple, Tuple> tupleMapper;
protected Function<XXLinqMetadata, XXLinqMetadata> metaDataMapper;
@Override
public XXLinqMetadata getMetaData() {
return this.metaDataMapper.invoke();
}
@Override
public Iterator<Tuple> iterator() {
return this;
}
public static <E> XXLinqCursor createXXLinqCursor(Iterable<E> iter, String tableName, String columnName) {
Cursor<Tuple> mapper = new Mapper<E, Tuple>(ArrayTuple.FACTORY_METHOD,
iter.iterator());
return new XXLinqWrapperCursor(mapper, tableName, columnName);
}
public static <E> XXLinqCursor createXXLinqCursor(Cursor<E> iter) {
Cursor<Tuple> mapper = new Mapper<E, Tuple>(ArrayTuple.FACTORY_METHOD,
iter);
return new XXLinqWrapperCursor(mapper);
}
public XXLinqCursor zip(XXLinqCursor aCursor) {
return new XXLinqZipCursor(this, aCursor);
}
public XXLinqCursor select(XXLinqColumn ... xxLinqColumns) {
return new XXLinqProjectionCursor(this, xxLinqColumns);
}
public XXLinqCursor where(XXLinqPredicate pred) {
// TODO Auto-generated method stub
return new XXLinqSelectionCursor(this, pred);
}
}
| lgpl-3.0 |
CD4017BE/CD4017BE_lib | src/java/cd4017be/lib/util/ItemKey.java | 1000 | package cd4017be.lib.util;
import net.minecraft.item.ItemStack;
/**
* Used for efficient shaped recipe lookup in HashMaps
* @author cd4017be
*/
public class ItemKey {
public final ItemStack[] items;
private final int hash;
public ItemKey(ItemStack... items) {
this.items = items;
final int prime = 31;
int result = 1;
for (ItemStack item : items)
result = prime * result + (item.isEmpty() ? 0 : item.getItem().getRegistryName().hashCode() ^ item.getDamageValue());
this.hash = result;
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj instanceof ItemKey) {
ItemKey other = (ItemKey) obj;
int n = items.length;
if (other.items.length != n) return false;
for (int i = 0; i < n; i++) {
ItemStack item = items[i];
if (!(item.isEmpty() ? other.items[i].isEmpty() : item.sameItem(other.items[i])))
return false;
}
return true;
}
return false;
}
}
| lgpl-3.0 |
timewalker74/ffmq | core/src/main/java/net/timewalker/ffmq4/transport/packet/query/CreateDurableSubscriberQuery.java | 4404 | /*
* This file is part of FFMQ.
*
* FFMQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* FFMQ 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 FFMQ; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.timewalker.ffmq4.transport.packet.query;
import javax.jms.Topic;
import net.timewalker.ffmq4.common.destination.DestinationSerializer;
import net.timewalker.ffmq4.transport.packet.PacketType;
import net.timewalker.ffmq4.utils.RawDataBuffer;
import net.timewalker.ffmq4.utils.id.IntegerID;
/**
* CreateDurableSubscriberQuery
*/
public final class CreateDurableSubscriberQuery extends AbstractSessionQuery
{
private IntegerID consumerId;
private Topic topic;
private String messageSelector;
private boolean noLocal;
private String name;
/* (non-Javadoc)
* @see net.timewalker.ffmq4.network.packet.AbstractPacket#getType()
*/
@Override
public byte getType()
{
return PacketType.Q_CREATE_DURABLE_SUBSCRIBER;
}
/* (non-Javadoc)
* @see net.timewalker.ffmq4.network.packet.AbstractPacket#serializeTo(net.timewalker.ffmq4.utils.RawDataOutputStream)
*/
@Override
protected void serializeTo(RawDataBuffer out)
{
super.serializeTo(out);
out.writeInt(consumerId.asInt());
DestinationSerializer.serializeTo(topic, out);
out.writeNullableUTF(messageSelector);
out.writeBoolean(noLocal);
out.writeUTF(name);
}
/* (non-Javadoc)
* @see net.timewalker.ffmq4.network.packet.AbstractPacket#unserializeFrom(net.timewalker.ffmq4.utils.RawDataInputStream)
*/
@Override
protected void unserializeFrom(RawDataBuffer in)
{
super.unserializeFrom(in);
consumerId = new IntegerID(in.readInt());
topic = (Topic)DestinationSerializer.unserializeFrom(in);
messageSelector = in.readNullableUTF();
noLocal = in.readBoolean();
name = in.readUTF();
}
/**
* @return the consumerId
*/
public IntegerID getConsumerId()
{
return consumerId;
}
/**
* @param consumerId the consumerId to set
*/
public void setConsumerId(IntegerID consumerId)
{
this.consumerId = consumerId;
}
/**
* @return the topic
*/
public Topic getTopic()
{
return topic;
}
/**
* @param topic the topic to set
*/
public void setTopic(Topic topic)
{
this.topic = topic;
}
/**
* @return the messageSelector
*/
public String getMessageSelector()
{
return messageSelector;
}
/**
* @param messageSelector the messageSelector to set
*/
public void setMessageSelector(String messageSelector)
{
this.messageSelector = messageSelector;
}
/**
* @return the noLocal
*/
public boolean isNoLocal()
{
return noLocal;
}
/**
* @param noLocal the noLocal to set
*/
public void setNoLocal(boolean noLocal)
{
this.noLocal = noLocal;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString());
sb.append(" consumerId=");
sb.append(consumerId);
sb.append(" topic=");
sb.append(topic);
sb.append(" messageSelector=[");
sb.append(messageSelector);
sb.append("] noLocal=");
sb.append(noLocal);
sb.append(" name=");
sb.append(name);
return sb.toString();
}
}
| lgpl-3.0 |
Spground/NewDUTHelper | app/src/main/java/com/siwe/dutschedule/base/BaseMessage.java | 3768 | package com.siwe.dutschedule.base;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.siwe.dutschedule.util.AppUtil;
public class BaseMessage {
private String code;
private String message;
private String resultSrc;
private Map<String, BaseModel> resultMap;
private Map<String, ArrayList<? extends BaseModel>> resultList;
public BaseMessage () {
this.resultMap = new HashMap<String, BaseModel>();
this.resultList = new HashMap<String, ArrayList<? extends BaseModel>>();
}
@Override
public String toString () {
return code + " | " + message + " | " + resultSrc;
}
public String getCode () {
return this.code;
}
public void setCode (String code) {
this.code = code;
}
public String getMessage () {
return this.message;
}
public void setMessage (String message) {
this.message = message;
}
public boolean isSuccess()
{
if(this.getCode()==null)
return false;
return this.getCode().equals("10000")?true:false;
}
public String getResult () {
return this.resultSrc;
}
public Object getResult (String modelName) throws Exception {
Object model = this.resultMap.get(modelName);
// catch null exception
if (model == null) {
throw new Exception("Message data is empty");
}
return model;
}
public ArrayList<? extends BaseModel> getResultList (String modelName) throws Exception {
ArrayList<? extends BaseModel> modelList = this.resultList.get(modelName);
// catch null exception
if (modelList == null || modelList.size() == 0) {
throw new Exception("Message data list is empty");
}
return modelList;
}
@SuppressWarnings("unchecked")
public void setResult (String result) throws Exception {
this.resultSrc = result;
if (result.length() > 0) {
JSONObject jsonObject = null;
jsonObject = new JSONObject(result);
Iterator<String> it = jsonObject.keys();
while (it.hasNext()) {
// initialize
String jsonKey = it.next();
String modelName = getModelName(jsonKey);
String modelClassName = C.packageName.model+"." + modelName;
JSONArray modelJsonArray = jsonObject.optJSONArray(jsonKey);
// JSONObject
if (modelJsonArray == null) {
JSONObject modelJsonObject = jsonObject.optJSONObject(jsonKey);
if (modelJsonObject == null) {
throw new Exception("Message result is invalid");
}
this.resultMap.put(modelName, json2model(modelClassName, modelJsonObject));
// JSONArray
} else {
ArrayList<BaseModel> modelList = new ArrayList<BaseModel>();
for (int i = 0; i < modelJsonArray.length(); i++) {
JSONObject modelJsonObject = modelJsonArray.optJSONObject(i);
modelList.add(json2model(modelClassName, modelJsonObject));
}
this.resultList.put(modelName, modelList);
}
}
}
}
@SuppressWarnings("unchecked")
private BaseModel json2model (String modelClassName, JSONObject modelJsonObject) throws Exception {
// auto-load model class
BaseModel modelObj = (BaseModel) Class.forName(modelClassName).newInstance();
Class<? extends BaseModel> modelClass = modelObj.getClass();
// auto-setting model fields
Iterator<String> it = modelJsonObject.keys();
while (it.hasNext()) {
String varField = it.next();
String varValue = modelJsonObject.getString(varField);
Field field = modelClass.getDeclaredField(varField);
field.setAccessible(true); // have private to be accessable
field.set(modelObj, varValue);
}
return modelObj;
}
private String getModelName (String str) {
String[] strArr = str.split("\\W");
if (strArr.length > 0) {
str = strArr[0];
}
return AppUtil.ucfirst(str);
}
} | lgpl-3.0 |
TanyaEf/jrs-rest-java-client | src/main/java/com/jaspersoft/jasperserver/jaxrs/client/dto/jobs/reportjobmodel/ReportJobStateModel.java | 2277 | /*
* Copyright (C) 2005 - 2014 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 free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.reportjobmodel;
import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.JobState;
import com.jaspersoft.jasperserver.jaxrs.client.dto.jobs.JobStateType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
/**
* Searching thumbnail jobs by runtime information
*
* @author Ivan Chan (ichan@jaspersoft.com)
* @version $Id: ReportJobStateModel.java 25420 2012-10-20 16:36:09Z sergey.prilukin $
* @since 1.0
*/
@XmlRootElement(name = "stateModel")
public class ReportJobStateModel extends JobState {
/**
* Creates an empty object.
*/
public ReportJobStateModel() {
}
/**
* Sets the job next fire time.
*
* @param nextFireTime the next fire time for the job
*/
public ReportJobStateModel setNextFireTime(Date nextFireTime) {
super.setNextFireTime(nextFireTime);
return this;
}
/**
* Sets the job previous fire time.
*
* @param previousFireTime the previous fire time of the job
*/
public ReportJobStateModel setPreviousFireTime(Date previousFireTime) {
super.setPreviousFireTime(previousFireTime);
return this;
}
/**
* Sets the execution state of the job trigger.
*
* @param state one of the <code>STATE_*</code> constants
*/
public ReportJobStateModel setValue(JobStateType state) {
super.setValue(state);
return this;
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/HmiCore | HmiGraphics/src/hmi/graphics/collada/Shape.java | 5076 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.graphics.collada;
import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;
import java.io.IOException;
import java.util.ArrayList;
/**
* Declares a physical shape
* Ignored tags: hollow, mass, density, instance_physics_material, physics_material, instance_geometry,
* plane, cylinder, tapered_cylinder, tapered_capsule
*
* Assumes that the shape contains only one rotation and one translation, does not check or enforce only
* one of box, plane, sphere, cylinder, tapered_cylinder, capsule, tapered_capsule
* @author Herwin van Welbergen
*/
public class Shape extends ColladaElement
{
private Translate translate = null;
private Rotate rotate = null;
private Box box = null;
private Sphere sphere = null;
private Capsule capsule = null;
private ArrayList<Extra> extras = new ArrayList<Extra>();
public Shape()
{
super();
}
public Shape(Collada collada, XMLTokenizer tokenizer) throws IOException
{
super(collada);
readXML(tokenizer);
}
@Override
public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt)
{
appendXMLStructure(buf, fmt, getBox());
appendXMLStructure(buf, fmt, getSphere());
appendXMLStructure(buf, fmt, getCapsule());
appendXMLStructure(buf, fmt, getTranslate());
appendXMLStructure(buf, fmt, getRotate());
appendXMLStructureList(buf, fmt, extras);
return buf;
}
@Override
public void decodeContent(XMLTokenizer tokenizer) throws IOException
{
while (tokenizer.atSTag())
{
String tag = tokenizer.getTagName();
if (tag.equals(Translate.xmlTag()))
{
setTranslate(new Translate(getCollada(), tokenizer));
}
else if (tag.equals(Rotate.xmlTag()))
{
setRotate(new Rotate(getCollada(), tokenizer));
}
else if (tag.equals(Box.xmlTag()))
{
setBox(new Box(getCollada(), tokenizer));
}
else if (tag.equals(Sphere.xmlTag()))
{
setSphere(new Sphere(getCollada(), tokenizer));
}
else if (tag.equals(Capsule.xmlTag()))
{
setCapsule(new Capsule(getCollada(), tokenizer));
}
else
{
getCollada().warning(tokenizer.getErrorMessage("Shape: skip : " + tokenizer.getTagName()));
tokenizer.skipTag();
}
}
addColladaNode(getTranslate());
addColladaNode(getRotate());
addColladaNode(getBox());
addColladaNode(getSphere());
addColladaNode(getCapsule());
}
/*
* The XML Stag for XML encoding
*/
private static final String XMLTAG = "shape";
/**
* The XML Stag for XML encoding
*/
public static String xmlTag()
{
return XMLTAG;
}
/**
* returns the XML Stag for XML encoding
*/
@Override
public String getXMLTag()
{
return XMLTAG;
}
public void setCapsule(Capsule capsule)
{
this.capsule = capsule;
}
public Capsule getCapsule()
{
return capsule;
}
public void setSphere(Sphere sphere)
{
this.sphere = sphere;
}
public Sphere getSphere()
{
return sphere;
}
public void setBox(Box box)
{
this.box = box;
}
public Box getBox()
{
return box;
}
public void setTranslate(Translate translate)
{
this.translate = translate;
}
public Translate getTranslate()
{
return translate;
}
public void setRotate(Rotate rotate)
{
this.rotate = rotate;
}
public Rotate getRotate()
{
return rotate;
}
}
| lgpl-3.0 |
raffaeleconforti/ResearchCode | graph-algorithms/src/main/java/de/vogella/algorithms/dijkstra/engine/DijkstraAlgorithm.java | 4662 | /*
* Copyright (C) 2018 Raffaele Conforti (www.raffaeleconforti.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, see <http://www.gnu.org/licenses/>.
*/
package de.vogella.algorithms.dijkstra.engine;
import de.vogella.algorithms.dijkstra.model.Edge;
import de.vogella.algorithms.dijkstra.model.Graph;
import de.vogella.algorithms.dijkstra.model.Vertex;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import java.util.*;
public class DijkstraAlgorithm {
private final List<Edge> edges;
private Set<Vertex> settledNodes;
private Set<Vertex> unSettledNodes;
private Map<Vertex, Vertex> predecessors;
private Map<Vertex, Integer> distance;
public DijkstraAlgorithm(Graph graph) {
// create a copy of the array so that we can operate on this array
this.edges = new ArrayList<Edge>(graph.getEdges());
}
public void execute(Vertex source) {
settledNodes = new UnifiedSet<Vertex>();
unSettledNodes = new UnifiedSet<Vertex>();
distance = new UnifiedMap<Vertex, Integer>();
predecessors = new UnifiedMap<Vertex, Vertex>();
distance.put(source, 0);
unSettledNodes.add(source);
while (unSettledNodes.size() > 0) {
Vertex node = getMinimum(unSettledNodes);
settledNodes.add(node);
unSettledNodes.remove(node);
findMinimalDistances(node);
}
}
private void findMinimalDistances(Vertex node) {
List<Vertex> adjacentNodes = getNeighbors(node);
for (Vertex target : adjacentNodes) {
if (getShortestDistance(target) > getShortestDistance(node)
+ getDistance(node, target)) {
distance.put(target, getShortestDistance(node)
+ getDistance(node, target));
predecessors.put(target, node);
unSettledNodes.add(target);
}
}
}
private int getDistance(Vertex node, Vertex target) {
for (Edge edge : edges) {
if (edge.getSource().equals(node)
&& edge.getDestination().equals(target)) {
return edge.getWeight();
}
}
throw new RuntimeException("Should not happen");
}
private List<Vertex> getNeighbors(Vertex node) {
List<Vertex> neighbors = new ArrayList<Vertex>();
for (Edge edge : edges) {
if (edge.getSource().equals(node)
&& !isSettled(edge.getDestination())) {
neighbors.add(edge.getDestination());
}
}
return neighbors;
}
private Vertex getMinimum(Set<Vertex> vertexes) {
Vertex minimum = null;
for (Vertex vertex : vertexes) {
if (minimum == null) {
minimum = vertex;
} else {
if (getShortestDistance(vertex) < getShortestDistance(minimum)) {
minimum = vertex;
}
}
}
return minimum;
}
private boolean isSettled(Vertex vertex) {
return settledNodes.contains(vertex);
}
private int getShortestDistance(Vertex destination) {
Integer d = distance.get(destination);
if (d == null) {
return Integer.MAX_VALUE;
} else {
return d;
}
}
/*
* This method returns the path from the source to the selected target and
* NULL if no path exists
*/
public ArrayList<Vertex> getPath(Vertex target) {
ArrayList<Vertex> path = new ArrayList<Vertex>();
Vertex step = target;
// check if a path exists
if (predecessors.get(step) == null) {
return null;
}
path.add(step);
while (predecessors.get(step) != null) {
step = predecessors.get(step);
path.add(step);
}
// Put it into the correct order
Collections.reverse(path);
return path;
}
} | lgpl-3.0 |
kinglin/satellite-menu | src/android/view/ext/SatelliteAnimationCreator.java | 4115 | package android.view.ext;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.view.ext.R;
/**
* Factory class for creating satellite in/out animations
*
* @author Siyamed SINIR
*
*/
public class SatelliteAnimationCreator {
//ItemÊÕÈëʱµÄ¶¯»
@SuppressLint("NewApi")
public static Animation createItemInAnimation(Context context, int index, long expandDuration, int x, int y){
//Ðýת
RotateAnimation rotate = new RotateAnimation(270, 0,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setInterpolator(context, R.anim.sat_item_in_rotate_interpolator);
rotate.setDuration(expandDuration);
//Î»ÒÆ
TranslateAnimation translate = new TranslateAnimation(x, 0, y, 0);
long delay = 250;
if(expandDuration <= 250){
delay = expandDuration / 3;
}
long duration = 400;
if((expandDuration-delay) > duration){
duration = expandDuration-delay;
}
translate.setDuration(duration);
translate.setStartOffset(delay);
translate.setInterpolator(context, R.anim.sat_item_anticipate_interpolator);
//͸Ã÷¶È
AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
long alphaDuration = 10;
alphaAnimation.setDuration(alphaDuration);
alphaAnimation.setStartOffset((delay + duration) - alphaDuration);
//ÕûÌåÌí¼Ó
AnimationSet animationSet = new AnimationSet(false);
animationSet.setFillAfter(false);
animationSet.setFillBefore(true);
animationSet.setFillEnabled(true);
animationSet.addAnimation(alphaAnimation);
animationSet.addAnimation(rotate);
animationSet.addAnimation(translate);
animationSet.setStartOffset(30*index);
animationSet.start();
animationSet.startNow();
return animationSet;
}
//ItemÕ¹¿ªÊ±µÄ¶¯»
@SuppressLint("NewApi")
public static Animation createItemOutAnimation(Context context, int index, long expandDuration, int x, int y){
//Î»ÒÆ
TranslateAnimation translate = new TranslateAnimation(0, x, 0, y);
translate.setStartOffset(0);
translate.setDuration(expandDuration);
translate.setInterpolator(context, R.anim.sat_item_overshoot_interpolator);
//ÕûÌåÌí¼Ó
AnimationSet animationSet = new AnimationSet(false);
animationSet.setFillAfter(false);
animationSet.setFillBefore(true);
animationSet.setFillEnabled(true);
animationSet.addAnimation(translate);
animationSet.setStartOffset(30*index);
return animationSet;
}
public static Animation createMainButtonAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_main_rotate_left);
}
public static Animation createMainButtonInverseAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_main_rotate_right);
}
//ij¸öitemµã»÷ºóµÄЧ¹û
public static Animation createItemClickAnimation(Context context){
return AnimationUtils.loadAnimation(context, R.anim.sat_item_anim_click);
}
//µÃµ½Ã¿¸öitem×îºóµÄλÖõÄx×ø±ê
public static int getTranslateX(float degree, int distance){
return Double.valueOf(distance * Math.cos(Math.toRadians(degree))).intValue();
}
//µÃµ½Ã¿¸öitem×îºóµÄλÖõÄy×ø±ê
public static int getTranslateY(float degree, int distance){
return Double.valueOf(-1 * distance * Math.sin(Math.toRadians(degree))).intValue();
}
}
| lgpl-3.0 |
384401056/itheima | MobileLottery/src/com/blueice/mobilelottery/utils/MemoryManager.java | 3032 | package com.blueice.mobilelottery.utils;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
/**
* 内存大小判断工具类。
*
*/
public class MemoryManager {
private static final String TAG = "MemoryManager";
private static final int MAXMEMORY=300*1024*1024;//程序运行的最大内存 模拟器(0-16m),真机(16M-32M),这里为了看到效果故意放大了。
/**
* 判断系统是否有足够的内存。有返回true,没有返回false;
* @param context
* @return
*/
public static boolean hasAcailMemory() {
// 获取手机内部空间大小
long memory = getAvailableInternalMemorySize();
Log.i(TAG, memory+"");
if (memory < MAXMEMORY) {
//应用将处于低内存状态下运行
return false;
} else {
return true;
}
}
/**
* 获取手机内部可用空间大小
*
* @return
*/
public static long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();// 获取 Android 数据目录
StatFs stat = new StatFs(path.getPath());// 一个模拟linux的df命令的一个类,获得SD卡和手机内存的使用情况
long blockSize = stat.getBlockSize();// 返回 Int ,大小,以字节为单位,一个文件系统
long availableBlocks = stat.getAvailableBlocks();// 返回 Int ,获取当前可用的存储空间
return availableBlocks * blockSize;
}
/**
* 获取手机内部空间大小
*
* @return
*/
public static long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();// 获取该区域可用的文件系统数
return totalBlocks * blockSize;
}
/**
* 获取手机外部可用空间大小
*
* @return
*/
public static long getAvailableExternalMemorySize() {
if (externalMemoryAvailable()) {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
} else {
throw new RuntimeException("Don't have sdcard.");
}
}
/**
* 获取手机外部空间大小
*
* @return
*/
public static long getTotalExternalMemorySize() {
if (externalMemoryAvailable()) {
File path = Environment.getExternalStorageDirectory();// 获取外部存储目录即 SDCard
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
} else {
throw new RuntimeException("Don't have sdcard.");
}
}
/**
* 外部存储是否可用
*
* @return
*/
public static boolean externalMemoryAvailable() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
}
| lgpl-3.0 |
zenframework/z8 | org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/db/sql/expressions/IsNot.java | 472 | package org.zenframework.z8.server.db.sql.expressions;
import org.zenframework.z8.server.base.table.value.Field;
import org.zenframework.z8.server.db.sql.SqlField;
import org.zenframework.z8.server.db.sql.SqlToken;
import org.zenframework.z8.server.types.sql.sql_bool;
public class IsNot extends Rel {
public IsNot(Field field) {
this(new SqlField(field));
}
public IsNot(SqlToken token) {
super(token, Operation.NotEq, new sql_bool(true));
}
}
| lgpl-3.0 |
dbmalkovsky/CSSBox | src/main/java/org/fit/cssbox/layout/TableCellBox.java | 11888 | /**
* TableCellBox.java
* Copyright (c) 2005-2007 Radek Burget
*
* CSSBox 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.
*
* CSSBox 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 CSSBox. If not, see <http://www.gnu.org/licenses/>.
*
* Created on 29.9.2006, 14:15:23 by burgetr
*/
package org.fit.cssbox.layout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import cz.vutbr.web.css.*;
import org.fit.cssbox.css.HTMLNorm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
/**
* A box that represents a single table cell.
* @author burgetr
*/
public class TableCellBox extends BlockBox
{
private static Logger log = LoggerFactory.getLogger(TableCellBox.class);
protected int colspan;
protected int rowspan;
/** first row of this cell in the body */
protected int row;
/** first collumn of this cell in the row */
protected int column;
/** the owner row */
protected TableRowBox ownerRow;
/** the owner column */
protected TableColumn ownerColumn;
/** relative width [%] when used */
protected int percent;
/** vertical content offset produced by vertical alignment */
protected int coffset;
//====================================================================================
/**
* Create a new table cell
*/
public TableCellBox(Element n, Graphics2D g, VisualContext ctx)
{
super(n, g, ctx);
isblock = true;
loadAttributes();
fleft = new FloatList(this);
fright = new FloatList(this);
coffset = 0;
}
/**
* Create a new table cell from an inline box
*/
public TableCellBox(InlineBox src)
{
super(src);
isblock = true;
loadAttributes();
fleft = new FloatList(this);
fright = new FloatList(this);
coffset = 0;
}
/**
* @return the column span
*/
public int getColspan()
{
return colspan;
}
/**
* @return the row span
*/
public int getRowspan()
{
return rowspan;
}
public void setColspan(int colspan)
{
this.colspan = colspan;
}
public void setRowspan(int rowspan)
{
this.rowspan = rowspan;
}
/**
* @return the row of this cell in the table body
*/
public int getRow()
{
return row;
}
/**
* @return the column of this cell in the row
*/
public int getColumn()
{
return column;
}
/**
* @return the ownerRow
*/
public TableRowBox getOwnerRow()
{
return ownerRow;
}
/**
* @param ownerRow the ownerRow to set
*/
public void setOwnerRow(TableRowBox ownerRow)
{
this.ownerRow = ownerRow;
}
/**
* @return the ownerColumn
*/
public TableColumn getOwnerColumn()
{
return ownerColumn;
}
/**
* @param ownerColumn the ownerColumn to set
*/
public void setOwnerColumn(TableColumn ownerColumn)
{
this.ownerColumn = ownerColumn;
}
/**
* Set the index of the first row and column of this cell in the row
* @param column the column index to set
* @param row the row index to set
*/
public void setCellPosition(int column, int row)
{
this.column = column;
this.row = row;
}
/**
* Set the total width of the cell. The content width is computed automatically.
* @param width the width to be set
*/
public void setWidth(int width)
{
content.width = width - border.left - padding.left - padding.right - border.right;
bounds.width = width;
wset = true;
updateChildSizes();
}
/**
* Set the total width of the cell. The content width is computed automatically.
* @param height the height to be set
*/
public void setHeight(int height)
{
content.height = height - border.top - padding.top - padding.bottom - border.bottom;
bounds.height = height;
hset = true;
}
/**
* @return the percentage when the width is specified relatively
*/
public int getPercent()
{
return percent;
}
@Override
public String toString()
{
return super.toString() + "[" + column + "," + row + "]";
}
//====================================================================================
/**
* Applies the vertical alignment after the row height is computed. Moves all child boxes
* according to the vertical-align value of the cell and the difference between the original
* height (after the cell layout) and the new (required by the row) height.
* @param origHeight the original cell height obtained from the content layout
* @param newHeight the cell height required by the row. It should be greater or equal to origHeight.
* @param baseline the row's baseline offset
*/
public void applyVerticalAlign(int origHeight, int newHeight, int baseline)
{
int yofs = 0;
CSSProperty.VerticalAlign valign = style.getProperty("vertical-align");
if (valign == null) valign = CSSProperty.VerticalAlign.MIDDLE;
switch (valign)
{
case TOP: yofs = 0;
break;
case BOTTOM: yofs = newHeight - origHeight;
break;
case MIDDLE: yofs = (newHeight - origHeight) / 2;
break;
default: yofs = baseline - getFirstInlineBoxBaseline(); //all other values should behave as BASELINE
break;
}
if (yofs > 0)
coffset = yofs;
}
@Override
public int getAbsoluteContentY()
{
//apply the possible content offset caused by vertical alignment
return super.getAbsoluteContentY() + coffset;
}
@Override
public void computeEfficientMargins()
{
//no margin collapsing with the contents for table cells
emargin = new LengthSet(margin);
}
@Override
public int getMinimalWidth()
{
int ret = getMinimalContentWidth();
if (!wrelative && hasFixedWidth() && content.width > ret)
ret = content.width;
ret += margin.left + padding.left + border.left +
margin.right + padding.right + border.right;
return ret;
}
@Override
public int getMaximalWidth()
{
int ret = getMaximalContentWidth();
/*if (!wrelative && hasFixedWidth())
ret = content.width;*/
//increase by margin, padding, border
ret += margin.left + padding.left + border.left +
margin.right + padding.right + border.right;
return ret;
}
@Override
protected void loadSizes(boolean update)
{
CSSDecoder dec = new CSSDecoder(ctx);
//containing box sizes
int contw = getContainingBlock().width;
//Borders
if (!update) //borders needn't be updated
loadBorders(dec, contw);
//Padding
loadPadding(dec, contw);
//Content and margins
if (!update)
{
content = new Dimension(0, 0);
margin = new LengthSet();
emargin = new LengthSet();
min_size = new Dimension(-1, -1);
max_size = new Dimension(-1, -1);
coords = new LengthSet();
}
//Load the width if set
CSSProperty.Width wprop = null;
TermLengthOrPercent width = null;
String widthattr = HTMLNorm.getAttribute(getElement(), "width"); //try to load from attribute
if (!widthattr.equals(""))
{
width = HTMLNorm.createLengthOrPercent(widthattr);
if (width != null)
wprop = width.isPercentage() ? CSSProperty.Width.percentage : CSSProperty.Width.length;
}
else //no attribute set - use the style
{
wprop = style.getProperty("width");
width = getLengthValue("width");
}
if (wprop == null || wprop == CSSProperty.Width.AUTO)
{
wset = false;
}
else
{
wset = true;
if (!update)
content.width = dec.getLength(width, false, 0, 0, contw);
if (width.isPercentage())
{
wrelative = true;
percent = Math.round(width.getValue());
if (percent == 0)
wrelative = false; //consider 0% as absolute 0
}
}
//Load the height if set
String heightattr = HTMLNorm.getAttribute(getElement(), "height"); //try to load from attribute
CSSProperty.Height hprop = null;
TermLengthOrPercent height = null;
if (!heightattr.equals(""))
{
height = HTMLNorm.createLengthOrPercent(widthattr);
if (height != null)
hprop = height.isPercentage() ? CSSProperty.Height.percentage : CSSProperty.Height.length;
}
else
{
hprop = style.getProperty("height");
height = getLengthValue("height");
}
boolean hauto = (hprop == null || hprop == CSSProperty.Height.AUTO);
if (getContainingBlockBox().hasFixedWidth())
{
hset = !hauto;
if (!update)
content.height = dec.getLength(height, hauto, 0, 0, getContainingBlock().width);
}
else
{
hset = (!hauto && !height.isPercentage());
if (!update)
content.height = dec.getLength(height, hauto, 0, 0, 0);
}
}
@Override
public boolean hasFixedWidth()
{
return true; //the width is set by the column
}
@Override
public boolean canIncreaseWidth()
{
return true;
}
@Override
public Color getBgcolor()
{
//if no background is specified for the cell, we try to use the row, row group, column, column group
Color bg = bgcolor;
if (bg == null)
bg = getOwnerRow().getBgcolor();
if (bg == null)
bg = getOwnerColumn().getBgcolor();
if (bg == null)
bg = getOwnerRow().getOwnerBody().getBgcolor();
return bg;
}
@Override
protected boolean separatedFromTop(ElementBox box)
{
return true;
}
@Override
protected boolean separatedFromBottom(ElementBox box)
{
return true;
}
@Override
protected boolean encloseFloats()
{
return true; //table cell always encloses contained floats
}
/**
* Loads the important values from the element attributes.
*/
protected void loadAttributes()
{
try {
if (!HTMLNorm.getAttribute(el, "colspan").equals(""))
colspan = Integer.parseInt(HTMLNorm.getAttribute(el, "colspan"));
else
colspan = 1;
if (!HTMLNorm.getAttribute(el, "rowspan").equals(""))
rowspan = Integer.parseInt(HTMLNorm.getAttribute(el, "rowspan"));
else
rowspan = 1;
} catch (NumberFormatException e) {
log.warn("Invalid width value: " + e.getMessage());
}
}
}
| lgpl-3.0 |
subes/invesdwin-nowicket | invesdwin-nowicket-examples/granatasoft-remotelist-parent/granatasoft-remotelist-website/src/main/java/com/granatasoft/remotelist/website/pages/remotelist/categoryrow/CategoryRow.java | 2287 | package com.granatasoft.remotelist.website.pages.remotelist.categoryrow;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.concurrent.NotThreadSafe;
import javax.inject.Inject;
import org.apache.wicket.request.resource.ByteArrayResource;
import org.apache.wicket.request.resource.IResource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Configurable;
import com.granatasoft.remotelist.persistence.ApplicationInstanceDao;
import com.granatasoft.remotelist.persistence.Category;
import com.granatasoft.remotelist.website.pages.remotelist.applicationinstancerow.ApplicationInstanceRow;
import de.invesdwin.norva.beanpath.annotation.Hidden;
import de.invesdwin.nowicket.generated.markup.annotation.GeneratedMarkup;
import de.invesdwin.util.bean.AValueObject;
@NotThreadSafe
@GeneratedMarkup
@Configurable
public class CategoryRow extends AValueObject implements InitializingBean {
private final Category category;
private List<ApplicationInstanceRow> applicationInstances;
@Inject
private transient ApplicationInstanceDao applicationInstanceRepository;
public CategoryRow(final Category c) {
this.category = c;
}
@Override
public void afterPropertiesSet() throws Exception {
this.applicationInstances = applicationInstanceRepository.findByCategory(category)
.stream()
.map(a -> new ApplicationInstanceRow(a))
.sorted()
.collect(Collectors.toList());
}
@Hidden
public String getCategoryName() {
return this.category.getName();
}
public List<ApplicationInstanceRow> getApplicationInstances() {
return applicationInstances;
}
@Hidden
public IResource getCategoryLogo() {
if (category.getLogo() != null) {
return new ByteArrayResource(null, category.getLogo(), category.getLogoFileName());
}
return null;
}
@Override
public int compareTo(final Object o) {
if (o instanceof CategoryRow) {
final CategoryRow cO = (CategoryRow) o;
return getCategoryName().compareTo(cO.getCategoryName());
} else {
return 1;
}
}
}
| lgpl-3.0 |
accord-net/java | Catalano.Math/src/Catalano/Math/Geometry/IShapeOptimizer.java | 1673 | // Catalano Math Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2013
// diego.catalano at live.com
//
// Copyright © Andrew Kirillov, 2005-2009
// andrew.kirillov@aforgenet.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.
//
// 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 Catalano.Math.Geometry;
import Catalano.Core.IntPoint;
import java.util.ArrayList;
/**
* Interface for shape optimizing algorithms.
*
* <para>The shape optimizing algorithms can be useful in conjunction with such algorithms
* like convex hull searching, which usually may provide many hull points, where some
* of them are insignificant and could be removed.</para>
* @author Diego Catalano
*/
public interface IShapeOptimizer {
/**
* Optimize specified shape.
* @param shape Shape to be optimized.
* @return Returns final optimized shape, which may have reduced amount of points.
*/
ArrayList<IntPoint> OptimizeShape( ArrayList<IntPoint> shape );
}
| lgpl-3.0 |
Putnami/putnami-web-toolkit | doc/src/main/java/fr/putnami/pwt/doc/client/social/widget/SocialBar.java | 1326 | /**
* This file is part of pwt.
*
* pwt 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.
*
* pwt 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 pwt. If not,
* see <http://www.gnu.org/licenses/>.
*/
package fr.putnami.pwt.doc.client.social.widget;
import fr.putnami.pwt.core.theme.client.CssStyle;
import fr.putnami.pwt.core.widget.client.ButtonGroup;
import fr.putnami.pwt.core.widget.client.base.SimpleStyle;
import fr.putnami.pwt.core.widget.client.util.StyleUtils;
public class SocialBar extends ButtonGroup {
private static final CssStyle STYLE_SOCIAL_BAR = new SimpleStyle("social-bar");
public SocialBar() {
StyleUtils.addStyle(this, SocialBar.STYLE_SOCIAL_BAR);
this.add(new TwitterButton());
this.add(new FacebookButton());
this.add(new GooglePlusButton());
this.add(new LinkedInButton());
this.add(new GitHubButton());
}
}
| lgpl-3.0 |
ceharris/SchemaCrawler | schemacrawler-api/src/main/java/schemacrawler/utility/SchemaCrawlerUtility.java | 2500 | /*
*
* SchemaCrawler
* http://www.schemacrawler.com
* Copyright (c) 2000-2015, Sualeh Fatehi.
*
* 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 schemacrawler.utility;
import java.sql.Connection;
import java.sql.ResultSet;
import schemacrawler.crawl.SchemaCrawler;
import schemacrawler.schema.Catalog;
import schemacrawler.schema.ResultsColumns;
import schemacrawler.schemacrawler.DatabaseSpecificOverrideOptions;
import schemacrawler.schemacrawler.SchemaCrawlerException;
import schemacrawler.schemacrawler.SchemaCrawlerOptions;
/**
* SchemaCrawler utility methods.
*
* @author sfatehi
*/
public final class SchemaCrawlerUtility
{
public static Catalog getCatalog(final Connection connection,
final DatabaseSpecificOverrideOptions databaseSpecificOverrideOptions,
final SchemaCrawlerOptions schemaCrawlerOptions)
throws SchemaCrawlerException
{
final SchemaCrawler schemaCrawler = new SchemaCrawler(connection,
databaseSpecificOverrideOptions);
final Catalog catalog = schemaCrawler.crawl(schemaCrawlerOptions);
return catalog;
}
public static Catalog getCatalog(final Connection connection,
final SchemaCrawlerOptions schemaCrawlerOptions)
throws SchemaCrawlerException
{
return getCatalog(connection,
new DatabaseSpecificOverrideOptions(),
schemaCrawlerOptions);
}
public static ResultsColumns getResultColumns(final ResultSet resultSet)
{
return SchemaCrawler.getResultColumns(resultSet);
}
private SchemaCrawlerUtility()
{
// Prevent instantiation
}
}
| lgpl-3.0 |
almondtools/compilerutils | src/main/java/net/amygdalum/util/text/linkeddawg/LinkedCharDawgCompiler.java | 1134 | package net.amygdalum.util.text.linkeddawg;
import net.amygdalum.util.text.CharDawg;
import net.amygdalum.util.text.CharWordGraphCompiler;
import net.amygdalum.util.text.CharNode;
import net.amygdalum.util.text.NodeResolver;
public class LinkedCharDawgCompiler<T> implements CharWordGraphCompiler<T, CharDawg<T>> {
@Override
public CharNode<T> create() {
return new CharGenericNode<>();
}
@Override
public CharDawg<T> build(CharNode<T> node) {
return new LinkedCharDawg<>(node);
}
@Override
public NodeResolver<CharNode<T>> resolver() {
return new CharNodesCompiler<T>() {
protected CharNode<T> compileNode(CharNode<T> node) {
CharNode<T> optimizedNode = CharTerminalNode.buildNodeFrom(node, this);
if (optimizedNode != null) {
return optimizedNode;
}
optimizedNode = CharArrayNode.buildNodeFrom(node, this);
if (optimizedNode != null) {
return optimizedNode;
}
optimizedNode = CharMapNode.buildNodeFrom(node, this);
if (optimizedNode != null) {
return optimizedNode;
}
return null;
}
@Override
public void link(CharNode<T> node) {
}
};
}
} | lgpl-3.0 |
Godin/sonar | sonar-ws-generator/src/main/java/org/sonarqube/wsgenerator/ApiDefinitionDownloader.java | 2172 | /*
* 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.sonarqube.wsgenerator;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.OrchestratorBuilder;
import com.sonar.orchestrator.http.HttpCall;
import com.sonar.orchestrator.http.HttpResponse;
import com.sonar.orchestrator.locator.FileLocation;
import java.io.File;
import static com.sonar.orchestrator.container.Edition.COMMUNITY;
public class ApiDefinitionDownloader {
public static void main(String[] args) {
System.out.println(downloadApiDefinition());
}
public static String downloadApiDefinition() {
OrchestratorBuilder builder = Orchestrator.builderEnv();
builder.setEdition(COMMUNITY);
builder.setZipFile(FileLocation.byWildcardMavenFilename(new File("../sonar-application/build/distributions"), "sonar-application-*.zip").getFile())
.setOrchestratorProperty("orchestrator.workspaceDir", "build");
Orchestrator orchestrator = builder
// Enable organizations ws
.setServerProperty("sonar.sonarcloud.enabled", "true")
.build();
orchestrator.start();
try {
HttpCall httpCall = orchestrator.getServer().newHttpCall("api/webservices/list").setParam("include_internals", "true");
HttpResponse response = httpCall.execute();
return response.getBodyAsString();
} finally {
orchestrator.stop();
}
}
}
| lgpl-3.0 |
klipdev/SpiderGps | workspace/SpiderGps/src3p/org/klipdev/spidergps3p/kml/AbstractFeatureType.java | 9571 | //
// Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.8-b130911.1802
// Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source.
// Généré le : 2015.10.08 à 11:14:04 PM CEST
//
package org.klipdev.spidergps3p.kml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.klipdev.spidergps3p.atom.AtomPersonConstruct;
import org.klipdev.spidergps3p.atom.Link;
import org.klipdev.spidergps3p.xal.AddressDetails;
/**
* <p>Classe Java pour AbstractFeatureType complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="AbstractFeatureType">
* <complexContent>
* <extension base="{http://www.opengis.net/kml/2.2}AbstractObjectType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}name" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}visibility" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}open" minOccurs="0"/>
* <element ref="{http://www.w3.org/2005/Atom}author" minOccurs="0"/>
* <element ref="{http://www.w3.org/2005/Atom}link" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}address" minOccurs="0"/>
* <element ref="{urn:oasis:names:tc:ciq:xsdschema:xAL:2.0}AddressDetails" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}phoneNumber" minOccurs="0"/>
* <choice>
* <element ref="{http://www.opengis.net/kml/2.2}Snippet" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}snippet" minOccurs="0"/>
* </choice>
* <element ref="{http://www.opengis.net/kml/2.2}description" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}AbstractViewGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}AbstractTimePrimitiveGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}styleUrl" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}AbstractStyleSelectorGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}Region" minOccurs="0"/>
* <choice>
* <element ref="{http://www.opengis.net/kml/2.2}Metadata" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}ExtendedData" minOccurs="0"/>
* </choice>
* <element ref="{http://www.opengis.net/kml/2.2}AbstractFeatureSimpleExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}AbstractFeatureObjectExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AbstractFeatureType", propOrder = {
"rest"
})
@XmlSeeAlso({
PlacemarkType.class,
NetworkLinkType.class,
AbstractContainerType.class,
AbstractOverlayType.class
})
public abstract class AbstractFeatureType
extends AbstractObjectType
{
@XmlElementRefs({
@XmlElementRef(name = "Metadata", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "address", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AbstractTimePrimitiveGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = Link.class, required = false),
@XmlElementRef(name = "description", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "visibility", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "snippet", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ExtendedData", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AbstractFeatureObjectExtensionGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "name", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "styleUrl", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AbstractFeatureSimpleExtensionGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "phoneNumber", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Snippet", namespace = "http://www.opengis.net/kml/2.2", type = SnippetDeprecated.class, required = false),
@XmlElementRef(name = "AbstractViewGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "Region", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AddressDetails", namespace = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0", type = JAXBElement.class, required = false),
@XmlElementRef(name = "AbstractStyleSelectorGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false),
@XmlElementRef(name = "open", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false)
})
protected List<Object> rest;
/**
* Obtient le reste du modèle de contenu.
*
* <p>
* Vous obtenez la propriété "catch-all" pour la raison suivante :
* Le nom de champ "Snippet" est utilisé par deux parties différentes d'un schéma. Reportez-vous à :
* ligne 321 sur file:/Users/Christophe/Documents/Dev/SpiderGps/workspace/SpiderGps/src/ogckml22.xsd
* ligne 320 sur file:/Users/Christophe/Documents/Dev/SpiderGps/workspace/SpiderGps/src/ogckml22.xsd
* <p>
* Pour vous débarrasser de cette propriété, appliquez une personnalisation de propriété à l'une
* des deux déclarations suivantes afin de modifier leurs noms :
* Gets the value of the rest property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rest property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRest().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link MetadataType }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link StyleType }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link CameraType }{@code >}
* {@link JAXBElement }{@code <}{@link StyleMapType }{@code >}
* {@link JAXBElement }{@code <}{@link AtomPersonConstruct }{@code >}
* {@link JAXBElement }{@code <}{@link TimeSpanType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractViewType }{@code >}
* {@link JAXBElement }{@code <}{@link AddressDetails }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractStyleSelectorType }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractTimePrimitiveType }{@code >}
* {@link Link }
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
* {@link JAXBElement }{@code <}{@link ExtendedDataType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractObjectType }{@code >}
* {@link JAXBElement }{@code <}{@link String }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
* {@link JAXBElement }{@code <}{@link LookAtType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeStampType }{@code >}
* {@link SnippetDeprecated }
* {@link JAXBElement }{@code <}{@link RegionType }{@code >}
* {@link JAXBElement }{@code <}{@link Boolean }{@code >}
*
*
*/
public List<Object> getRest() {
if (rest == null) {
rest = new ArrayList<Object>();
}
return this.rest;
}
}
| lgpl-3.0 |
ltettoni/logic2j | src/test/java/org/logic2j/core/library/impl/AdHocLibraryForTesting.java | 4016 | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
import static org.logic2j.engine.solver.Continuation.CONTINUE;
import java.util.ArrayList;
import java.util.List;
import org.logic2j.core.api.library.annotation.Predicate;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.model.Var;
import org.logic2j.engine.solver.Continuation;
import org.logic2j.engine.unify.UnifyContext;
/**
* A small ad-hoc implementation of a {@link org.logic2j.core.api.library.PLibrary} just for testing.
*/
public class AdHocLibraryForTesting extends LibraryBase {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AdHocLibraryForTesting.class);
public AdHocLibraryForTesting(PrologImplementation theProlog) {
super(theProlog);
}
/**
* Classic production of several solutions.
*
* @param currentVars
* @param theLowerBound
* @param theIterable
* @param theUpperBound
* @return
*/
@Predicate
public int int_range_classic(UnifyContext currentVars, Object theLowerBound, Object theIterable, Object theUpperBound) {
final Object lowerBound = currentVars.reify(theLowerBound);
final Object upperBound = currentVars.reify(theUpperBound);
ensureBindingIsNotAFreeVar(lowerBound, "int_range_classic/3", 0);
ensureBindingIsNotAFreeVar(upperBound, "int_range_classic/3", 2);
final int lower = ((Number) lowerBound).intValue();
final int upper = ((Number) upperBound).intValue();
for (int iter = lower; iter < upper; iter++) {
logger.info("{} is going to unify an notify one solution: {}", this, iter);
final int continuation = unifyAndNotify(currentVars, theIterable, iter);
if (continuation != Continuation.CONTINUE) {
return continuation;
}
}
return Continuation.CONTINUE;
}
/**
* Special production of several solutions in one go.
*
* @param currentVars
* @param theMinBound
* @param theIterable
* @param theMaxBound Upper bound + 1 (ie theIterable will go up to theMaxBound-1)
* @return
*/
@Predicate
public int int_range_multi(UnifyContext currentVars, Object theMinBound, final Object theIterable, Object theMaxBound) {
final Object minBound = currentVars.reify(theMinBound);
final Object iterating = currentVars.reify(theIterable);
final Object maxBound = currentVars.reify(theMaxBound);
ensureBindingIsNotAFreeVar(minBound, "int_range_multi/3", 0);
ensureBindingIsNotAFreeVar(maxBound, "int_range_multi/3", 2);
final int min = ((Number) minBound).intValue();
final int max = ((Number) maxBound).intValue();
if (iterating instanceof Var<?>) {
final List<Integer> values = new ArrayList<>();
for (int val = min; val < max; val++) {
values.add(val);
}
logger.info("{} is going to notify solutions: {}", this, values);
for (int increment = min; increment < max; increment++) {
final int cont = unifyAndNotify(currentVars, iterating, increment);
if (cont != CONTINUE) {
return cont;
}
}
} else {
// Check
final int iter = ((Number) iterating).intValue();
if (min <= iter && iter < max) {
return notifySolution(currentVars);
}
}
return Continuation.CONTINUE;
}
}
| lgpl-3.0 |
Godin/sonar | sonar-plugin-api/src/test/java/org/sonar/api/utils/DateUtilsTest.java | 6484 | /*
* 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.api.utils;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Date;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.utils.DateUtils.parseDate;
import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
@RunWith(DataProviderRunner.class)
public class DateUtilsTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void parseDate_valid_format() {
Date date = DateUtils.parseDate("2010-05-18");
assertThat(date.getDate()).isEqualTo(18);
}
@Test
public void parseDate_not_valid_format() {
expectedException.expect(MessageException.class);
DateUtils.parseDate("2010/05/18");
}
@Test
public void parseDate_not_lenient() {
expectedException.expect(MessageException.class);
DateUtils.parseDate("2010-13-18");
}
@Test
public void parseDateQuietly() {
assertThat(DateUtils.parseDateQuietly("2010/05/18")).isNull();
Date date = DateUtils.parseDateQuietly("2010-05-18");
assertThat(date.getDate()).isEqualTo(18);
}
@Test
public void parseDate_fail_if_additional_characters() {
expectedException.expect(MessageException.class);
DateUtils.parseDate("1986-12-04foo");
}
@Test
public void parseDateTime_valid_format() {
Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
assertThat(date.getMinutes()).isEqualTo(50);
}
@Test
public void parseDateTime_not_valid_format() {
expectedException.expect(MessageException.class);
DateUtils.parseDate("2010/05/18 10:55");
}
@Test
public void parseDateTime_fail_if_additional_characters() {
expectedException.expect(MessageException.class);
DateUtils.parseDateTime("1986-12-04T01:02:03+0300foo");
}
@Test
public void parseDateTimeQuietly() {
assertThat(DateUtils.parseDateTimeQuietly("2010/05/18 10:55")).isNull();
Date date = DateUtils.parseDateTimeQuietly("2010-05-18T15:50:45+0100");
assertThat(date.getMinutes()).isEqualTo(50);
}
@Test
public void shouldFormatDate() {
assertThat(DateUtils.formatDate(new Date())).startsWith("20");
assertThat(DateUtils.formatDate(new Date())).hasSize(10);
}
@Test
public void shouldFormatDateTime() {
assertThat(DateUtils.formatDateTime(new Date())).startsWith("20");
assertThat(DateUtils.formatDateTime(new Date()).length()).isGreaterThan(20);
}
@Test
public void shouldFormatDateTime_with_long() {
assertThat(DateUtils.formatDateTime(System.currentTimeMillis())).startsWith("20");
assertThat(DateUtils.formatDateTime(System.currentTimeMillis()).length()).isGreaterThan(20);
}
@Test
public void format_date_time_null_safe() {
assertThat(DateUtils.formatDateTimeNullSafe(new Date())).startsWith("20");
assertThat(DateUtils.formatDateTimeNullSafe(new Date()).length()).isGreaterThan(20);
assertThat(DateUtils.formatDateTimeNullSafe(null)).isEmpty();
}
@Test
public void long_to_date() {
Date date = new Date();
assertThat(DateUtils.longToDate(date.getTime())).isEqualTo(date);
assertThat(DateUtils.longToDate(null)).isNull();
}
@Test
public void date_to_long() {
Date date = new Date();
assertThat(DateUtils.dateToLong(date)).isEqualTo(date.getTime());
assertThat(DateUtils.dateToLong(null)).isEqualTo(null);
}
@DataProvider
public static Object[][] date_times() {
return new Object[][] {
{"2014-05-27", parseDate("2014-05-27")},
{"2014-05-27T15:50:45+0100", parseDateTime("2014-05-27T15:50:45+0100")},
{null, null}
};
}
@Test
@UseDataProvider("date_times")
public void param_as__date_time(String stringDate, Date expectedDate) {
assertThat(parseDateOrDateTime(stringDate)).isEqualTo(expectedDate);
assertThat(parseStartingDateOrDateTime(stringDate)).isEqualTo(expectedDate);
}
@DataProvider
public static Object[][] ending_date_times() {
return new Object[][] {
{"2014-05-27", parseDate("2014-05-28")},
{"2014-05-27T15:50:45+0100", parseDateTime("2014-05-27T15:50:45+0100")},
{null, null}
};
}
@Test
@UseDataProvider("ending_date_times")
public void param_as_ending_date_time(String stringDate, Date expectedDate) {
assertThat(parseEndingDateOrDateTime(stringDate)).isEqualTo(expectedDate);
}
@Test
public void fail_when_param_as_date_or_datetime_not_a_datetime() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Date 'polop' cannot be parsed as either a date or date+time");
parseDateOrDateTime("polop");
}
@Test
public void fail_when_param_as_starting_datetime_not_a_datetime() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Date 'polop' cannot be parsed as either a date or date+time");
parseStartingDateOrDateTime("polop");
}
@Test
public void fail_when_param_as_ending_datetime_not_a_datetime() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("'polop' cannot be parsed as either a date or date+time");
parseEndingDateOrDateTime("polop");
}
}
| lgpl-3.0 |
trejkaz/hex-components | interpreter/src/main/java/org/trypticon/hex/interpreters/InterpreterInfo.java | 3040 | /*
* Hex - a hex viewer and annotator
* Copyright (C) 2009-2014,2016-2017,2021 Hakanai, Hex Project
*
* 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.trypticon.hex.interpreters;
import org.trypticon.hex.util.Format;
import org.trypticon.hex.util.Localisable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
* Holds information about an interpreter.
*
* @author trejkaz
*/
public interface InterpreterInfo extends Localisable {
/**
* Gets the list of options supported by the interpreter.
* If there are no options this should return an empty list.
*
* @return the list of supported options.
*/
List<Option<?>> getOptions();
/**
* Creates a new interpreter with the provided options.
*
* @param options the options.
* @return the interpreter.
*/
Interpreter<?> create(Map<String, Object> options);
/**
* Class describing options which can be passed to the interpreter.
*/
class Option<T> implements Localisable {
private final String name;
private final Class<T> type;
private final boolean required;
private final List<T> values;
public Option(String name, Class<T> type, boolean required) {
this(name, type, required, Collections.<T>emptyList());
}
public Option(String name, Class<T> type, boolean required, List<T> values) {
this.name = name;
this.type = type;
this.required = required;
this.values = Collections.unmodifiableList(new ArrayList<>(values));
}
public String getName() {
return name;
}
@Override
public String toLocalisedString(Format style) {
return toLocalisedString(style, Locale.getDefault());
}
@Override
public String toLocalisedString(Format style, Locale locale) {
return ResourceBundle.getBundle("org/trypticon/hex/interpreters/Bundle", locale)
.getString("Option." + getName());
}
public Class<?> getType() {
return type;
}
public boolean isRequired() {
return required;
}
public List<T> getValues() {
return values;
}
}
}
| lgpl-3.0 |
Realmcraft/Vault | src/net/milkbowl/vault/economy/plugins/Economy_eWallet.java | 8714 | /* This file is part of Vault.
Vault 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.
Vault 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 Vault. If not, see <http://www.gnu.org/licenses/>.
*/
package net.milkbowl.vault.economy.plugins;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import me.ethan.eWallet.ECO;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import net.milkbowl.vault.economy.EconomyResponse.ResponseType;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
public class Economy_eWallet implements Economy {
private static final Logger log = Logger.getLogger("Minecraft");
private final String name = "eWallet";
private Plugin plugin = null;
private ECO econ = null;
public Economy_eWallet(Plugin plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(new EconomyServerListener(this), plugin);
// Load Plugin in case it was loaded before
if (econ == null) {
Plugin econ = plugin.getServer().getPluginManager().getPlugin("eWallet");
if (econ != null && econ.isEnabled()) {
this.econ = (ECO) econ;
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), name));
}
}
}
public class EconomyServerListener implements Listener {
Economy_eWallet economy = null;
public EconomyServerListener(Economy_eWallet economy) {
this.economy = economy;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) {
if (economy.econ == null) {
Plugin eco = plugin.getServer().getPluginManager().getPlugin("eWallet");
if (eco != null) {
economy.econ = (ECO) eco;
log.info(String.format("[%s][Economy] %s hooked.", plugin.getDescription().getName(), economy.name));
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event) {
if (economy.econ != null) {
if (event.getPlugin().getDescription().getName().equals("eWallet")) {
economy.econ = null;
log.info(String.format("[%s][Economy] %s unhooked.", plugin.getDescription().getName(), economy.name));
}
}
}
}
@Override
public boolean isEnabled() {
return this.econ != null;
}
@Override
public String getName() {
return name;
}
@Override
public String format(double amount) {
amount = Math.ceil(amount);
if (amount == 1) {
return String.format("%d %s", (int)amount, econ.singularCurrency);
} else {
return String.format("%d %s", (int)amount, econ.pluralCurrency);
}
}
@Override
public String currencyNameSingular() {
return econ.singularCurrency;
}
@Override
public String currencyNamePlural() {
return econ.pluralCurrency;
}
@Override
public double getBalance(String playerName) {
Integer i = econ.getMoney(playerName);
return i == null ? 0 : i;
}
@Override
public boolean has(String playerName, double amount) {
return getBalance(playerName) >= Math.ceil(amount);
}
@Override
public EconomyResponse withdrawPlayer(String playerName, double amount) {
double balance = getBalance(playerName);
amount = Math.ceil(amount);
if (amount < 0) {
return new EconomyResponse(0, balance, ResponseType.FAILURE, "Cannot withdraw negative funds");
} else if (balance >= amount) {
double finalBalance = balance - amount;
econ.takeMoney(playerName, (int) amount);
return new EconomyResponse(amount, finalBalance, ResponseType.SUCCESS, null);
} else {
return new EconomyResponse(0, balance, ResponseType.FAILURE, "Insufficient funds");
}
}
@Override
public EconomyResponse depositPlayer(String playerName, double amount) {
double balance = getBalance(playerName);
amount = Math.ceil(amount);
if (amount < 0) {
return new EconomyResponse(0, balance, ResponseType.FAILURE, "Cannot deposit negative funds");
} else {
balance += amount;
econ.giveMoney(playerName, (int) amount);
return new EconomyResponse(amount, balance, ResponseType.SUCCESS, null);
}
}
@Override
public EconomyResponse createBank(String name, String player) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse deleteBank(String name) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse bankHas(String name, double amount) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse bankWithdraw(String name, double amount) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse bankDeposit(String name, double amount) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse isBankOwner(String name, String playerName) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse isBankMember(String name, String playerName) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public EconomyResponse bankBalance(String name) {
return new EconomyResponse(0, 0, ResponseType.NOT_IMPLEMENTED, "eWallet does not support bank accounts!");
}
@Override
public List<String> getBanks() {
return new ArrayList<String>();
}
@Override
public boolean hasBankSupport() {
return false;
}
@Override
public boolean hasAccount(String playerName) {
return econ.hasAccount(playerName);
}
@Override
public boolean createPlayerAccount(String playerName) {
if (hasAccount(playerName)) {
return false;
}
econ.createAccount(playerName, 0);
return true;
}
@Override
public int fractionalDigits() {
return 0;
}
@Override
public boolean hasAccount(String playerName, String worldName) {
return hasAccount(playerName);
}
@Override
public double getBalance(String playerName, String world) {
return getBalance(playerName);
}
@Override
public boolean has(String playerName, String worldName, double amount) {
return has(playerName, amount);
}
@Override
public EconomyResponse withdrawPlayer(String playerName, String worldName, double amount) {
return withdrawPlayer(playerName, amount);
}
@Override
public EconomyResponse depositPlayer(String playerName, String worldName, double amount) {
return depositPlayer(playerName, amount);
}
@Override
public boolean createPlayerAccount(String playerName, String worldName) {
return createPlayerAccount(playerName);
}
}
| lgpl-3.0 |
trentlarson/Schedule-Forecast | core/src/main/java/com/trentlarson/forecast/core/scheduling/TimeSchedule.java | 86519 | package com.trentlarson.forecast.core.scheduling;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import com.trentlarson.forecast.core.helper.DateUtil;
public class TimeSchedule {
public static final double MAX_WORKHOURS_PER_WORKDAY = 8.0;
private static final int WORKDAYS_PER_WEEK = 5;
public static final double TYPICAL_INDIVIDUAL_WORKHOURS_PER_WORKWEEK = WORKDAYS_PER_WEEK * MAX_WORKHOURS_PER_WORKDAY;
private static final int FIRST_HOUR_OF_WORKDAY = 8;
private static final java.text.SimpleDateFormat WEEKDAY_DATE_TIME = new java.text.SimpleDateFormat("EEE MMM dd hh:mm a");
private static final java.text.SimpleDateFormat WEEKDAY_DATE = new java.text.SimpleDateFormat("EEE MMM dd");
private static final java.text.SimpleDateFormat SLASH_DATE = new java.text.SimpleDateFormat("yyyy/MM/dd");
// this has no spaces so table formatting in HTML wraps consistently (ug)
private static final java.text.SimpleDateFormat SLASH_TIME = new java.text.SimpleDateFormat("yyyy.MM.dd'@'HH:mm");
// OK, I'd like to shorten these strings (eg. to just "scheduling.Time"),
// but then the Jira page to set logging levels doesn't work. Any ideas? TNL
public static final Logger log4jLog = Logger.getLogger("com.trentlarson.forecast.core.scheduling.TimeSchedule");
public static final Logger fnebLog = Logger.getLogger("com.trentlarson.forecast.core.scheduling.TimeSchedule.-FNEB--"); // findNextEstBegin
public static final Logger fdiwwLog = Logger.getLogger("com.trentlarson.forecast.core.scheduling.TimeSchedule.-FDIWW-"); // futureDateInWorkWeek
public static final Logger iaaLog = Logger.getLogger("com.trentlarson.forecast.core.scheduling.TimeSchedule.--IAA--"); // injectAndAdjust
public static final Logger wsbLog = Logger.getLogger("com.trentlarson.forecast.core.scheduling.TimeSchedule.--WSB--"); // workSecondsBetween
/**
Tracks a number of work hours per week, which can be stored and
retrieved by any point in time.
*/
public static class WeeklyWorkHours {
/**
Map from start dates for each working hour rate
to work hours available per day
Note: it's not just a SortedMap because I need the Cloneable interface
*/
private TreeMap<Date,Double> ranges = new TreeMap<Date,Double>();
/** for testing */
public Object clone() {
WeeklyWorkHours result = new WeeklyWorkHours();
result.ranges = (TreeMap<Date,Double>) ranges.clone();
return result;
}
/** for testing */
protected int size() {
return ranges.size();
}
public String toString() {
return "WeeklyWorkHours " + ranges.toString();
}
public String toShortString() {
StringBuilder sb = new StringBuilder();
for (Iterator<Date> keyIter = ranges.keySet().iterator();
keyIter.hasNext(); ) {
Date key = keyIter.next();
sb.append(SLASH_TIME.format(key) + "=" + ranges.get(key));
if (keyIter.hasNext()) {
sb.append(", ");
}
}
return sb.toString();
}
public boolean isEmpty() {
return ranges.size() == 0;
}
public Double endingHours() {
if (ranges.size() == 0) {
throw new IllegalStateException("Cannot access time from empty range.");
} else {
return ranges.get(ranges.lastKey());
}
}
/**
@return weekly hours available starting on this date
@throws IllegalStateException if the date is before all available times
*/
public Double retrieve(Date time) {
if (ranges.size() == 0) {
throw new IllegalStateException("Cannot access time " + time + " from empty range.");
} else if (time.before(ranges.firstKey())) {
throw new IllegalStateException("Cannot access time " + time + " from range starting " + ranges.firstKey());
}
if (ranges.containsKey(time)) {
return ranges.get(time);
} else {
return ranges.get(ranges.headMap(time).lastKey());
}
}
/**
Simply adds this info as a record; does no sanity checking.
If the time already exists, this value will replace it.
This info is cloned so that modifications won't affect references.
*/
// THIS SHOULD BE PRIVATE! Use injectAndAdjust instead... but
// maybe a new method that doesn't take an end time?
public void inject(Date startTime, Double hours) {
ranges.put((Date)startTime.clone(), hours);
}
/**
@param start time to start working (not adjusted by FIRST_HOUR_OF_WORKDAY)
@return time when a different rate of weekly hours is available,
or null if this rate is available forever. More precisely:
<ol>
<li> return the next time a rate that is higher or lower is
available (always the next time slice) -- unless the available
rate for the given week is the maximum (MAX_WORKHOURS_PER_WORKDAY
* WORKDAYS_PER_WEEK) or higher, in which case return the next
time there is a rate that is lower (because it doesn't matter if
they're higher)
<li> if no such rates exist, return null
</ol>
@throws IllegalStateException if the date is before all available times
*/
public Date nextRateChange(Date start) {
Double startRate = retrieve(start);
SortedMap<Date,Double> more = ranges.tailMap(start);
Iterator<Date> rateIter = more.keySet().iterator();
Date finalDate = null;
while (rateIter.hasNext()) {
finalDate = rateIter.next();
double hours = retrieve(finalDate);
// check if this rate is significantly different
if (hours != startRate) {
// check to see if it matters
if (startRate < MAX_WORKHOURS_PER_WORKDAY * WORKDAYS_PER_WEEK
|| hours < MAX_WORKHOURS_PER_WORKDAY * WORKDAYS_PER_WEEK) {
break;
}
}
finalDate = null;
}
return finalDate;
}
/**
Adjust all affected records by subtracting 'weeklyHourRateDiff'
hours. Note that this assumes that there are at least
weeklyHourRateDiff hours in the entire range from startTime to
endTime, and throws an exception if not.
@throws IllegalStateException if either date is before all available times
@throws IllegalStateException if any record would be < 0
*/
public void injectAndAdjust(Date startTime, Date endTime,
double weeklyHourRateDiff) {
if (weeklyHourRateDiff == 0.0) {
return; // for efficiency
}
double startHours = retrieve(startTime);
// sanity check
if (startHours - weeklyHourRateDiff < 0) {
throw new IllegalStateException("Cannot set negative hours of " + startHours + " - " + weeklyHourRateDiff + " to range of " + startTime + " thru " + endTime + ". Ranges are: " + toShortString());
}
if (endTime.before(startTime)) {
throw new IllegalStateException("Cannot adjust invalid range of " + startTime + " thru " + endTime + ". Ranges are: " + toShortString());
}
// check previous
double prevHoursNow = -1.0;
SortedMap<Date,Double> prevMap = ranges.headMap(startTime);
if (prevMap.size() > 0) {
prevHoursNow = ranges.get(prevMap.lastKey());
}
// -- if same, remove this record
if (prevHoursNow == startHours - weeklyHourRateDiff) {
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("removing " + startTime);
}
ranges.remove(startTime);
} else { // -- if different, create/update this record
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("creating " + startTime + " with "
+ (startHours - weeklyHourRateDiff));
}
ranges.put(startTime, startHours - weeklyHourRateDiff);
}
// keep track because we may have to restore these hours later
prevHoursNow = startHours - weeklyHourRateDiff;
double prevHoursBeforeChange = startHours;
// look for next time to adjust (either next rate or end)
Date nextChange = null;
Iterator<Date> moreIter = ranges.tailMap(startTime).keySet().iterator();
if (moreIter.hasNext()) {
nextChange = moreIter.next();
// if the first one is the start time, skip it
if (nextChange.equals(startTime)) {
if (moreIter.hasNext()) {
nextChange = moreIter.next();
} else {
nextChange = null;
}
}
// repeat that while there are more rates and we're before the end time
while (nextChange != null
&& nextChange.before(endTime)) {
double nextRate = ranges.get(nextChange);
if (nextRate - weeklyHourRateDiff < 0) {
throw new IllegalStateException("At " + nextChange + ", new hours of " + nextRate + " - " + weeklyHourRateDiff + " is a negative time. (Working from " + startTime + " to " + endTime + ".) Ranges are: " + toShortString());
}
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("creating next " + nextChange + " with "
+ (nextRate - weeklyHourRateDiff));
}
ranges.put(nextChange, nextRate - weeklyHourRateDiff);
prevHoursNow = nextRate - weeklyHourRateDiff;
prevHoursBeforeChange = nextRate;
if (moreIter.hasNext()) {
nextChange = moreIter.next();
} else {
nextChange = null;
}
}
}
// adjust the end time
// if it already exists in our ranges...
if (ranges.containsKey(endTime)) {
// ... check whether it needs to be erased (if same as previous rate)
if (ranges.get(endTime) == prevHoursNow) {
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("removing last " + endTime + " with "
+ prevHoursBeforeChange);
}
ranges.remove(endTime);
}
} else {
// ... else it doesn't already exist, so we have to make one
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("creating last " + endTime + " with "
+ prevHoursBeforeChange);
}
ranges.put(endTime, prevHoursBeforeChange);
}
if (iaaLog.isDebugEnabled()) {
iaaLog.debug("ranges now: " + toShortString());
}
}
}
private static class WorkedHoursAndRates {
protected final Date start, end;
protected final double numHours, hoursPerDay;
protected WorkedHoursAndRates(Date start_, Date end_,
double numHours_, double hoursPerDay_) {
this.start = start_;
this.end = end_;
this.numHours = numHours_;
this.hoursPerDay = hoursPerDay_;
}
}
public static class IssueSchedule<T extends IssueWorkDetail<T>> implements Comparable<IssueSchedule<T>> {
private final T issue;
private final Date beginDate;
private final Date endDate;
private final Calendar nextEstBegin;
private final List<IssueSchedule<T>> splitAroundOthers;
private final List<WorkedHoursAndRates> hoursWorked;
private IssueSchedule
(T issue_, Date beginDate_, Date endDate_,
Calendar nextEstBegin_, List<IssueSchedule<T>> splitAroundOthers_,
List<WorkedHoursAndRates> hoursWorked_) {
this.issue = issue_;
this.beginDate = beginDate_;
this.endDate = endDate_;
this.nextEstBegin = nextEstBegin_;
this.splitAroundOthers = splitAroundOthers_;
this.hoursWorked = hoursWorked_;
}
public int compareTo(IssueSchedule<T> object) {
return getBeginDate().compareTo((object).getBeginDate());
}
public String toString() {
return "IssueSchedule " + issue.getKey();
}
public StringBuilder getHoursWorkedDescription(boolean forHtml) {
StringBuilder sb = new StringBuilder();
for (WorkedHoursAndRates workedRange : hoursWorked) {
if (sb.length() > 0) {
if (forHtml) {
sb.append("<br>");
} else {
sb.append(", ");
}
}
sb.append(workedRange.numHours + " hours");
if (workedRange.numHours > 0) {
sb.append(" (at " + workedRange.hoursPerDay + "/day)");
}
sb.append(" "
+ SLASH_TIME.format(instanceAdjustedByStartOfWorkDay(workedRange.start).getTime())
+ "-"
+ SLASH_TIME.format(instanceAdjustedByStartOfWorkDay(workedRange.end).getTime()));
}
return sb;
}
public IssueWorkDetail<T> getIssue() {
return issue;
}
/** @return date work on this task should begin, NOT adjusted by workday hours */
public Date getBeginDate() {
return beginDate;
}
/** @return date work on this task should begin, NOT adjusted by workday hours */
public Calendar getBeginCal() {
Calendar cal = new GregorianCalendar();
cal.setTime(beginDate);
return cal;
}
/** @return date work on this task should begin, adjusted by workday hours */
public Calendar getAdjustedBeginCal() {
// REFACTOR to use instanceAdjustedByStartOfWorkDay
Calendar beginCal = Calendar.getInstance();
beginCal.setTime(beginDate);
beginCal.roll(Calendar.HOUR_OF_DAY, FIRST_HOUR_OF_WORKDAY); // to calculate during day
return beginCal;
}
/** @return date work on this task should complete, NOT adjusted by workday hours */
public Date getEndDate() {
return endDate;
}
/** @return date work on this task should complete, NOT adjusted by workday hours */
public Calendar getEndCal() {
Calendar cal = new GregorianCalendar();
cal.setTime(endDate);
return cal;
}
/** @return date work on this task should complete, adjusted by workday hours */
public Calendar getAdjustedEndCal() {
// REFACTOR to use instanceAdjustedByStartOfWorkDay
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
endCal.roll(Calendar.HOUR_OF_DAY, FIRST_HOUR_OF_WORKDAY); // to calculate during day
return endCal;
}
/** @return date the next task can begin, NOT adjusted by workday hours */
public Calendar getNextEstBegin() {
return nextEstBegin;
}
/** @return date the next task can begin, adjusted by workday hours */
public Date getAdjustedNextBeginDate() {
// REFACTOR to use instanceAdjustedByStartOfWorkDay?
nextEstBegin.roll(Calendar.HOUR_OF_DAY, FIRST_HOUR_OF_WORKDAY); // to display during day
Date result = nextEstBegin.getTime();
nextEstBegin.roll(Calendar.HOUR_OF_DAY, -FIRST_HOUR_OF_WORKDAY); // to calculate from midnight
return result;
}
/** @return IssueSchedule elements of items spanned by this one */
public List<IssueSchedule<T>> getSplitAroundOthers() {
return splitAroundOthers;
}
public boolean isSplitAroundOthers() {
return splitAroundOthers.size() > 0;
}
/**
@param calStartOfDay midnight in morning of day to start checking for work to do
@param days how many days (including weekends/holidays) to check
@return number of seconds of work scheduled to do in that time frame
*/
public long timeWorkedOnDays(Calendar calStartOfDay, int days, double weeklyHours) {
Calendar calStartOfNextDay = (Calendar) calStartOfDay.clone();
calStartOfNextDay.add(Calendar.DAY_OF_YEAR, days);
double dailyHours = weeklyHours / WORKDAYS_PER_WEEK;
long totalTime =
workSecondsBetween(calStartOfDay, calStartOfNextDay, dailyHours);
for (Iterator<IssueSchedule<T>> schedIter = getSplitAroundOthers().iterator();
schedIter.hasNext(); ) {
IssueSchedule<T> sched = schedIter.next();
if (sched.getBeginCal().before(calStartOfNextDay)
&& sched.getEndCal().after(calStartOfDay)) {
totalTime -=
workSecondsBetween(sched.getBeginCal(), sched.getEndCal(), dailyHours);
}
}
return totalTime;
}
}
public static interface IssueWorkDetail<T extends IssueWorkDetail<T>> {
public String getKey();
public String getTimeAssignee();
public String getSummary();
/** @return estimated seconds remaining */
public int getEstimate();
/** @return in seconds */
public int getTimeSpent();
/** @return in seconds */
public int totalEstimate();
/** @return in seconds */
public int totalTimeSpent();
/** either the maximum number of seconds or 0 if there is no max */
public int getMaxSecondsPerWeek();
public Date getDueDate();
/** date when work must start (probably for X hours-per-week tasks, which isn't built yet); see IssueLoader.DB_START_DATE_COLUMN for how we load values */
public Date getMustStartOnDate();
/** 1-based (though I'd like to make it 0-based; just have to adjust Jira loading and modifying) */
public int getPriority();
public boolean getResolved();
/** @return issues that "must be done before" this issue */
public Set<T> getPrecursors();
/** @return issues to schedule before this issue (subtasks and precursors) */
public Set<T> getIssuesToScheduleFirst();
}
protected static class IssueWorkDetailOriginal<T extends IssueWorkDetailOriginal<T>> implements IssueWorkDetail<T>, Comparable<T> {
// REFACTOR the key to be null by default
protected String key = "", timeAssignee = null, summary = "";
protected int issueEstSecondsRaw = 0, secsPerWeek = 0;
protected int priority = 1;
protected Date dueDate = null, mustStartOnDate = null;
// issues that "must be done before" this one
protected final SortedSet<T> precursors;
// issues that "are part of" this one
protected final Set<T> subtasks;
/**
* for GSON deserialization
*/
public IssueWorkDetailOriginal() {
this.key = "";
this.summary = "";
this.priority = 1;
this.precursors = new TreeSet<T>();
this.subtasks = new TreeSet<>();
}
/**
@param issueEstSecondsRaw_ estimate in seconds
*/
public IssueWorkDetailOriginal
(String key_, String timeAssignee_, String summary_,
int issueEstSecondsRaw_, double maxHoursPerWeek_,
Date dueDate_, Date mustStartOnDate_,
int priority_) {
this();
this.key = key_;
this.timeAssignee = timeAssignee_;
this.summary = summary_;
this.issueEstSecondsRaw = issueEstSecondsRaw_;
this.secsPerWeek = maxHoursPerWeek_ <= 0.0 ? 0 : ((int) (maxHoursPerWeek_ * 60 * 60));
this.dueDate = dueDate_;
this.mustStartOnDate = mustStartOnDate_;
this.priority = priority_;
}
public String getKey() { return key; }
public String getTimeAssignee() { return timeAssignee; }
public String getSummary() { return summary; }
public int getEstimate() { return issueEstSecondsRaw; }
public int getTimeSpent() { return 0; }
public int getMaxSecondsPerWeek() { return secsPerWeek; }
public int totalEstimate() { return issueEstSecondsRaw; }
public int totalTimeSpent() { return 0; }
public Date getDueDate() { return dueDate; }
/** @see IssueWorkDetail#getMustStartOnDate() */
public Date getMustStartOnDate() { return mustStartOnDate; }
/** @see IssueWorkDetail#getPriority() */
public int getPriority() { return priority; }
public boolean getResolved() { return false; }
public Set<T> getPrecursors() { return precursors; }
public Set<T> getSubtasks() { return subtasks; }
public Set<T> getIssuesToScheduleFirst() {
Set<T> result = new TreeSet<T>();
result.addAll(getPrecursors());
result.addAll(subtasks);
return result;
}
public String toString() {
return "IssueWorkDetailOriginal " + getKey();
}
public int compareTo(T object) {
return getKey().compareTo(object.getKey());
}
}
/**
Try to deprecate this since WeeklyWorkHours is used most everywhere.
Used for input to scheduling, in a list telling what is
available. Implementations must use the getStartOfTimeSpan for
Comparable interface (and 'equals' method).
*/
public static interface HoursForTimeSpan extends Comparable<HoursForTimeSpan> {
public Date getStartOfTimeSpan();
public double getHoursAvailable();
}
public static class HoursForTimeSpanOriginal implements HoursForTimeSpan {
Date startOfTimeSpan;
double hoursAvailable;
public HoursForTimeSpanOriginal(Date start, double hours) {
if (start == null) {
throw new IllegalStateException("Cannot supply work with null date.");
}
startOfTimeSpan = start;
hoursAvailable = hours;
}
public Date getStartOfTimeSpan() {
return startOfTimeSpan;
}
public double getHoursAvailable() {
return hoursAvailable;
}
public int compareTo(HoursForTimeSpan o) {
return getStartOfTimeSpan()
.compareTo((o).getStartOfTimeSpan());
}
public boolean equals(Object o) {
if (o instanceof HoursForTimeSpan) {
return compareTo((HoursForTimeSpan) o) == 0;
} else {
return false;
}
}
public String toString() {
String[] split = SLASH_DATE.format(startOfTimeSpan).split("/");
return
"Span " + split[1] + "/" + split[2] + "=" + hoursAvailable;
}
}
/**
sorts by start date, then priority, then due date
*/
public static class DetailPriorityComparator<T extends IssueWorkDetail<T>> implements Comparator<T> {
private final boolean reversePriority;
public DetailPriorityComparator(boolean reversePriority_) {
this.reversePriority = reversePriority_;
}
public int compare(T d1, T d2) {
// first determinant is whether there's a start date on it
if (d1.getMustStartOnDate() == null && d2.getMustStartOnDate() != null) {
return 1;
} else if (d1.getMustStartOnDate() != null && d2.getMustStartOnDate() == null) {
return -1;
} else {
int dateCompare = 0;
if (d1.getMustStartOnDate() != null && d2.getMustStartOnDate() != null) {
dateCompare = d1.getMustStartOnDate().compareTo(d2.getMustStartOnDate());
}
if (dateCompare != 0) {
return dateCompare;
} else {
// next determinant is the priority
if (d1.getPriority() != d2.getPriority()) {
// lower priority comes earlier
if (reversePriority) {
return (d2.getPriority() - d1.getPriority());
} else {
return (d1.getPriority() - d2.getPriority());
}
// final determinant is the due-date
} else if (d1.getDueDate() == null && d2.getDueDate() != null) {
return 1;
} else if (d1.getDueDate() != null && d2.getDueDate() == null) {
return -1;
} else {
dateCompare = 0;
if (d1.getDueDate() != null && d2.getDueDate() != null) {
dateCompare = d1.getDueDate().compareTo(d2.getDueDate());
}
if (dateCompare != 0) {
return dateCompare;
} else {
return d2.getKey().compareTo(d2.getKey());
}
}
}
}
}
}
/**
sorts by start date, then due date, then priority
*/
public static class DetailDueComparator<T extends IssueWorkDetail<T>> implements Comparator<T> {
public int compare(T d1, T d2) {
// first determinant is whether there's a start date on it
if (d1.getMustStartOnDate() == null && d2.getMustStartOnDate() != null) {
return 1;
} else if (d1.getMustStartOnDate() != null && d2.getMustStartOnDate() == null) {
return -1;
} else {
int dateCompare = 0;
if (d1.getMustStartOnDate() != null && d2.getMustStartOnDate() != null) {
dateCompare = d1.getMustStartOnDate().compareTo(d2.getMustStartOnDate());
}
if (dateCompare != 0) {
return dateCompare;
} else {
// next determinant is the due-date
if (d1.getDueDate() == null && d2.getDueDate() != null) {
return 100;
} else if (d1.getDueDate() != null && d2.getDueDate() == null) {
return -100;
} else {
dateCompare = 0;
if (d1.getDueDate() != null && d2.getDueDate() != null) {
dateCompare = d1.getDueDate().compareTo(d2.getDueDate());
}
if (dateCompare != 0) {
return dateCompare;
} else {
// final determinant is the priority
// lower priority comes earlier
return 10 * (d1.getPriority() - d2.getPriority());
}
}
}
}
}
}
protected static Calendar instanceAdjustedByStartOfWorkDay(Calendar cal) {
Calendar result = (Calendar) cal.clone();
result.roll(Calendar.HOUR_OF_DAY, FIRST_HOUR_OF_WORKDAY);
return result;
}
protected static Date instanceAdjustedByStartOfWorkDay(Date date) {
Calendar resultCal = Calendar.getInstance();
resultCal.setTime(date);
return instanceAdjustedByStartOfWorkDay(resultCal).getTime();
}
/**
*
* @param thisCal
* @return a calendar where the hour-of-day is rounded down (ie. set to beginning of the day, down to the millisecond)
*/
private static Calendar instanceAtDayStart(Calendar thisCal) {
Calendar newCal = (Calendar) thisCal.clone();
newCal.set(Calendar.HOUR_OF_DAY, 0);
newCal.set(Calendar.MINUTE, 0);
newCal.set(Calendar.SECOND, 0);
newCal.set(Calendar.MILLISECOND, 0);
return newCal;
}
/**
*
* @param thisCal
* @return a calendar where the day-of-week is rounded down (ie. set to beginning of the week, down to the millisecond)
*/
/* unused
private static Calendar instanceAtWeekStart(Calendar thisCal) {
Calendar newCal = (Calendar) thisCal.clone();
newCal.set(Calendar.DAY_OF_WEEK, 0);
return instanceAtDayStart(newCal);
}
*/
/** @return number of days into the work week by midnight this day's morning */
private static int daysIntoWorkWeek(Calendar someday) {
switch (someday.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY: return 0;
case Calendar.MONDAY: return 0;
case Calendar.TUESDAY: return 1;
case Calendar.WEDNESDAY: return 2;
case Calendar.THURSDAY: return 3;
case Calendar.FRIDAY: return 4;
// FIX this to throw the exception and still work on our data (test for it?)
case Calendar.SATURDAY: return 5;
// case Calendar.SATURDAY: throw new IllegalStateException("The previous date shouldn't ever be a non-weekday " + someday.get(Calendar.DAY_OF_WEEK));
default: throw new IllegalStateException("The previous date shouldn't ever be a non-weekday " + someday.get(Calendar.DAY_OF_WEEK));
}
}
/**
@return Calendar for the first time after given date that falls in work-week
*/
private static Calendar dateInWorkWeek(Date date, double dailyHours) {
// shift the start time to be within the work week
Calendar nextEstBegin = new GregorianCalendar();
nextEstBegin.setTime(date);
{
if (nextEstBegin.get(Calendar.HOUR_OF_DAY) < FIRST_HOUR_OF_WORKDAY) {
nextEstBegin.set(Calendar.HOUR_OF_DAY, 0);
nextEstBegin.set(Calendar.MINUTE, 0);
} else {
int hour_into_workday =
nextEstBegin.get(Calendar.HOUR_OF_DAY) - FIRST_HOUR_OF_WORKDAY;
if (hour_into_workday < dailyHours) {
nextEstBegin.set(Calendar.HOUR_OF_DAY, hour_into_workday);
} else {
nextEstBegin.add(Calendar.DAY_OF_WEEK, 1);
nextEstBegin.set(Calendar.HOUR_OF_DAY, 0);
nextEstBegin.set(Calendar.MINUTE, 0);
}
}
nextEstBegin.set(Calendar.SECOND, 0);
nextEstBegin.set(Calendar.MILLISECOND, 0);
if (nextEstBegin.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
nextEstBegin.add(Calendar.DAY_OF_WEEK, 2);
} else if (nextEstBegin.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
nextEstBegin.add(Calendar.DAY_OF_WEEK, 1);
}
}
return nextEstBegin;
}
/**
*
* @param date
* @return beginning work time in week following date
*/
/* unused
private static Calendar beginningOfNextWorkWeek(Calendar thisCal) {
Calendar nextCal = (Calendar) thisCal.clone();
nextCal.add(Calendar.WEEK_OF_YEAR, 1);
return dateInWorkWeek(instanceAtWeekStart(nextCal).getTime(), MAX_WORKHOURS_PER_WORKDAY);
}
*/
/**
@return number of seconds of work time between two dates, where
startCal comes before endCal and both are NOT adjusted by
FIRST_HOUR_OF_WORKDAY
*/
private static long workSecondsBetween(Calendar startCal, Calendar endCal,
double dailyHours) {
if (dailyHours == 0.0) {
return 0; // just for efficiency
}
// get the full time between the dates
long millisecondsBetween =
endCal.getTime().getTime() - startCal.getTime().getTime();
long fullTimeSecondsBetween = millisecondsBetween / 1000;
// if daylight-savings is in the middle, we'll have to adjust
// (since our calculations are based on full-day increments)
boolean startInDaylight =
startCal.getTimeZone().inDaylightTime(startCal.getTime());
boolean endInDaylight =
endCal.getTimeZone().inDaylightTime(endCal.getTime());
if (startInDaylight != endInDaylight) {
if (startInDaylight) {
// the ending is not in daylight savings, so an hour has been added
fullTimeSecondsBetween -= 3600;
} else {
// the ending is in daylight savings, so an hour has been subtracted
fullTimeSecondsBetween += 3600;
}
}
// calculate any non-work seconds in between
long numSecondsAlreadyOnFirstDay =
startCal.get(Calendar.HOUR_OF_DAY) * 3600L
+ startCal.get(Calendar.MINUTE) * 60L
+ startCal.get(Calendar.SECOND);
// -- don't count after-hours (16/day)
long totalTimePastMidnightOnFirstMorn =
numSecondsAlreadyOnFirstDay + fullTimeSecondsBetween;
long fullDays = totalTimePastMidnightOnFirstMorn / (24L * 3600L);
long fullDayNonWorkSeconds =
(long) (fullDays * (24.0 - MAX_WORKHOURS_PER_WORKDAY) * 3600.0);
// -- don't count work if starting or ending on weekend
long firstDaySecsToSubtract = 0;
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// remove all the time today that is usually counted for work
firstDaySecsToSubtract =
(long)
(MAX_WORKHOURS_PER_WORKDAY * 3600.0 - numSecondsAlreadyOnFirstDay);
}
// -- don't count weekend days
long fullWeeks = fullDays / 7;
long fullWeekendDays = fullWeeks * (7 - WORKDAYS_PER_WEEK);
// -- check if we are spanning any weekend days
if (endCal.get(Calendar.DAY_OF_WEEK) < startCal.get(Calendar.DAY_OF_WEEK)) {
// the starting time is in one week, and the end time is in the next week
if (startCal.get(Calendar.DAY_OF_WEEK) <= Calendar.FRIDAY) {
fullWeekendDays += 1;
}
if (endCal.get(Calendar.DAY_OF_WEEK) >= Calendar.MONDAY) {
fullWeekendDays += 1;
}
}
long weekendDaySecondsBetween =
(long) (fullWeekendDays * MAX_WORKHOURS_PER_WORKDAY * 3600.0);
// -- don't count partial time if ending on a weekend
long secondsOnLastDayToSubtract = 0;
if (endCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| endCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
secondsOnLastDayToSubtract =
endCal.get(Calendar.HOUR_OF_DAY) * 3600
+ endCal.get(Calendar.MINUTE) * 60
+ endCal.get(Calendar.SECOND);
}
long secondsOffToSubtract =
firstDaySecsToSubtract
+ fullDayNonWorkSeconds
+ weekendDaySecondsBetween
+ secondsOnLastDayToSubtract;
// now we can calculate result
// note that this is where we adjust by the actual working rate
long result =
(long)
((fullTimeSecondsBetween - secondsOffToSubtract)
* (dailyHours / MAX_WORKHOURS_PER_WORKDAY));
if (wsbLog.isDebugEnabled()) {
wsbLog.debug("total hours past morning: " + (totalTimePastMidnightOnFirstMorn / 3600.0));
wsbLog.debug("A) first-day non-work hours: " + (firstDaySecsToSubtract / 3600.0));
wsbLog.debug("B) everyday non-work hours between: " + (fullDayNonWorkSeconds / 3600.0));
wsbLog.debug("C) weekend day hours between: " + (weekendDaySecondsBetween / 3600.0));
wsbLog.debug("D) last day hours: " + (secondsOnLastDayToSubtract / 3600.0));
wsbLog.debug("E) off hours (A+B+C+D): " + (secondsOffToSubtract / 3600.0));
wsbLog.debug("F) full time hours: " + (fullTimeSecondsBetween / 3600.0));
wsbLog.debug("result hours (F-E * " + (100 * dailyHours / MAX_WORKHOURS_PER_WORKDAY) + "%): " + (result / 3600.0));
}
return result;
}
private static Calendar futureDateInWorkWeek(Calendar thisEstBegin,
long secondsToAdd,
double dailyHoursAvailable) {
long numSecsAlreadyOnDay =
thisEstBegin.get(Calendar.HOUR_OF_DAY) * 3600
+ thisEstBegin.get(Calendar.MINUTE) * 60
+ thisEstBegin.get(Calendar.SECOND);
long timePastThisMorning = numSecsAlreadyOnDay + secondsToAdd;
int numEstDays = 0;
int numEstSecsOnLastDay = (int) timePastThisMorning;
if (dailyHoursAvailable > 0.0) {
// number of days is number of whole increments of a day size
numEstDays =
(int) (secondsToAdd / (dailyHoursAvailable * 3600.0));
// last day time is remainder
numEstSecsOnLastDay =
(int) (secondsToAdd % (dailyHoursAvailable * 3600.0));
// calculate percentage of last day (to set the time on the final day)
double percentOfLastDayAlready =
numSecsAlreadyOnDay / (MAX_WORKHOURS_PER_WORKDAY * 3600.0);
double percentOfLastDayToAdd =
numEstSecsOnLastDay / (dailyHoursAvailable * 3600.0);
double totalPercentOnLastDay =
percentOfLastDayAlready + percentOfLastDayToAdd;
if (totalPercentOnLastDay >= 1.0) {
numEstDays++;
totalPercentOnLastDay -= 1.0;
}
numEstSecsOnLastDay =
(int) (totalPercentOnLastDay * MAX_WORKHOURS_PER_WORKDAY * 3600.0);
}
if (fdiwwLog.isDebugEnabled()) {
fdiwwLog.debug("numSecsAlreadyOnDay in hours: " + (numSecsAlreadyOnDay / 3600.0));
fdiwwLog.debug("timePastThisMorning in hours: " + (timePastThisMorning / 3600.0));
fdiwwLog.debug("dailyHours: " + dailyHoursAvailable);
fdiwwLog.debug("numEstDays: " + numEstDays);
fdiwwLog.debug("last day hours if full time: " + ((numEstSecsOnLastDay * dailyHoursAvailable / MAX_WORKHOURS_PER_WORKDAY) / 3600.0));
fdiwwLog.debug("numEstSecsOnLastDay in hours: " + (numEstSecsOnLastDay / 3600.0));
}
Calendar nextEstBegin = instanceAtDayStart(thisEstBegin);
if (numEstDays > 0) {
int fullWeeks =
(daysIntoWorkWeek(thisEstBegin) + numEstDays) / WORKDAYS_PER_WEEK;
int weekendDays = fullWeeks * (7 - WORKDAYS_PER_WEEK);
nextEstBegin.add(Calendar.DAY_OF_WEEK, numEstDays + weekendDays);
if (fdiwwLog.isDebugEnabled()) {
fdiwwLog.debug("added " + thisEstBegin.getTime() + " + "
+ numEstDays + " days + "
+ weekendDays + " weekends"
+ " = " + nextEstBegin.getTime());
}
}
nextEstBegin.add(Calendar.SECOND, numEstSecsOnLastDay);
nextEstBegin = DateUtil.round(nextEstBegin, Calendar.MINUTE); // This shouldn't matter, but you can see what can happen with rounding errors on tlarson's schedule with jira-test-begin-work-error.sql (after removing this line).
if (fdiwwLog.isDebugEnabled()) {
fdiwwLog.debug("added " + thisEstBegin.getTime() + " + "
+ (secondsToAdd / 3600.0) + " hours"
+ " (ie. " + numEstDays + " days, "
+ (numEstSecsOnLastDay / 3600.0) + " last-day hours)"
+ " = " + nextEstBegin.getTime());
}
if (fdiwwLog.isDebugEnabled()) {
fdiwwLog.debug("result: " + (nextEstBegin.getTime()));
}
return nextEstBegin;
}
private static class NextBeginAndHoursWorked {
protected final List<WorkedHoursAndRates> hoursWorked;
protected final Calendar nextBegin;
protected NextBeginAndHoursWorked(Calendar nextBegin_,
List<WorkedHoursAndRates> hoursWorked_) {
this.nextBegin = nextBegin_;
this.hoursWorked = hoursWorked_;
}
}
/**
@param thisEstBegin time to start working (not adjusted by FIRST_HOUR_OF_WORKDAY)
@param estSeconds estimate in seconds
@param weeklyHours tells how many available each week;
beware, because it is modified by time needed for this task
@return the next start date based on the start date and estimate
*/
private static NextBeginAndHoursWorked findNextEstBegin
(Calendar thisEstBegin, int estSeconds, WeeklyWorkHours weeklyHours, int maxSecondsPerWeek) {
Calendar nextWorkChunkBegins = (Calendar) thisEstBegin.clone();
List<WorkedHoursAndRates> hoursWorked = new ArrayList<WorkedHoursAndRates>();
int estSecsRemaining = estSeconds;
do {
double totalWorkRateAvailableThisRange =
weeklyHours.retrieve(nextWorkChunkBegins.getTime());
double dailyHoursAvailableThisRange =
Math.min(MAX_WORKHOURS_PER_WORKDAY, totalWorkRateAvailableThisRange / WORKDAYS_PER_WEEK);
// This is helpful to show the actual worked time, eg. when there's a maximum hours/week for this issue.
double dailyHoursWorkingThisRange = dailyHoursAvailableThisRange;
if (maxSecondsPerWeek > 0) {
dailyHoursWorkingThisRange =
Math.min(dailyHoursAvailableThisRange, (maxSecondsPerWeek / 3600.0) / WORKDAYS_PER_WEEK);
}
if (fnebLog.isDebugEnabled()) {
fnebLog.debug("est hours remaning: " + (estSecsRemaining / 3600.0));
fnebLog.debug("next work begins: " + (nextWorkChunkBegins.getTime()));
fnebLog.debug("all rates: " + (weeklyHours.toShortString()));
fnebLog.debug("rate this range: " + totalWorkRateAvailableThisRange);
fnebLog.debug("daily rate: " + dailyHoursWorkingThisRange);
if (maxSecondsPerWeek > 0) {
fnebLog.debug("max hours this issue/week: " + (maxSecondsPerWeek / 3600));
}
}
Calendar nextChangeCal = null;
long availableSecsToNextChange = estSecsRemaining;
Date nextChange =
weeklyHours.nextRateChange(nextWorkChunkBegins.getTime());
if (nextChange != null) {
nextChangeCal = Calendar.getInstance();
nextChangeCal.setTime(nextChange);
if (fnebLog.isDebugEnabled()) {
fnebLog.debug("next rate change: " + (nextChangeCal.getTime()));
}
availableSecsToNextChange =
workSecondsBetween(nextWorkChunkBegins, nextChangeCal,
dailyHoursWorkingThisRange);
}
long secondsThisRange =
Math.min(availableSecsToNextChange, estSecsRemaining);
if (maxSecondsPerWeek > 0) {
secondsThisRange = Math.min(secondsThisRange, maxSecondsPerWeek);
}
if (fnebLog.isDebugEnabled()) {
fnebLog.debug("hours available: " + (availableSecsToNextChange / 3600.0));
fnebLog.debug("hours used this range: " + (secondsThisRange / 3600.0));
}
Calendar endOfThisRange = nextChangeCal;
// the next start may be different from the end, eg. if we only work a few hours a week on this
Calendar startOfNextRange = nextChangeCal;
if (secondsThisRange > 0) {
endOfThisRange =
futureDateInWorkWeek(nextWorkChunkBegins, secondsThisRange,
dailyHoursAvailableThisRange);
if (dailyHoursAvailableThisRange == dailyHoursWorkingThisRange) {
startOfNextRange = endOfThisRange;
} else {
startOfNextRange =
futureDateInWorkWeek(nextWorkChunkBegins, secondsThisRange,
dailyHoursWorkingThisRange);
}
weeklyHours
.injectAndAdjust(nextWorkChunkBegins.getTime(),
startOfNextRange.getTime(),
dailyHoursWorkingThisRange * WORKDAYS_PER_WEEK);
} else { // secondsThisRange == 0
if (estSecsRemaining == 0.0) {
// just set the end date to the same as the beginning
endOfThisRange = nextWorkChunkBegins;
startOfNextRange = nextWorkChunkBegins;
}
}
{
// add to the records of time worked
Date rangeBegin = nextWorkChunkBegins.getTime();
if (secondsThisRange == 0
&& hoursWorked.size() > 0
&& hoursWorked.get(hoursWorked.size() - 1).numHours == 0) {
rangeBegin = hoursWorked.get(hoursWorked.size() - 1).start;
hoursWorked.remove(hoursWorked.size() - 1);
}
hoursWorked.add
(new WorkedHoursAndRates
(instanceAdjustedByStartOfWorkDay(rangeBegin),
instanceAdjustedByStartOfWorkDay(endOfThisRange).getTime(),
secondsThisRange / 3600.0,
dailyHoursAvailableThisRange));
}
estSecsRemaining -= secondsThisRange;
nextWorkChunkBegins = startOfNextRange;
} while (estSecsRemaining > 0);
if (fnebLog.isDebugEnabled()) {
fnebLog.debug("result time: " + nextWorkChunkBegins.getTime());
}
return new NextBeginAndHoursWorked(nextWorkChunkBegins, hoursWorked);
}
private static Date previousTaskEnd(Calendar taskBegin, int estSeconds) {
// calculate task's end time
// if it's at a day's beginning, put the previous end on the previous day
int endOffsetMillis = 0;
if (taskBegin.get(Calendar.HOUR_OF_DAY) == 0 // if at day start
&& taskBegin.get(Calendar.MINUTE) == 0
&& taskBegin.get(Calendar.SECOND) == 0
&& taskBegin.get(Calendar.MILLISECOND) == 0
&& estSeconds > 0) { // and there was time for this issue (lest end predate start))
// move end date back to end of previous workday
endOffsetMillis += 16 * 3600 * 1000;
if (taskBegin.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
// move end date back to end of previous Friday
endOffsetMillis += 2 * 24 * 3600 * 1000;
}
}
Date result = new Date(taskBegin.getTime().getTime() - endOffsetMillis);
fnebLog.debug("previous end: " + result);
return result;
}
/**
Loop through non-contiguous list looking for all matches so we can
get an accurate next-begin date.
*/
private static Calendar checkWholeContiguousList(Calendar endOfFirstContiguousBlock, List<IssueSchedule> nonContiguousSchedules) {
boolean stillFinding;
do {
stillFinding = false;
for (Iterator<IssueSchedule> issueIter = nonContiguousSchedules.iterator(); issueIter.hasNext(); ) {
IssueSchedule schedule = issueIter.next();
if (schedule.getBeginDate().equals(endOfFirstContiguousBlock.getTime())) {
// it lines up with my block of time, so shift the block
endOfFirstContiguousBlock = schedule.getNextEstBegin();
issueIter.remove();
stillFinding = true;
} else if (schedule.getBeginDate().before(endOfFirstContiguousBlock.getTime())) {
// it won't affect any issues remaining to be schedules
issueIter.remove();
}
}
} while (stillFinding);
return endOfFirstContiguousBlock;
}
/**
@param issueDetails IssueWorkDetail objects remaining to be
scheduled
@param userWeeklyHours used to determine available hours,
and modified when hours are used
@param schedulesForKeys maps from issue key String to the
IssueSchedule element for it; elements are added as they are
successfully scheduled
@param startDate is the beginning of some day to start
scheduling
@return list of IssueSchedule elements in the order they were
created
*/
private static <T extends IssueWorkDetail<T>> List<IssueSchedule<T>> createIssueSchedules
(List<T> issueDetails,
Map<String,WeeklyWorkHours> userWeeklyHours,
Map<String,IssueSchedule<T>> schedulesForKeys,
double multiplier, Date startDate) {
// store each IssueSchedule as it is scheduled
List<IssueSchedule<T>> allSchedules = new ArrayList<IssueSchedule<T>>();
Iterator<T> detailIter = issueDetails.iterator();
if (detailIter.hasNext()) {
// move past all the issues already scheduled
T currentDetail;
boolean detailIsScheduled;
// using MAX_WORKHOURS shouldn't make a difference since start
// date should be specified at the beginning of the day
Calendar endOfFirstContiguousBlock =
dateInWorkWeek(startDate, MAX_WORKHOURS_PER_WORKDAY);
Date defaultStartDate = endOfFirstContiguousBlock.getTime();
ArrayList<IssueSchedule> nonContiguousSchedules =
new ArrayList<IssueSchedule>();
int count = 0;
// Hmmm... this is going through every issue and checking it's schedule;
// seems like this could be optimized by storing this info from previous
// scheduling.
do {
currentDetail = detailIter.next();
detailIsScheduled = schedulesForKeys.containsKey(currentDetail.getKey());
if (detailIsScheduled) {
count++;
IssueSchedule schedule = schedulesForKeys.get(currentDetail.getKey());
if (schedule.getBeginDate().equals(endOfFirstContiguousBlock.getTime())) {
endOfFirstContiguousBlock = schedule.getNextEstBegin();
} else if (schedule.getBeginDate().after(endOfFirstContiguousBlock.getTime())) {
nonContiguousSchedules.add(schedule);
}
}
} while (detailIter.hasNext() && detailIsScheduled);
log4jLog.debug
("There are " + (issueDetails.size() - count) + " left"
+ " (" + count + "/" + issueDetails.size() + " done)"
+ " for " + currentDetail.getTimeAssignee()
+ (!detailIsScheduled ? "; next is " + currentDetail.getKey() : ""));
if (!detailIsScheduled) {
WeeklyWorkHours weeklyHours =
userWeeklyHours.get(currentDetail.getTimeAssignee());
if (weeklyHours == null) {
throw new IllegalStateException(currentDetail.getTimeAssignee() + " does not have any hours available for scheduling issues, but they have issue " + currentDetail.getKey() + " assigned to them. Available user schedules are: " + userWeeklyHours);
}
// some non-contiguous issues may match the end time
endOfFirstContiguousBlock =
checkWholeContiguousList(endOfFirstContiguousBlock, nonContiguousSchedules);
// schedule as many tasks as possible
boolean allPrecursorsScheduled = true;
Collections.sort(nonContiguousSchedules);
do {
Calendar nextEstBegin = Calendar.getInstance();
nextEstBegin.setTime(defaultStartDate);
if (weeklyHours.retrieve(nextEstBegin.getTime()) == 0.0) {
nextEstBegin
.setTime(weeklyHours.nextRateChange(nextEstBegin.getTime()));
}
// get the starting time based on the last precursor ending time,
// but don't proceed if any precursors or subtasks are not scheduled
Calendar maxEndOfPrecursors = null;
Set<? extends IssueWorkDetail> allToDoBefore =
currentDetail.getIssuesToScheduleFirst();
for (Iterator<? extends IssueWorkDetail> preIter = allToDoBefore.iterator();
preIter.hasNext() && allPrecursorsScheduled; ) {
IssueWorkDetail preDetail = preIter.next();
if (!schedulesForKeys.containsKey(preDetail.getKey())
&& !preDetail.getResolved()) {
log4jLog.debug("Postponing issue " + currentDetail.getKey() + " until " + preDetail.getKey() + " is scheduled.");
allPrecursorsScheduled = false;
} else if (!preDetail.getResolved()) {
IssueSchedule schedule = schedulesForKeys.get(preDetail.getKey());
Calendar startFromPrecursor = schedule.getNextEstBegin();
if (maxEndOfPrecursors == null
|| startFromPrecursor.after(maxEndOfPrecursors)) {
maxEndOfPrecursors = startFromPrecursor;
}
}
}
if (allPrecursorsScheduled) {
// nextEstBegin = endOfFirstContiguousBlock;
boolean isNonContiguous = false;
if (currentDetail.getMustStartOnDate() != null
&& currentDetail.getMustStartOnDate().after(nextEstBegin.getTime())) {
double dailyHours =
weeklyHours.retrieve(currentDetail.getMustStartOnDate())
/ WORKDAYS_PER_WEEK;
nextEstBegin =
dateInWorkWeek(currentDetail.getMustStartOnDate(), dailyHours);
isNonContiguous = true;
}
// move if it must be pushed later due to precursors
if (maxEndOfPrecursors != null
&& maxEndOfPrecursors.after(nextEstBegin)) {
nextEstBegin = maxEndOfPrecursors;
isNonContiguous = true;
}
Date thisEstBegin = nextEstBegin.getTime();
List<IssueSchedule> splitAroundOthers = new ArrayList<IssueSchedule>();
int issueEstSeconds = (int) (currentDetail.getEstimate() * multiplier);
NextBeginAndHoursWorked nextAndWorked =
new NextBeginAndHoursWorked(nextEstBegin, new ArrayList<WorkedHoursAndRates>());
if (currentDetail.getResolved()) {
// just mark this done with the current time
} else {
// calculate the beginning of the next task, using any spare time
log4jLog.debug(currentDetail.getKey() + " est * mult: "
+ (currentDetail.getEstimate() / 3600.0) + "h * " + multiplier);
@SuppressWarnings("unchecked")
ArrayList<IssueSchedule> nonContigsThatMayOverlap =
(ArrayList<IssueSchedule>) nonContiguousSchedules.clone();
nextAndWorked =
findNextEstBegin(nextEstBegin, issueEstSeconds, weeklyHours, currentDetail.getMaxSecondsPerWeek());
log4jLog.debug(currentDetail.getKey() + " end: "
+ "+" + (issueEstSeconds / 3600.0)
+ "h = " + nextAndWorked.nextBegin.getTime());
nextEstBegin = nextAndWorked.nextBegin;
{
// this section is only for displaying possible overlaps
for (Iterator<IssueSchedule> iter = nonContigsThatMayOverlap.iterator(); iter.hasNext(); ) {
IssueSchedule anotherSched = iter.next();
if (anotherSched.getBeginDate().after(thisEstBegin)
&& anotherSched.getBeginDate().before(nextEstBegin.getTime())) {
// there's another task in the way, so add its time and recalculate
if (!isNonContiguous) {
// this is building on the initial block, so overlaps are contiguous now
nonContiguousSchedules.remove(anotherSched);
}
splitAroundOthers.add(anotherSched);
}
}
for (int icontig = 0; icontig < splitAroundOthers.size(); icontig++) {
nonContigsThatMayOverlap.remove(splitAroundOthers.get(icontig));
}
}
}
// finally we can add this record
IssueSchedule schedule =
new IssueSchedule
(currentDetail,
new Date(thisEstBegin.getTime()),
previousTaskEnd(nextEstBegin, issueEstSeconds),
(Calendar) nextEstBegin.clone(),
splitAroundOthers,
nextAndWorked.hoursWorked);
log4jLog.debug(currentDetail.getKey() + " times: "
+ schedule.getAdjustedBeginCal().getTime()
+ " - " + schedule.getAdjustedEndCal().getTime());
allSchedules.add(schedule);
schedulesForKeys.put(currentDetail.getKey(), schedule);
// if this was put on the first contiguous block, increase that block
if (schedule.getBeginDate().equals(endOfFirstContiguousBlock.getTime())) {
endOfFirstContiguousBlock = schedule.getNextEstBegin();
for (int i = 0; i < nonContiguousSchedules.size(); i++) {
IssueSchedule anotherSched = nonContiguousSchedules.get(i);
if (anotherSched.getBeginDate().equals(endOfFirstContiguousBlock.getTime())) {
endOfFirstContiguousBlock = anotherSched.getNextEstBegin();
}
}
} else if (isNonContiguous) {
nonContiguousSchedules.add(schedule);
}
// ensure that the next iteration starts at end of used time (or later)
// nextEstBegin = endOfFirstContiguousBlock;
}
if (detailIter.hasNext()) {
currentDetail = detailIter.next();
} else {
currentDetail = null;
}
} while (currentDetail != null && allPrecursorsScheduled);
}
}
return allSchedules;
}
protected static Set<IssueWorkDetail> findAllPrecursorsForAssignee(IssueWorkDetail issue) {
return findAllPrecursorsForAssignee(issue, issue.getTimeAssignee(), new TreeSet<IssueWorkDetail>(), new TreeSet<String>());
}
/**
@param found Set of IssueWorkDetail objects, to which issues are
added if they are precursors owned by assignee
*/
private static Set<IssueWorkDetail> findAllPrecursorsForAssignee
(IssueWorkDetail<? extends IssueWorkDetail> issue, String assignee, Set<IssueWorkDetail> found, TreeSet<String> parents) {
// check for loops
if (parents.contains(issue.getKey())) {
throw new IllegalStateException("The issue " + issue.getKey() + " has a loop in it's blocking parentage: " + parents);
}
parents.add(issue.getKey());
// recursively look for ones to do first
for (IssueWorkDetail pre : issue.getIssuesToScheduleFirst()) {
if (pre.getTimeAssignee().equals(assignee)) {
found.add(pre);
}
@SuppressWarnings("unchecked")
TreeSet<String> copyOfParents = (TreeSet<String>) parents.clone();
findAllPrecursorsForAssignee(pre, assignee, found, copyOfParents);
}
return found;
}
public static <T extends IssueWorkDetail> void setInitialOrdering(Map<?,List<T>> userDetails) {
setInitialOrdering(userDetails, false);
}
public static <T extends IssueWorkDetail> void setInitialOrdering(
Map<?,List<T>> userDetails, boolean reversePriority) {
// put them in order by due date and then by priority
for (Iterator users = userDetails.keySet().iterator(); users.hasNext(); ) {
Collections.sort
((List<IssueWorkDetail>) userDetails.get(users.next()),
new DetailPriorityComparator(reversePriority));
}
// since dependents must follow their precursors, make sure they come later
// (possibility of infinite loop if we created a tree with a cycle; we don't)
for (Object user : userDetails.keySet()) {
List<T> oneUserDetails = userDetails.get(user);
for (int pos = 0; pos < oneUserDetails.size(); pos++) {
// -- gather the list of precursors
T issue = oneUserDetails.get(pos);
Set precursors = findAllPrecursorsForAssignee(issue);
int maxPosOfPres = pos;
for (Iterator<IssueWorkDetail> preIter = precursors.iterator(); preIter.hasNext(); ) {
int prePos = oneUserDetails.indexOf(preIter.next());
if (prePos > maxPosOfPres) {
maxPosOfPres = prePos;
}
}
if (maxPosOfPres > pos) {
log4jLog.debug("Due to dependency, shifting " + issue.getKey() + " from " + pos + " to " + maxPosOfPres);
oneUserDetails.remove(pos);
oneUserDetails.add(maxPosOfPres, issue);
pos--;
}
}
}
}
/**
@param userDetails Map from username String to a List of
IssueWorkDetail elements; it is modified to ensure that each List
is sorted into priority order
@param userWeeklyHours tracks the hours for each person; it will
also be updated with the new available hours as things are
scheduled
@return a map from the issue key String to the IssueSchedule for
it; plus, it has the side-effect that the userDetails Map will be
sorted in priority order
*/
public static <T extends IssueWorkDetail<T>> Map<String,IssueSchedule<T>> schedulesForUserIssues
(Map<String,List<T>> userDetails,
Map<String,WeeklyWorkHours> userWeeklyHours,
Date startDate, double multiplier, boolean reversePriority) {
//log4jLog.setLevel(org.apache.log4j.Level.DEBUG);
if (log4jLog.isDebugEnabled()) {
log4jLog.debug("Basic scheduling info follows.");
log4jLog.debug("userWeeklyHours: " + userWeeklyHours);
log4jLog.debug("userDetails: " + userDetails);
}
setInitialOrdering(userDetails, reversePriority);
// look through all the user issues, and repeat until all scheduled
Map<String,IssueSchedule<T>> issueSchedules =
new HashMap<String,IssueSchedule<T>>();
String stillUnfinished;
String previousUnfinishedName = null;
int previousUnfinishedIssueNum = -1;
int finished; // to guard against an infinite loop without progress
do {
do {
stillUnfinished = null;
finished = 0;
for (String user : userDetails.keySet()) {
List<T> oneUserDetails = userDetails.get(user);
List<IssueSchedule<T>> schedule =
createIssueSchedules(oneUserDetails, userWeeklyHours,
issueSchedules, multiplier, startDate);
finished += schedule.size();
// check if there are any issues still not scheduled
if (oneUserDetails.size() > 0) {
IssueWorkDetail<T> lastDetail =
oneUserDetails.get(oneUserDetails.size() - 1);
if (!issueSchedules.containsKey(lastDetail.getKey())) {
stillUnfinished = user;
}
}
}
log4jLog.debug("Finished " + finished + " on this iteration.");
} while (stillUnfinished != null && finished > 0);
// The following is to try and resolve a deadlock in the last
// person's issue. We could do more by trying to adjust the
// issue order for anyone who still has issues, maybe by trying
// each at a time.
if (stillUnfinished != null && finished == 0) {
// deadlock in the scheduling!
// move the precursors (to the last (problem) issue) up in their scheduling
// -- move backward along the last person's issues to find the problem
List<T> oneUserDetails = userDetails.get(stillUnfinished);
int lastIssueDone;
for (lastIssueDone = oneUserDetails.size() - 1;
lastIssueDone > -1 // this has happened before!
&& !issueSchedules.containsKey
((oneUserDetails.get(lastIssueDone)).getKey());
lastIssueDone--) {
}
// -- now move that issue up in the scheduling order
if (previousUnfinishedName != null
&& previousUnfinishedName.equals(stillUnfinished)
&& previousUnfinishedIssueNum < oneUserDetails.size()
&& previousUnfinishedIssueNum == lastIssueDone + 1) {
// this has all the same finished info as last time!
throw new IllegalStateException("The scheduling loop stopped making progress because we can't schedule " + oneUserDetails.get(lastIssueDone + 1));
} else {
// record this info to make sure we aren't looping without progress
previousUnfinishedName = stillUnfinished;
previousUnfinishedIssueNum = lastIssueDone + 1;
// now grab that unfinished issue, get the precursors, and move them forward
T unfinishedTarget = oneUserDetails.get(lastIssueDone + 1);
shiftPrecursors(unfinishedTarget, userDetails, issueSchedules, new HashSet<String>());
}
}
} while (stillUnfinished != null && finished == 0);
return issueSchedules;
}
/**
Adjust position in schedule for precursors of unfinishedTarget.
Note that the HashSet argument was specified only because we need both Set and Cloneable.
*/
private static <T extends IssueWorkDetail<T>> void shiftPrecursors
(T unfinishedTarget,
Map<String,List<T>> userDetails,
Map<String,IssueSchedule<T>> issueSchedules,
HashSet<String> visitedPrecursorKeys) {
Set<T> precursorsToShift = unfinishedTarget.getIssuesToScheduleFirst();
for (T precursor : precursorsToShift) {
if (!issueSchedules.containsKey(precursor.getKey())) {
// find this item in the assignee's list and move it up in order
List<T> assigneeDetails = userDetails.get(precursor.getTimeAssignee());
int firstUnscheduledPos;
for (firstUnscheduledPos = 0;
issueSchedules.containsKey
((assigneeDetails.get(firstUnscheduledPos)).getKey());
firstUnscheduledPos++);
log4jLog.debug("To avoid deadlock, shifting " + precursor.getKey() + " from " + assigneeDetails.indexOf(precursor) + " to " + firstUnscheduledPos);
assigneeDetails.remove(precursor);
assigneeDetails.add(firstUnscheduledPos, precursor);
if (visitedPrecursorKeys.add(precursor.getKey())) {
shiftPrecursors
(precursor, userDetails, issueSchedules,
(HashSet<String>) visitedPrecursorKeys.clone());
} else {
log4jLog.warn("Warning: there's a cycle in the precursor loop for " + precursor.getKey() + "! (Continuing anyway.)");
}
}
}
}
/**
@param fullSchedule contains all the IssueSchedule elements to display
*/
public static <T extends IssueWorkDetail<T>> void writeIssueSchedule
(List<IssueSchedule<T>> fullSchedule,
double multiplier,
boolean showResolved,
java.io.Writer out)
throws java.io.IOException {
out.write("<table border='1'>\n");
out.write("<tr>\n");
out.write("<td>issue</td>\n");
out.write("<td>assignee</td>\n");
out.write("<td>summary</td>\n");
out.write("<td>priority</td>\n");
out.write("<td>start date</td>\n");
out.write("<td>time left</td>\n");
out.write("<td>finish date</td>\n");
out.write("<td>due date</td>\n");
out.write("<td>ranges of hourly work done</td>\n");
out.write("</tr>\n");
Iterator schedules = fullSchedule.iterator();
while (schedules.hasNext()) {
IssueSchedule schedule = (IssueSchedule) schedules.next();
IssueWorkDetail detail = schedule.issue;
if (showResolved
|| !detail.getResolved()) {
String prefix = "", suffix = "";
if (detail.getResolved()) {
prefix = "<strike>";
suffix = "</strike>";
}
out.write("<tr>\n");
// key
out.write("<td>" + prefix + "<a href='/secure/ViewIssue.jspa?key=" + detail.getKey() + "'>" + detail.getKey() + "</a>" + suffix + "</td>\n");
// assignee
out.write("<td>" + detail.getTimeAssignee() + "</td>\n");
// summary
out.write("<td>" + prefix + detail.getSummary() + suffix + "</td>\n");
// priority
out.write("<td>" + (detail.getPriority() - 1) + suffix + "</td>\n");
String value;
// start date
out.write("<td>");
value = WEEKDAY_DATE_TIME.format(schedule.getAdjustedBeginCal().getTime());
if (detail.getDueDate() != null
&& schedule.endDate.after(detail.getDueDate())) {
value = "<font color='red'>" + value + "</font>";
}
out.write(value);
out.write("</td>\n");
// remaining time
out.write("<td>");
out.write(prefix);
int issueEstSeconds = (int) (detail.getEstimate() * multiplier);
if (detail.getEstimate() == 0) { out.write("<font color='orange'>"); }
String hours =
String.valueOf
((issueEstSeconds % (MAX_WORKHOURS_PER_WORKDAY * 3600.0)) / 3600.0);
if (hours.indexOf('.') > -1
&& hours.length() - hours.indexOf('.') > 3) {
hours = hours.substring(0, hours.indexOf('.') + 3);
}
out.write
((int) (issueEstSeconds / (MAX_WORKHOURS_PER_WORKDAY * 3600.0)) + "d "
+ hours + "h");
if (detail.getEstimate() == 0) { out.write("</font>"); }
out.write(suffix);
out.write("</td>\n");
// finish date
out.write("<td>");
value = WEEKDAY_DATE_TIME.format(schedule.getAdjustedEndCal().getTime());
if (detail.getDueDate() != null
&& schedule.endDate.after(detail.getDueDate())) {
value = "<font color='red'>" + value + "</font>";
}
out.write(value);
out.write("</td>\n");
// due date
out.write("<td>");
if (detail.getDueDate() != null) {
value = WEEKDAY_DATE.format(detail.getDueDate());
} else {
value = "none";
}
if (detail.getDueDate() != null
&& schedule.endDate.after(detail.getDueDate())) {
value = "<font color='red'>" + value + "</font>";
}
out.write(value);
out.write("</td>\n");
// working hours
out.write("<td>\n");
out.write(schedule.getHoursWorkedDescription(true).toString());
out.write("</td>\n");
}
out.write("</tr>\n");
}
out.write("</table>\n");
out.flush();
}
public static void main(String[] args) throws Exception {
//log4jLog.setLevel(org.apache.log4j.Level.DEBUG);
java.io.PrintWriter out = null;
try {
out = new java.io.PrintWriter(System.out);
if (args.length > 0) {
out = new java.io.PrintWriter(args[0]);
}
outputTestResults(out);
} finally {
try { out.close(); } catch (Exception e) {}
}
}
public static void outputTestResults(java.io.PrintWriter out) throws Exception {
//log4jLog.setLevel(org.apache.log4j.Level.DEBUG);
final java.text.SimpleDateFormat slashFormatter = new java.text.SimpleDateFormat("yyyy/MM/dd");
final double multiplier = 2.0;
final double dailyHours = MAX_WORKHOURS_PER_WORKDAY;
final int weeklyHours = (int) (WORKDAYS_PER_WEEK * dailyHours);
final Date startDate = SLASH_DATE.parse("2005/04/04");
Map userDetails = new HashMap();
List details1 = new ArrayList();
String user = "trent--team_1";
IssueWorkDetailOriginal test1 =
(new IssueWorkDetailOriginal
("TEST-T1", user, "summary T1", 10 * 3600, 0.0,
slashFormatter.parse("2005/06/01"), null, 1));
IssueWorkDetailOriginal test2 =
(new IssueWorkDetailOriginal
("TEST-T2", user, "summary T2", 5 * 3600, 0.0,
slashFormatter.parse("2005/05/01"), null, 2));
IssueWorkDetailOriginal test3 =
(new IssueWorkDetailOriginal
("TEST-T3", user, "summary T3", 5 * 3600, 0.0, null, null, 3));
IssueWorkDetailOriginal test4 =
(new IssueWorkDetailOriginal
("TEST-T4", user, "summary T4", 4 * 3600, 0.0,
slashFormatter.parse("2005/06/01"), null, 4));
IssueWorkDetailOriginal test5 =
(new IssueWorkDetailOriginal
("TEST-T5", user, "summary T5", 1 * 3600, 0.0,
slashFormatter.parse("2005/05/15"), null, 3));
IssueWorkDetailOriginal test6 =
(new IssueWorkDetailOriginal
("TEST-T6", user, "summary T6", 4 * 3600, 0.0,
slashFormatter.parse("2005/06/01"), null, 3));
details1.add(test1);
details1.add(test2);
details1.add(test3);
details1.add(test4);
details1.add(test5);
details1.add(test6);
test4.getPrecursors().add(test6);
userDetails.put(user, details1);
List details2 = new ArrayList();
user = "nobody--team_1";
details2.add
(new IssueWorkDetailOriginal
("TEST-n1", user, "summary n1", 4 * 3600, 0.0,
slashFormatter.parse("2005/06/01"), null, 0));
userDetails.put(user, details2);
setInitialOrdering(userDetails);
out.println("<br>");
String key1 = ((IssueWorkDetail) details1.get(1)).getKey();
out.println((key1.equals("TEST-T2") ? "pass" : "fail")
+ " (first after simple prioritizing is TEST-T2; got " + key1 + ")");
out.println("<br>");
out.println((details1.indexOf(test4) > details1.indexOf(test6) ? "pass" : "fail")
+ " (a dependant issue comes after its precursor)");
Calendar friMorn = new GregorianCalendar();
friMorn.setTime(slashFormatter.parse("2005/04/29"));
Calendar friEve = (Calendar) friMorn.clone();
friEve.add(Calendar.HOUR_OF_DAY, (int) dailyHours);
out.println("<br>");
out.println((workSecondsBetween(friMorn, friEve, 0.0)
== 0.0 ? "pass" : "fail")
+ " (there are the right number of seconds with no work time;"
+ " wanted " + 0.0
+ " got " + workSecondsBetween(friMorn, friEve, 0.0) + ")");
out.println("<br>");
out.println((workSecondsBetween(friMorn, friEve, dailyHours)
== dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds in a work day;"
+ " wanted " + (dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, friEve, dailyHours) + ")");
Calendar friNoon = (Calendar) friMorn.clone();
friNoon.add(Calendar.HOUR_OF_DAY, (int) dailyHours / 2);
out.println("<br>");
out.println((workSecondsBetween(friMorn, friNoon, dailyHours / 2.0)
== dailyHours / 4 * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds in half a half a work day;"
+ " wanted " + (dailyHours / 4 * 3600)
+ " got " + workSecondsBetween(friMorn, friNoon, dailyHours / 2.0) + ")");
Calendar satEve = (Calendar) friEve.clone();
satEve.add(Calendar.DATE, 1);
out.println("<br>");
out.println((workSecondsBetween(friMorn, satEve, dailyHours)
== dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Sat eve;"
+ " wanted " + (dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, satEve, dailyHours) + ")");
Calendar sunMorn = (Calendar) friEve.clone();
sunMorn.add(Calendar.DATE, 2);
Calendar sunEve = (Calendar) satEve.clone();
sunEve.add(Calendar.DATE, 1);
out.println("<br>");
out.println((workSecondsBetween(friMorn, sunEve, dailyHours)
== dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Sun eve;"
+ " wanted " + (dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, sunEve, dailyHours) + ")");
Calendar monMorn = new GregorianCalendar();
monMorn.setTime(slashFormatter.parse("2005/05/02"));
out.println("<br>");
out.println((workSecondsBetween(sunMorn, monMorn, dailyHours)
== 0 ? "pass" : "fail")
+ " (there are the right number of seconds from Sun morn to Mon morn;"
+ " wanted " + 0
+ " got " + workSecondsBetween(sunMorn, monMorn, dailyHours) + ")");
out.println("<br>");
out.println((workSecondsBetween(friMorn, monMorn, dailyHours)
== dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Mon morn;"
+ " wanted " + (dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, monMorn, dailyHours) + ")");
Calendar monNoon = (Calendar) monMorn.clone();
monNoon.add(Calendar.HOUR_OF_DAY, 4);
out.println("<br>");
out.println((workSecondsBetween(friMorn, monNoon, dailyHours)
== (int) (1.5 * dailyHours * 3600) ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Mon noon;"
+ " wanted " + ((int) (1.5 * dailyHours * 3600))
+ " got " + workSecondsBetween(friMorn, monNoon, dailyHours) + ")");
Calendar monEve = (Calendar) monMorn.clone();
monEve.add(Calendar.HOUR_OF_DAY, (int) dailyHours);
out.println("<br>");
out.println((workSecondsBetween(friMorn, monEve, dailyHours)
== 2 * dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Mon eve;"
+ " wanted " + (2 * dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, monEve, dailyHours) + ")");
out.println("<br>");
out.println((workSecondsBetween(friMorn, monNoon, dailyHours / 2.0)
== 1.5 * dailyHours / 2 * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Mon noon"
+ " doing half time;"
+ " wanted " + (1.5 * dailyHours / 2 * 3600)
+ " got " + workSecondsBetween(friMorn, monNoon, dailyHours / 2.0) + ")");
Calendar tuesEve = (Calendar) monEve.clone();
tuesEve.add(Calendar.DAY_OF_WEEK, 1);
out.println("<br>");
out.println((workSecondsBetween(monMorn, tuesEve, dailyHours)
== 2 * dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Mon morn to Tues eve;"
+ " wanted " + (2 * dailyHours * 3600)
+ " got " + workSecondsBetween(monMorn, tuesEve, dailyHours) + ")");
monEve.add(Calendar.WEEK_OF_YEAR, 1);
out.println("<br>");
out.println((workSecondsBetween(friMorn, monEve, dailyHours)
== 7 * dailyHours * 3600 ? "pass" : "fail")
+ " (there are the right number of seconds from Fri morn to Mon 2 eves away;"
+ " wanted " + (7 * dailyHours * 3600)
+ " got " + workSecondsBetween(friMorn, monEve, dailyHours) + ")");
{
//out.println("<h3>nextRateChange</h3>");
Date first = slashFormatter.parse("2005/04/01");
Date eighth = slashFormatter.parse("2005/04/08");
Date fifteenth = slashFormatter.parse("2005/04/15");
Date twentysecond = slashFormatter.parse("2005/04/22");
Date twentyninth = slashFormatter.parse("2005/04/29");
WeeklyWorkHours range = new WeeklyWorkHours();
range.inject(first, 10.0);
range.inject(eighth, 5.0);
range.inject(fifteenth, 40.0);
range.inject(twentysecond, 60.0);
range.inject(twentyninth, 20.0);
Date before = slashFormatter.parse("2005/03/31");
out.println("<br>");
try {
range.nextRateChange(before);
out.println("fail (invalid date didn't throw an exception)");
} catch (IllegalStateException e) {
out.println("pass (invalid date threw an exception)");
}
Date second = slashFormatter.parse("2005/04/02");
out.println("<br>");
out.println((range.nextRateChange(second).equals(eighth) ? "pass" : "fail")
+ " (the next rate change after the 2nd is the 8th)");
Date ninth = slashFormatter.parse("2005/04/09");
out.println("<br>");
out.println((range.nextRateChange(ninth).equals(fifteenth) ? "pass" : "fail")
+ " (the next rate change after the 9th is the 15th)");
out.println("<br>");
out.println((range.nextRateChange(fifteenth).equals(twentyninth) ? "pass" : "fail")
+ " (the next rate change after the 15th is the 29th)");
out.println("<br>");
out.println((range.nextRateChange(twentysecond).equals(twentyninth) ? "pass" : "fail")
+ " (the next rate change after the 22nd is the 29th)");
Date thirtieth = slashFormatter.parse("2005/04/30");
out.println("<br>");
out.println((range.nextRateChange(thirtieth) == null ? "pass" : "fail")
+ " (there is no rate change after the 30th)");
}
{
//out.println("<h3>injectAndAdjust pass/fails</h3>");
Date first = slashFormatter.parse("2005/04/01");
Date eighth = slashFormatter.parse("2005/04/08");
Date fifteenth = slashFormatter.parse("2005/04/15");
Date twentysecond = slashFormatter.parse("2005/04/22");
Date twentyninth = slashFormatter.parse("2005/04/29");
WeeklyWorkHours origRange = new WeeklyWorkHours();
origRange.inject(first, 10.0);
origRange.inject(eighth, 5.0);
origRange.inject(fifteenth, 40.0);
origRange.inject(twentysecond, 60.0);
origRange.inject(twentyninth, 20.0);
WeeklyWorkHours workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(first, eighth, 8.0);
out.println("<br>");
out.println((workingRange.size() == 5 ? "pass" : "fail")
+ " (adjusting the first date range doesn't affect others)");
try {
workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(first, fifteenth, 6.0);
out.println("<br>");
out.println("fail (cannot drop any week below 0 hours)");
} catch (IllegalStateException e) {
out.println("<br>");
out.println("pass (cannot drop any week below 0 hours)");
}
}
{
//out.println("<h3>findNextEstBegin</h3>");
Date first = slashFormatter.parse("2005/04/01");
Date fourth = slashFormatter.parse("2005/04/04");
Date eleventh = slashFormatter.parse("2005/04/11");
Date eighteenth = slashFormatter.parse("2005/04/18");
Date twentyfifth = slashFormatter.parse("2005/04/25");
Date may2 = slashFormatter.parse("2005/05/02");
WeeklyWorkHours origRange = new WeeklyWorkHours();
origRange.inject(fourth, 20.0);
origRange.inject(eleventh, 5.0);
origRange.inject(eighteenth, 40.0);
origRange.inject(twentyfifth, 60.0);
origRange.inject(may2, 20.0);
WeeklyWorkHours workingRange;
Calendar thisEstBegin = Calendar.getInstance();
thisEstBegin.setTime(fourth);
workingRange = (WeeklyWorkHours) origRange.clone();
NextBeginAndHoursWorked nextAndHours =
findNextEstBegin(thisEstBegin, 1 * 3600, workingRange, 0);
Date taskEnd = previousTaskEnd(nextAndHours.nextBegin, 1 * 3600);
int offsetMillis = (int) (nextAndHours.nextBegin.getTime().getTime() - taskEnd.getTime());
out.println("<br>");
out.println((offsetMillis == 0 ? "pass" : "fail")
+ " (on the 4th, a 1-hour issue -- at 20 hours/week --"
+ " will end immediately before the next one begins)");
workingRange = (WeeklyWorkHours) origRange.clone();
nextAndHours = findNextEstBegin(thisEstBegin, 16 * 3600, workingRange, 0);
taskEnd = previousTaskEnd(nextAndHours.nextBegin, 16 * 3600);
Date eighth = slashFormatter.parse("2005/04/08");
out.println("<br>");
out.println((nextAndHours.nextBegin.getTime().equals(eighth) ? "pass" : "fail")
+ " (on the 4th, a 16-hour issue -- at 20 hours/week --"
+ " makes the next begin date the 8th;"
+ " got " + nextAndHours.nextBegin.getTime() + ")");
out.println("<br>");
offsetMillis = (int) (nextAndHours.nextBegin.getTime().getTime() - taskEnd.getTime());
out.println((offsetMillis == 16 * 3600 * 1000 ? "pass" : "fail")
+ " (on the 4th, a 16-hour issue -- at 20 hours/week --"
+ " will end the day before the next one begins;"
+ " got " + (offsetMillis / 3600000) + " hours)");
workingRange = (WeeklyWorkHours) origRange.clone();
nextAndHours = findNextEstBegin(thisEstBegin, 22 * 3600, workingRange, 0);
Date thirteenth = slashFormatter.parse("2005/04/13");
out.println("<br>");
out.println((nextAndHours.nextBegin.getTime().equals(thirteenth) ? "pass" : "fail")
+ " (on the 4th, a 22-hour issue -- at 20 then 5 hours/week --"
+ " makes the next begin date the 13th;"
+ " got " + nextAndHours.nextBegin.getTime() + ")");
}
{
out.println("<h3>injectAndAdjust ranges</h3>");
out.println("<table>");
Date first = slashFormatter.parse("2005/04/01");
Date eighth = slashFormatter.parse("2005/04/08");
Date fifteenth = slashFormatter.parse("2005/04/15");
Date twentysecond = slashFormatter.parse("2005/04/22");
Date twentyninth = slashFormatter.parse("2005/04/29");
WeeklyWorkHours origRange = new WeeklyWorkHours();
origRange.inject(first, 10.0);
origRange.inject(eighth, 5.0);
origRange.inject(fifteenth, 40.0);
origRange.inject(twentysecond, 60.0);
origRange.inject(twentyninth, 20.0);
out.println(" <tr>");
out.println(" <td>original:</td>");
out.println(" <td>" + origRange.toShortString() + "</td>");
out.println(" </tr>");
WeeklyWorkHours workingRange;
workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(first, fifteenth, 0.0);
out.println(" <tr>");
out.println(" <td>-0 in first 2 ranges</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(first, eighth, 8.0);
out.println(" <tr>");
out.println(" <td>-8 in first range</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(twentysecond, twentyninth, 55.0);
workingRange.injectAndAdjust(fifteenth, twentysecond, 35.0);
out.println(" <tr>");
out.println(" <td>-55 in fourth range, -35 in third</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
Date second = slashFormatter.parse("2005/04/02");
Date sixteenth = slashFormatter.parse("2005/04/16");
workingRange.injectAndAdjust(second, sixteenth, 4.0);
out.println(" <tr>");
out.println(" <td>-4 from 2nd to 16th</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
Date tenth = slashFormatter.parse("2005/04/10");
workingRange.injectAndAdjust(second, tenth, 5.0);
out.println(" <tr>");
out.println(" <td>-5 from 2nd to 10th</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
Date twentieth = slashFormatter.parse("2005/04/20");
workingRange.injectAndAdjust(fifteenth, twentieth, 35.0);
out.println(" <tr>");
out.println(" <td>-35 from 15th to 20th: </td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
workingRange.injectAndAdjust(fifteenth, twentysecond, 35.0);
out.println(" <tr>");
out.println(" <td>-35 from 15th to 22nd</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
Date twenthEighth = slashFormatter.parse("2005/04/28");
Date may2 = slashFormatter.parse("2005/05/02");
workingRange.injectAndAdjust(twenthEighth, may2, 20.0);
out.println(" <tr>");
out.println(" <td>-20 from 28th to 2nd</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
workingRange = (WeeklyWorkHours) origRange.clone();
Date may22 = slashFormatter.parse("2005/05/22");
workingRange.injectAndAdjust(may2, may22, 20.0);
out.println(" <tr>");
out.println(" <td>-20 from 2nd to 22nd</td>");
out.println(" <td>" + workingRange.toShortString() + "</td>");
out.println(" </tr>");
out.println("</table>");
}
{
out.println("<p>Showing schedule for our samples...<p>");
List sortedDetailKeys = new ArrayList(userDetails.keySet());
Collections.sort(sortedDetailKeys);
for (Iterator users = sortedDetailKeys.iterator(); users.hasNext(); ) {
Map<String,WeeklyWorkHours> userRanges =
new HashMap<String,WeeklyWorkHours>();
user = (String) users.next();
WeeklyWorkHours range = new WeeklyWorkHours();
range.inject(slashFormatter.parse("2005/04/01"), new Double(weeklyHours));
userRanges.put(user, range);
List schedules =
createIssueSchedules
((List) userDetails.get(user), userRanges, new HashMap(), multiplier,
slashFormatter.parse("2005/04/01"));
writeIssueSchedule(schedules, multiplier, true, out);
}
}
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/HmiCore | HmiXml/test/src/hmi/xml/XMLTokenizerTest.java | 28264 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
/*
* XMLTokenizer JUnit test
*/
package hmi.xml;
import static org.junit.Assert.*;
import org.junit.*;
import hmi.util.*;
import java.io.*;
import java.net.*;
/**
* JUnit test for hmi.xml.XMLTokenizer
*/
public class XMLTokenizerTest
{
public XMLTokenizerTest()
{
}
@Before
public void setUp()
{ // common initialization, executed for every test.
}
@After
public void tearDown()
{
}
/**
* a few basic tests
*/
@Test
public void basics()
{
new XMLTokenizer();
}
/**
* test XMLTokenizer for a minimal xml file.
*/
@Test
public void basics2()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader basictest1 = testRes.getReader("basictest1.xml");
assertTrue(basictest1 != null);
XMLTokenizer tokenizer = new XMLTokenizer(basictest1);
try
{
assertTrue(tokenizer.atSTag("test"));
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("tg"));
tokenizer.takeSTag("tg");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("tg"));
tokenizer.takeETag();
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("test"));
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* test XMLTokenizer for a minimal xml file.
*
* @throws IOException
*/
@Test
public void testFileConstructor() throws IOException
{
// String udir = System.getProperty("user.dir");
String sharedprojectdir = System.getProperty("shared.project.root");
String udir = sharedprojectdir + "/HmiCore/HmiXml";
// System.out.println("user.dir = " + udir);
File testFile = new File(udir + "/test/resource/XmlTokenizerTests/basictest1.xml"); // requires a copy of basictest1.xml inside the
// test/src/hmi/xml directory
// File testFile = new File("../../../resource/XmlTokenizerTests/basictest1.xml"); // does work only from the right user dir
XMLTokenizer tokenizer = new XMLTokenizer(testFile);
assertTrue(tokenizer.atSTag("test"));
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("tg"));
tokenizer.takeSTag("tg");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("tg"));
tokenizer.takeETag();
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("test"));
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
/**
* test XMLTokenizer for a minimal xml file, accessed via an file URL
*
* @throws IOException
*/
@Test
public void testURLConstructor() throws IOException
{
String sharedprojectdir = System.getProperty("shared.project.root");
String udir = sharedprojectdir + "/HmiCore/HmiXml";
// System.out.println("user.dir = " + udir);
URL testFileURL = new URL("file:///" + udir + "/test/resource/XmlTokenizerTests/basictest1.xml");
XMLTokenizer tokenizer = new XMLTokenizer(testFileURL);
assertTrue(tokenizer.atSTag("test"));
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("tg"));
tokenizer.takeSTag("tg");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("tg"));
tokenizer.takeETag();
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
assertTrue(tokenizer.atETag("test"));
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
/**
* test basic usage of namespaces when namespace recognition is turned off
*/
@Test
public void namespace1a()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader namespacetest1 = testRes.getReader("namespacetest1.xml");
XMLTokenizer tokenizer = new XMLTokenizer(namespacetest1);
tokenizer.setRecognizeNamespaces(false);
try
{
assertTrue(tokenizer.atSTag("ns:test"));
tokenizer.takeSTag("ns:test");
assertTrue(tokenizer.atSTag("ns:innertag"));
tokenizer.takeSTag("ns:innertag");
assertTrue(tokenizer.atETag("ns:innertag"));
tokenizer.takeETag("ns:innertag");
assertTrue(tokenizer.atETag("ns:test"));
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* test basic usage of namespaces: explicit declaration of ns, tags with ns labels
*/
@Test
public void namespace1b()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader namespacetest1 = testRes.getReader("namespacetest1.xml");
XMLTokenizer tokenizer = new XMLTokenizer(namespacetest1);
tokenizer.setRecognizeNamespaces(true);
String expectedNamespace = "http://hmi.ns.test";
try
{
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atETag("test"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* test basic usage of default namespaces.
*/
@Test
public void namespace2()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader namespacetest2 = testRes.getReader("namespacetest2.xml");
XMLTokenizer tokenizer = new XMLTokenizer(namespacetest2);
tokenizer.setRecognizeNamespaces(true);
String expectedNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
try
{
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atETag("test"));
assertTrue(tokenizer.getNamespace() == expectedNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* combined named namespace and default namespace
*/
@Test
public void namespace3()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader namespacetest3 = testRes.getReader("namespacetest3.xml");
XMLTokenizer tokenizer = new XMLTokenizer(namespacetest3);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
String expectedNSNamespace = "ns-namespace"; // this is declared to be the default namespace
String expectedEXNamespace = "ex-namespace"; // this is declared to be the default namespace
try
{
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNSNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNSNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atSTag("sometag"));
// System.out.println("log:" + tokenizer.getLog());
// System.out.println("Sometag-namespace:" + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeSTag("sometag");
assertTrue(tokenizer.atETag("sometag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atSTag("extratag"));
assertTrue(tokenizer.getNamespace() == expectedEXNamespace);
tokenizer.takeSTag("extratag");
assertTrue(tokenizer.atETag("extratag"));
assertTrue(tokenizer.getNamespace() == expectedEXNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atETag("test"));
// System.out.println("ETAG-namespace:" + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* combined named namespace and default namespace
*/
@Test
public void namespace5()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader namespacetest5 = testRes.getReader("namespacetest5.xml");
XMLTokenizer tokenizer = new XMLTokenizer(namespacetest5);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "default-namespace"; // this is declared to be the default namespace
// String expectedNSNamespace = "ns-namespace"; // this is declared to be the default namespace
// String expectedEXNamespace = "ex-namespace"; // this is declared to be the default namespace
try
{
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == null);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("innertag"));
// System.out.println("innertag ns: " + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atSTag("sometag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeSTag("sometag");
tokenizer.takeETag("sometag");
assertTrue(tokenizer.atETag("innertag"));
// System.out.println("/innertag ns: " + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atSTag("nonamespace"));
// System.out.println("nonamespace ns:" + tokenizer.getNamespace() );
assertTrue(tokenizer.getNamespace() == null);
tokenizer.takeSTag("nonamespace");
assertTrue(tokenizer.atSTag("sometag"));
assertTrue(tokenizer.getNamespace() == null);
tokenizer.takeSTag("sometag");
tokenizer.takeETag("sometag");
assertTrue(tokenizer.atETag("nonamespace"));
assertTrue(tokenizer.getNamespace() == null);
tokenizer.takeETag("nonamespace");
assertTrue(tokenizer.atETag("test"));
// System.out.println("ETAG-namespace:" + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == null);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* test attribute namepaces
*/
@Test
public void attributeNamespace()
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader attributeNamespacetest = testRes.getReader("attributeNamespacetest.xml");
XMLTokenizer tokenizer = new XMLTokenizer(attributeNamespacetest);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
String expectedNSNamespace = "ns-namespace"; // this is declared to be the default namespace
String expectedEXNamespace = "ex-namespace"; // this is declared to be the default namespace
String expectedAttr0 = "value0";
String expectedAttr1 = "value1";
String expectedAttr2NS = "value2";
try
{
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNSNamespace);
String val0 = tokenizer.getAttribute(expectedNSNamespace + ":atr0");
// //System.out.println("val0=" + val0);
assertTrue(val0 != null);
assertTrue(val0.equals(expectedAttr0));
String val1 = tokenizer.getAttribute("atr1");
assertTrue(val1 != null);
assertTrue(val1.equals(expectedAttr1));
String val2 = tokenizer.getAttribute(expectedNSNamespace + ":atr2");
assertTrue(val2 != null);
assertTrue(val2.equals(expectedAttr2NS));
// String ns2 = tokenizer.getAttributeNamespace("atr2");
// assertTrue(ns2 != null);
// assertTrue(ns2.equals(expectedNS));
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedNSNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atSTag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("innertag");
assertTrue(tokenizer.atETag("innertag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag("innertag");
assertTrue(tokenizer.atSTag("sometag"));
// System.out.println("log:" + tokenizer.getLog());
// System.out.println("Sometag-namespace:" + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeSTag("sometag");
assertTrue(tokenizer.atETag("sometag"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atSTag("extratag"));
assertTrue(tokenizer.getNamespace() == expectedEXNamespace);
tokenizer.takeSTag("extratag");
assertTrue(tokenizer.atETag("extratag"));
assertTrue(tokenizer.getNamespace() == expectedEXNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atETag("test"));
// System.out.println("ETAG-namespace:" + tokenizer.getNamespace());
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
catch (Exception e)
{
System.out.println("XMLTokenizerTest: " + e);
assertTrue(false); // Exceptions should not happen
}
}
/**
* skipTag test
* @throws IOException
*/
@Test
public void skipTagTest() throws IOException
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader xmlsection = testRes.getReader("getXMLSectionTest.xml");
XMLTokenizer tokenizer = new XMLTokenizer(xmlsection);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("preamble"));
tokenizer.takeSTag("preamble");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
tokenizer.takeSTag("nested");
tokenizer.takeETag("nested");
tokenizer.takeETag("preamble");
// Now the main section that we want to skip starts:
assertTrue(tokenizer.atSTag("skippedtag"));
tokenizer.skipTag(); // skip it ...
// Some extras afterwards:
assertTrue(tokenizer.atSTag("moretags"));
tokenizer.takeSTag();
tokenizer.takeCharData();
tokenizer.takeETag("moretags");
assertTrue(tokenizer.atETag("test"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
/**
* getXMLSection test
*
* @throws IOException
*/
@Test
public void getXMLSectionTest() throws IOException
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader xmlsection = testRes.getReader("getXMLSectionTest.xml");
XMLTokenizer tokenizer = new XMLTokenizer(xmlsection);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
String expectedSection = "<ns:skippedtag attr=\"val\" xmlns:ns=\"http://ns\">" + OS.getNewline() + " <innertag> chardata "
+ OS.getNewline() + " <nestedtag> chardata" + OS.getNewline() + " <ns:skippedtag>" + OS.getNewline()
+ " more data" + OS.getNewline() + " </ns:skippedtag>" + OS.getNewline()
+ " </nestedtag>" + OS.getNewline() + " </innertag>" + OS.getNewline()
+ " <sometag xmlns:some=\"some-namespace\"/>" + OS.getNewline() + " <ns:extratag > moredata </ns:extratag>"
+ OS.getNewline() + " </ns:skippedtag>";
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("preamble"));
tokenizer.takeSTag("preamble");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
tokenizer.takeSTag("nested");
tokenizer.takeETag("nested");
tokenizer.takeETag("preamble");
// Now the main section that we want starts:
assertTrue(tokenizer.atSTag("skippedtag"));
String skipped = tokenizer.getXMLSection(); // get the section ...
// System.out.println("skipped:\n" + skipped);
// System.out.println("expected:\n" + expectedSection);
// System.out.println("Diff: " + StringUtil.showDiff(skipped, expectedSection));
// System.out.println("DiffPos: " + StringUtil.diffPos(skipped, expectedSection));
assertEquals(skipped, expectedSection); // test the section we extracted
// Some extras afterwards:
assertTrue(tokenizer.atSTag("moretags"));
tokenizer.takeSTag();
tokenizer.takeCharData();
tokenizer.takeETag("moretags");
assertTrue(tokenizer.atETag("test"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
@Test
public void getEmptyXMLSectionTest() throws IOException
{
XMLTokenizer tokenizer = new XMLTokenizer("<test/>");
assertTrue(tokenizer.atSTag("test"));
String skipped = tokenizer.getXMLSection();
assertEquals(skipped, "<test/>");
}
@Test
public void getEmptyXMLSectionTestWithAttribute() throws IOException
{
XMLTokenizer tokenizer = new XMLTokenizer("<test id=\"ident\"/>");
assertTrue(tokenizer.atSTag("test"));
String skipped = tokenizer.getXMLSection();
assertEquals(skipped, "<test id=\"ident\"/>");
}
@Test
public void getEmptyXMLSectionTestWithDangerousAttribute() throws IOException
{
XMLTokenizer tokenizer = new XMLTokenizer("<test id=\">ident\"/>"); // escaped > char (unescaped > chars are not allowed)
assertTrue(tokenizer.atSTag("test"));
String skipped = tokenizer.getXMLSection();
assertEquals(skipped, "<test id=\">ident\"/>");
}
@Test
public void getEmptyXMLSectionTestWithClosingTag() throws IOException
{
XMLTokenizer tokenizer = new XMLTokenizer("<test></test>");
assertEquals("<test></test>", tokenizer.getXMLSection());
}
@Test
public void getXMLSectionContentTest2() throws IOException
{
XMLTokenizer tok = new XMLTokenizer("<tag>blah</tag>");
tok.takeSTag("tag");
assertEquals("blah", tok.getXMLSectionContent());
}
/**
* getXMLSectionContent test, where we just want the contents, without the surrounding <tag> </tag> of the XML section
*
* @throws IOException
*/
@Test
public void getXMLSectionContentTest() throws IOException
{
Resources testRes = new Resources("XmlTokenizerTests");
Reader xmlsection = testRes.getReader("getXMLSectionTest.xml");
XMLTokenizer tokenizer = new XMLTokenizer(xmlsection);
tokenizer.setRecognizeNamespaces(true);
String expectedDefaultNamespace = "http://hmi.ns.test"; // this is declared to be the default namespace
String expectedSection = OS.getNewline() + " <innertag> chardata " + OS.getNewline() + " <nestedtag> chardata"
+ OS.getNewline() + " <ns:skippedtag>" + OS.getNewline() + " more data" + OS.getNewline()
+ " </ns:skippedtag>" + OS.getNewline() + " </nestedtag>" + OS.getNewline() + " </innertag>"
+ OS.getNewline() + " <sometag xmlns:some=\"some-namespace\"/>" + OS.getNewline()
+ " <ns:extratag > moredata </ns:extratag>" + OS.getNewline() + " ";
assertTrue(tokenizer.atSTag("test"));
// critical: even this tag, where the xmlns is added already takes the new ns namespace into account
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
// System.out.println("log:" + tokenizer.getLog());
tokenizer.takeSTag("test");
assertTrue(tokenizer.atSTag("preamble"));
tokenizer.takeSTag("preamble");
assertTrue(tokenizer.atCharData());
tokenizer.takeCharData();
tokenizer.takeSTag("nested");
tokenizer.takeETag("nested");
tokenizer.takeETag("preamble");
// Now the main section that we want starts:
assertTrue(tokenizer.atSTag("skippedtag"));
String skipped = tokenizer.getXMLSectionContent(); // get the section ...
// System.out.println("skipped:\n[" + skipped + "]");
// System.out.println("expected:\n[" + expectedSection + "]");
// System.out.println("Diff: " + StringUtil.showDiff(skipped, expectedSection));
// System.out.println("DiffPos: " + StringUtil.diffPos(skipped, expectedSection));
assertEquals(skipped, expectedSection); // test the section we extracted
tokenizer.takeETag("skippedtag");
// Some extras afterwards:
assertTrue(tokenizer.atSTag("moretags"));
tokenizer.takeSTag();
tokenizer.takeCharData();
tokenizer.takeETag("moretags");
assertTrue(tokenizer.atETag("test"));
assertTrue(tokenizer.getNamespace() == expectedDefaultNamespace);
tokenizer.takeETag();
assertTrue(tokenizer.atEndOfDocument());
}
@Test
public void getXMLSectionEmptyContentTest() throws IOException
{
XMLTokenizer tokenizer = new XMLTokenizer("<test/>");
tokenizer.takeSTag("test");
assertEquals("", tokenizer.getXMLSectionContent());
}
}
| lgpl-3.0 |
taccoraw/gumtree | gen.antlr/src/main/java/fr/labri/gumtree/gen/antlr/AbstractAntlrTreeGenerator.java | 3096 | package fr.labri.gumtree.gen.antlr;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Parser;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import fr.labri.gumtree.io.TreeGenerator;
import fr.labri.gumtree.tree.Tree;
public abstract class AbstractAntlrTreeGenerator extends TreeGenerator {
protected Map<CommonTree, Tree> trees;
protected static Map<Integer, String> names;
protected static Map<Integer, Integer> chars;
protected CommonTokenStream tokens;
public AbstractAntlrTreeGenerator() {
loadNames();
}
protected abstract CommonTree getStartSymbol(String file) throws RecognitionException, IOException;
@Override
public Tree generate(String file) throws IOException {
try {
loadChars(file);
CommonTree ct = getStartSymbol(file);
trees = new HashMap<CommonTree, Tree>();
return toTree(ct);
} catch (RecognitionException e) {
System.out.println("at " + e.line + ":" + e.charPositionInLine);
e.printStackTrace();
}
return null;
}
protected abstract Parser getEmptyParser();
protected Tree toTree(CommonTree ct) {
Tree t = null;
if (ct.getText().equals(names.get(ct.getType())))
t = new Tree(ct.getType());
else
t = new Tree(ct.getType(), ct.getText());
t.setTypeLabel(names.get(ct.getType()));
int[] pos = getPosAndLength(ct);
t.setPos(pos[0]);
t.setLength(pos[1]);
if (ct.getParent() != null )
t.setParentAndUpdateChildren(trees.get(ct.getParent()));
if (ct.getChildCount() > 0) {
trees.put(ct, t);
for (CommonTree cct : (List<CommonTree>) ct.getChildren()) toTree(cct);
}
return t;
}
private void loadNames() {
names = new HashMap<Integer, String>();
Parser p = getEmptyParser();
for (Field f : p.getClass().getFields()) {
if (f.getType().equals(int.class)) {
try {
names.put(f.getInt(p), f.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void loadChars(String file) throws IOException {
chars = new HashMap<Integer, Integer>();
BufferedReader r = new BufferedReader(new FileReader(file));
int line = 0;
int chrs = 0;
while (r.ready()) {
String cur = r.readLine();
chrs += cur.length() + 1;
chars.put(line, chrs);
line++;
}
r.close();
}
@SuppressWarnings("serial")
private int[] getPosAndLength(CommonTree ct) {
//if (ct.getTokenStartIndex() == -1 || ct.getTokenStopIndex() == -1) System.out.println("yoooo" + ct.toStringTree());
int start = (ct.getTokenStartIndex() == -1) ? 0 : new CommonToken(tokens.get(ct.getTokenStartIndex())) { int getPos() { return start; } } .getPos();
int stop = (ct.getTokenStopIndex() == -1) ? 0 : new CommonToken(tokens.get(ct.getTokenStopIndex())) { int getPos() { return stop; } } .getPos();
return new int[] { start, stop - start + 1 };
}
}
| lgpl-3.0 |
hea3ven/BuildCraft | common/buildcraft/silicon/TileProgrammingTable.java | 5714 | /**
* Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.silicon;
import java.util.List;
import io.netty.buffer.ByteBuf;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import buildcraft.BuildCraftCore;
import buildcraft.api.recipes.BuildcraftRecipeRegistry;
import buildcraft.api.recipes.IProgrammingRecipe;
import buildcraft.core.lib.network.command.CommandWriter;
import buildcraft.core.lib.network.command.ICommandReceiver;
import buildcraft.core.lib.network.command.PacketCommand;
import buildcraft.core.lib.utils.NetworkUtils;
import buildcraft.core.lib.utils.StringUtils;
public class TileProgrammingTable extends TileLaserTableBase implements IInventory, ISidedInventory, ICommandReceiver {
public static final int WIDTH = 6;
public static final int HEIGHT = 4;
public String currentRecipeId = "";
public IProgrammingRecipe currentRecipe;
public List<ItemStack> options;
public int optionId;
private boolean queuedNetworkUpdate = false;
private void queueNetworkUpdate() {
queuedNetworkUpdate = true;
}
@Override
public boolean canUpdate() {
return !FMLCommonHandler.instance().getEffectiveSide().isClient();
}
@Override
public void updateEntity() { // WARNING: run only server-side, see canUpdate()
super.updateEntity();
if (queuedNetworkUpdate) {
sendNetworkUpdate();
queuedNetworkUpdate = false;
}
if (currentRecipe == null) {
return;
}
if (this.getStackInSlot(0) == null) {
currentRecipe = null;
return;
}
if (optionId >= 0 && getEnergy() >= currentRecipe.getEnergyCost(options.get(optionId))) {
if (currentRecipe.canCraft(this.getStackInSlot(0))) {
ItemStack remaining = currentRecipe.craft(this.getStackInSlot(0), options.get(optionId));
if (remaining != null && remaining.stackSize > 0) {
setEnergy(0);
decrStackSize(0, remaining.stackSize);
outputStack(remaining, this, 1, false);
}
}
findRecipe();
}
}
/* IINVENTORY */
@Override
public int getSizeInventory() {
return 2;
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
super.setInventorySlotContents(slot, stack);
if (slot == 0) {
findRecipe();
}
}
@Override
public String getInventoryName() {
return StringUtils.localize("tile.programmingTableBlock.name");
}
@Override
public void readData(ByteBuf stream) {
super.readData(stream);
currentRecipeId = NetworkUtils.readUTF(stream);
optionId = stream.readUnsignedByte();
updateRecipe();
}
@Override
public void writeData(ByteBuf stream) {
super.writeData(stream);
NetworkUtils.writeUTF(stream, currentRecipeId);
stream.writeByte(optionId);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
if (nbt.hasKey("recipeId") && nbt.hasKey("optionId")) {
currentRecipeId = nbt.getString("recipeId");
optionId = nbt.getInteger("optionId");
} else {
currentRecipeId = null;
}
updateRecipe();
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
if (currentRecipeId != null) {
nbt.setString("recipeId", currentRecipeId);
nbt.setByte("optionId", (byte) optionId);
}
}
@Override
public int getRequiredEnergy() {
if (hasWork()) {
return currentRecipe.getEnergyCost(options.get(optionId));
} else {
return 0;
}
}
public void findRecipe() {
String oldId = currentRecipeId;
currentRecipeId = null;
if (getStackInSlot(0) != null) {
for (IProgrammingRecipe recipe : BuildcraftRecipeRegistry.programmingTable.getRecipes()) {
if (recipe.canCraft(getStackInSlot(0))) {
currentRecipeId = recipe.getId();
break;
}
}
}
if ((oldId != null && !oldId.equals(currentRecipeId)) || (oldId == null && currentRecipeId != null)) {
optionId = -1;
updateRecipe();
queueNetworkUpdate();
}
}
public void updateRecipe() {
currentRecipe = BuildcraftRecipeRegistry.programmingTable.getRecipe(currentRecipeId);
if (currentRecipe != null) {
options = currentRecipe.getOptions(WIDTH, HEIGHT);
} else {
options = null;
}
}
public void rpcSelectOption(final int pos) {
BuildCraftCore.instance.sendToServer(new PacketCommand(this, "select", new CommandWriter() {
public void write(ByteBuf data) {
data.writeByte(pos);
}
}));
}
@Override
public void receiveCommand(String command, Side side, Object sender, ByteBuf stream) {
if (side.isServer() && "select".equals(command)) {
optionId = stream.readUnsignedByte();
if (optionId >= options.size()) {
optionId = 0;
}
queueNetworkUpdate();
}
}
@Override
public boolean hasWork() {
return currentRecipe != null && optionId >= 0 && this.getStackInSlot(1) == null;
}
@Override
public boolean canCraft() {
return hasWork();
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
return slot == 0 || stack == null;
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int[] getAccessibleSlotsFromSide(int side) {
return new int[] {0, 1};
}
@Override
public boolean canInsertItem(int slot, ItemStack stack, int side) {
return slot == 0;
}
@Override
public boolean canExtractItem(int slot, ItemStack stack, int side) {
return slot == 1;
}
}
| lgpl-3.0 |
Ortolang/diffusion | comp/src/main/java/fr/ortolang/diffusion/template/MessageResolverMethod.java | 3049 | package fr.ortolang.diffusion.template;
/*
* #%L
* ORTOLANG
* A online network structure for hosting language resources and tools.
* *
* Jean-Marie Pierrel / ATILF UMR 7118 - CNRS / Université de Lorraine
* Etienne Petitjean / ATILF UMR 7118 - CNRS
* Jérôme Blanchard / ATILF UMR 7118 - CNRS
* Bertrand Gaiffe / ATILF UMR 7118 - CNRS
* Cyril Pestel / ATILF UMR 7118 - CNRS
* Marie Tonnelier / ATILF UMR 7118 - CNRS
* Ulrike Fleury / ATILF UMR 7118 - CNRS
* Frédéric Pierre / ATILF UMR 7118 - CNRS
* Céline Moro / ATILF UMR 7118 - CNRS
* *
* This work is based on work done in the equipex ORTOLANG (http://www.ortolang.fr/), by several Ortolang contributors (mainly CNRTL and SLDR)
* ORTOLANG is funded by the French State program "Investissements d'Avenir" ANR-11-EQPX-0032
* %%
* Copyright (C) 2013 - 2015 Ortolang Team
* %%
* 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%
*/
import freemarker.template.DefaultArrayAdapter;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class MessageResolverMethod implements TemplateMethodModelEx {
private ResourceBundle notification;
public MessageResolverMethod(Locale locale) {
this.notification = ResourceBundle.getBundle("notification", locale);
}
@Override
public Object exec(List arguments) throws TemplateModelException {
String key = arguments.get(0).toString();
if (notification.containsKey(key)) {
String string = notification.getString(key);
if (arguments.size() == 2 && arguments.get(1) != null) {
Object args = arguments.get(1);
if (args instanceof DefaultArrayAdapter) {
Object[] adaptedObject = (Object[]) ((DefaultArrayAdapter) args).getAdaptedObject(Object[].class);
string = MessageFormat.format(string, adaptedObject);
} else if (args instanceof SimpleScalar) {
string = MessageFormat.format(string, ((SimpleScalar) args).getAsString());
} else {
string = MessageFormat.format(string, args);
}
}
return string;
}
return "";
}
}
| lgpl-3.0 |
ericcornelissen/NervousFish | app/src/test/java/com/nervousfish/nervousfish/modules/pairing/events/BluetoothConnectedEventTest.java | 841 | package com.nervousfish.nervousfish.modules.pairing.events;
import com.nervousfish.nervousfish.modules.pairing.IBluetoothThread;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class BluetoothConnectedEventTest {
@Test
public void testBluetoothConnectedEvent() {
new BluetoothConnectedEvent(mock(IBluetoothThread.class));
}
@Test(expected = NullPointerException.class)
public void testBluetoothConnectedEventGetThreadNull() {
new BluetoothConnectedEvent(null);
}
@Test
public void testBluetoothConnectedEventGetThread() {
IBluetoothThread thread = mock(IBluetoothThread.class);
BluetoothConnectedEvent event = new BluetoothConnectedEvent(thread);
assertEquals(event.getThread(), thread);
}
}
| lgpl-3.0 |
tATAmI-Project/tATAmI-PC | src/tatami/pc/agent/visualization/PCSimulationGui.java | 2534 | /*******************************************************************************
* Copyright (C) 2013 Andrei Olaru, Marius-Tudor Benea, Nguyen Thi Thuy Nga, Amal El Fallah Seghrouchni, Cedric Herpson.
*
* This file is part of tATAmI-PC.
*
* tATAmI-PC 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.
*
* tATAmI-PC 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 tATAmI-PC. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package tatami.pc.agent.visualization;
import java.awt.GridBagConstraints;
import java.awt.Panel;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class PCSimulationGui extends PCDefaultAgentGui
{
public enum SimulationComponent {
CREATE, START, TIME, PAUSE, CLEAR, EXIT
}
public PCSimulationGui(AgentGuiConfig configuration)
{
super(configuration);
Panel box = new Panel();
box.setLayout(new BoxLayout(box, BoxLayout.LINE_AXIS));
JButton create = new JButton("Create agents");
box.add(create);
components.put(SimulationComponent.CREATE.toString(), create);
JButton start = new JButton("and Start");
box.add(start);
components.put(SimulationComponent.START.toString(), start);
JLabel displayedTime = new JLabel();
displayedTime.setText("--:--.-");
box.add(displayedTime);
components.put(SimulationComponent.TIME.toString(), displayedTime);
JButton pause = new JButton("Pause");
box.add(pause);
components.put(SimulationComponent.PAUSE.toString(), pause);
JButton clear = new JButton("Clear agents");
box.add(clear);
components.put(SimulationComponent.CLEAR.toString(), clear);
JButton stop = new JButton("Exit");
box.add(stop);
components.put(SimulationComponent.EXIT.toString(), stop);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
window.add(box, c);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
| lgpl-3.0 |
danielm59/DeathLog | src/main/java/io/github/danielm59/deathlog/reference/Reference.java | 576 | package io.github.danielm59.deathlog.reference;
public class Reference
{
public static final String MODID = "deathlog";
public static final String MODNAME = "Death Log";
public static final String VERSION = "@VERSION@";
public static final String CPROXY = "io.github.danielm59.deathlog.proxy.ClientProxy";
public static final String SPROXY = "io.github.danielm59.deathlog.proxy.ServerProxy";
public static final String GUIFACTORY = "io.github.danielm59.deathlog.client.gui.GuiFactory";
public static final String LogGUI = MODID + ":gui/logGUI2.png";
}
| lgpl-3.0 |
Agem-Bilisim/lider-console | lider-console-core/src/tr/org/liderahenk/liderconsole/core/model/ReportView.java | 4076 | /*
*
* Copyright © 2015-2016 Agem Bilişim
*
* This file is part of Lider Ahenk.
*
* Lider Ahenk 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.
*
* Lider Ahenk 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 Lider Ahenk. If not, see <http://www.gnu.org/licenses/>.
*/
package tr.org.liderahenk.liderconsole.core.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/**
* Model class for report views.
*
* @author <a href="mailto:emre.akkaya@agem.com.tr">Emre Akkaya</a>
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReportView implements Serializable {
private static final long serialVersionUID = 8960371013554607481L;
private Long id;
private ReportTemplate template;
private String name;
private String description;
private ReportType type;
private Set<ReportViewParameter> viewParams;
private Set<ReportViewColumn> viewColumns;
private Long alarmCheckPeriod;
private Long alarmRecordNumThreshold;
private String alarmMail;
private Date createDate;
private Date modifyDate;
public ReportView() {
}
public ReportView(Long id, ReportTemplate template, String name, String description, ReportType type,
Set<ReportViewParameter> viewParams, Set<ReportViewColumn> viewColumns, Long alarmCheckPeriod,
Long alarmRecordNumThreshold, String alarmMail, Date createDate, Date modifyDate) {
super();
this.id = id;
this.template = template;
this.name = name;
this.description = description;
this.type = type;
this.viewParams = viewParams;
this.viewColumns = viewColumns;
this.alarmCheckPeriod = alarmCheckPeriod;
this.alarmRecordNumThreshold = alarmRecordNumThreshold;
this.alarmMail = alarmMail;
this.createDate = createDate;
this.modifyDate = modifyDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ReportTemplate getTemplate() {
return template;
}
public void setTemplate(ReportTemplate template) {
this.template = template;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ReportType getType() {
return type;
}
public void setType(ReportType type) {
this.type = type;
}
public Set<ReportViewParameter> getViewParams() {
return viewParams;
}
public void setViewParams(Set<ReportViewParameter> viewParams) {
this.viewParams = viewParams;
}
public Set<ReportViewColumn> getViewColumns() {
return viewColumns;
}
public void setViewColumns(Set<ReportViewColumn> viewColumns) {
this.viewColumns = viewColumns;
}
public Long getAlarmCheckPeriod() {
return alarmCheckPeriod;
}
public void setAlarmCheckPeriod(Long alarmCheckPeriod) {
this.alarmCheckPeriod = alarmCheckPeriod;
}
public Long getAlarmRecordNumThreshold() {
return alarmRecordNumThreshold;
}
public void setAlarmRecordNumThreshold(Long alarmRecordNumThreshold) {
this.alarmRecordNumThreshold = alarmRecordNumThreshold;
}
public String getAlarmMail() {
return alarmMail;
}
public void setAlarmMail(String alarmMail) {
this.alarmMail = alarmMail;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
| lgpl-3.0 |
sikachu/jasperreports | src/net/sf/jasperreports/engine/design/DesignStyleContainer.java | 1497 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2013 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 net.sf.jasperreports.engine.design;
import net.sf.jasperreports.engine.JRDefaultStyleProvider;
import net.sf.jasperreports.engine.JRStyle;
/**
*
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: DesignStyleContainer.java 5878 2013-01-07 20:23:13Z teodord $
*/
public interface DesignStyleContainer
{
void setDefaultStyleProvider(JRDefaultStyleProvider defaultStyleProvider);
void setStyle(JRStyle style);
void setStyleNameReference(String styleName);
}
| lgpl-3.0 |
tecsinapse/tecsinapse-data-io | src/test/java/br/com/tecsinapse/dataio/TableTest.java | 1600 | /*
* Tecsinapse Data Input and Output
*
* License: GNU Lesser General Public License (LGPL), version 3 or later
* See the LICENSE file in the root directory or <http://www.gnu.org/licenses/lgpl-3.0.html>.
*/
package br.com.tecsinapse.dataio;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.testng.annotations.Test;
import com.google.common.io.Files;
import br.com.tecsinapse.dataio.style.Colors;
import br.com.tecsinapse.dataio.style.TableCellStyle;
import br.com.tecsinapse.dataio.util.ExporterUtil;
public class TableTest {
@Test
public void tableFluentRowAndCellTest() throws IOException {
Table table = new Table();
TableCell tableCellDate = new TableCell(2.56);
TableCellStyle tableCellStyle = new TableCellStyle(Colors.DARK_GREEN);
table
.withNewRow()
.withCell(new Date())
.withCell("Col two")
.withCell("BG Dark Green", tableCellStyle)
.withCell("BG Dark Green + cols span", tableCellStyle, 2)
.withCell(tableCellDate)
.withNewRow()
.withCell(new Date())
.withCell("@Col two")
.withCell("@BG Dark Green", tableCellStyle)
.withCell("@BG Dark Green + cols span", tableCellStyle, 2)
.withCell(tableCellDate);
File file = ResourceUtils.newFileTargetResource("/tableFluentRowAndCellTest.xlsx");
File outFile = ExporterUtil.getXlsxFile(table, file.getName());
Files.move(outFile, file);
}
} | lgpl-3.0 |
athento/athento-nx-automation-extended | athento-nx-automation-extended/src/test/java/org/athento/nuxeo/PackageToZipOperationTest.java | 5327 | package org.athento.nuxeo;
import com.google.inject.Inject;
import com.sun.org.apache.commons.logging.Log;
import com.sun.org.apache.commons.logging.LogFactory;
import org.athento.nuxeo.api.DocumentModelListPageProvider;
import org.athento.nuxeo.operations.CopyFileOperation;
import org.athento.nuxeo.operations.PackageToZipOperation;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.common.utils.FileUtils;
import org.nuxeo.common.utils.ZipUtils;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationChain;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.util.BlobList;
import org.nuxeo.ecm.automation.jaxrs.io.documents.PaginableDocumentModelListImpl;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
import org.nuxeo.ecm.core.api.impl.blob.FileBlob;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.LocalDeploy;
import java.io.File;
import java.net.URL;
/**
* Feed operation test.
*/
@RunWith(FeaturesRunner.class)
@Deploy("org.nuxeo.ecm.automation.core")
@LocalDeploy("org.athento.nuxeo.automation-extended:OSGI-INF/Automation/operations-contrib.xml")
public class PackageToZipOperationTest {
private static final Log LOG = LogFactory.getLog(PackageToZipOperationTest.class);
protected DocumentModel src, dst, abc;
@Inject
AutomationService service;
@Inject
CoreSession session;
@Before
public void initRepo() throws Exception {
session.removeChildren(session.getRootDocument().getRef());
session.save();
FileBlob blob = new FileBlob(getClass().getClassLoader().getResourceAsStream("test.pdf"));
src = session.createDocumentModel("/", "file1", "File");
src.setPropertyValue("dc:title", "Document 1");
src.setPropertyValue("dc:description", "Description 1");
src.setPropertyValue("file:content", blob);
src = session.createDocument(src);
session.save();
src = session.getDocument(src.getRef());
dst = session.createDocumentModel("/", "file2", "File");
dst.setPropertyValue("dc:title", "Document 2");
dst.setPropertyValue("dc:description", "Description 2");
dst.setPropertyValue("file:content", blob);
dst = session.createDocument(dst);
session.save();
dst = session.getDocument(dst.getRef());
abc = session.createDocumentModel("/", "file3", "File");
abc.setPropertyValue("dc:title", "Document 3");
abc.setPropertyValue("dc:description", "Description 3");
abc.setPropertyValue("file:content", blob);
abc = session.createDocument(abc);
session.save();
abc = session.getDocument(abc.getRef());
}
@Test
public void testPackageToZip() throws Exception {
DocumentModelList list = new DocumentModelListImpl();
list.add(src);
list.add(dst);
list.add(abc);
PaginableDocumentModelListImpl paginableDocumentModelList
= new PaginableDocumentModelListImpl(new DocumentModelListPageProvider(list));
OperationContext ctx = new OperationContext(session);
ctx.setInput(paginableDocumentModelList);
OperationChain chain = new OperationChain("testPackageToZipWithSize80K");
chain.add(PackageToZipOperation.ID).set("packageSize", 2).set("fileMaxSize", 81920); // 80Kb
BlobList blobList = (BlobList) service.run(ctx, chain);
Assert.assertTrue(blobList.size() == 2);
Assert.assertTrue(ZipUtils.getEntryNames(blobList.get(0).getStream()).size() == 1);
Assert.assertTrue(ZipUtils.getEntryNames(blobList.get(1).getStream()).size() == 1);
OperationContext ctx2 = new OperationContext(session);
ctx2.setInput(paginableDocumentModelList);
OperationChain chain2 = new OperationChain("testPackageToZipWitSize100K");
chain2.add(PackageToZipOperation.ID).set("packageSize", 2).set("fileMaxSize", 102400); // 100Kb
BlobList blobList2 = (BlobList) service.run(ctx2, chain2);
Assert.assertTrue(blobList2.size() == 2);
Assert.assertTrue(ZipUtils.getEntryNames(blobList2.get(0).getStream()).size() == 2);
Assert.assertTrue(ZipUtils.getEntryNames(blobList2.get(1).getStream()).size() == 1);
OperationContext ctx3 = new OperationContext(session);
ctx3.setInput(paginableDocumentModelList);
OperationChain chain3 = new OperationChain("testPackageToZipWitNoSize");
chain3.add(PackageToZipOperation.ID).set("packageSize", 1).set("fileMaxSize", -1); // 100Kb
BlobList blobList3 = (BlobList) service.run(ctx3, chain3);
Assert.assertTrue(blobList3.size() == 3);
Assert.assertTrue(ZipUtils.getEntryNames(blobList3.get(0).getStream()).size() == 1);
Assert.assertTrue(ZipUtils.getEntryNames(blobList3.get(1).getStream()).size() == 1);
Assert.assertTrue(ZipUtils.getEntryNames(blobList3.get(2).getStream()).size() == 1);
}
}
| lgpl-3.0 |
houdejun214/lakeside-java | lakeside-core/src/main/java/com/lakeside/core/utils/EmailUtil.java | 3338 | package com.lakeside.core.utils;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
/**
* @author zhufb
*
*/
public class EmailUtil {
public static void send(String[] recipeintEmail,String subject, String messageText) {
send(recipeintEmail,subject,messageText,new String[]{});
}
public static void send(String[] recipeintEmail,String subject, String messageText, String [] attachments) {
try {
String senderEmail = "nextsearchcentre@gmail.com";
String senderMailPassword = "NextSearchCentre";
String gmail = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.user", senderEmail);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
// Required to avoid security exception.
MyAuthenticator authentication = new MyAuthenticator(senderEmail,
senderMailPassword);
Session session = Session.getDefaultInstance(props, authentication);
session.setDebug(false);
MimeMessage message = new MimeMessage(session);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageText);
// Add message text
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Attachments should reside in your server.
// Example "c:\file.txt" or "/home/user/photo.jpg"
for (int i = 0; i < attachments.length; i++) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachments[i]);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
message.setSubject(subject);
message.setFrom(new InternetAddress(senderEmail));
Address[] array = new Address[recipeintEmail.length];
for(int i=0;i<recipeintEmail.length;i++){
array[i] = new InternetAddress(recipeintEmail[i]);
}
message.addRecipients(Message.RecipientType.TO, array);
Transport transport = session.getTransport("smtps");
transport.connect(gmail, 465, senderEmail, senderMailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private static class MyAuthenticator extends javax.mail.Authenticator {
String User;
String Password;
public MyAuthenticator (String user, String password) {
User = user;
Password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(User, Password);
}
}
}
| lgpl-3.0 |
maruohon/minihud | src/main/java/fi/dy/masa/minihud/renderer/RenderContainer.java | 7875 | package fi.dy.masa.minihud.renderer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import fi.dy.masa.malilib.util.JsonUtils;
import fi.dy.masa.minihud.config.RendererToggle;
import fi.dy.masa.minihud.renderer.shapes.ShapeBase;
public class RenderContainer
{
public static final OverlayRendererSpawnerPositions SPAWNER_RENDERER = new OverlayRendererSpawnerPositions();
public static final OverlayRendererWaterFalls WATER_FALL_RENDERER = new OverlayRendererWaterFalls();
public static final RenderContainer INSTANCE = new RenderContainer();
protected final List<OverlayRendererBase> renderers = new ArrayList<>();
protected boolean resourcesAllocated;
protected boolean useVbo;
protected int countActive;
private RenderContainer()
{
this.addRenderer(new OverlayRendererBeaconRange());
this.addRenderer(new OverlayRendererBlockGrid());
this.addRenderer(new OverlayRendererLightLevel());
this.addRenderer(new OverlayRendererRandomTickableChunks(RendererToggle.OVERLAY_RANDOM_TICKS_FIXED));
this.addRenderer(new OverlayRendererRandomTickableChunks(RendererToggle.OVERLAY_RANDOM_TICKS_PLAYER));
this.addRenderer(new OverlayRendererRegion());
this.addRenderer(new OverlayRendererSlimeChunks());
this.addRenderer(new OverlayRendererSpawnableColumnHeights());
this.addRenderer(new OverlayRendererSpawnableChunks(RendererToggle.OVERLAY_SPAWNABLE_CHUNKS_FIXED));
this.addRenderer(new OverlayRendererSpawnableChunks(RendererToggle.OVERLAY_SPAWNABLE_CHUNKS_PLAYER));
this.addRenderer(new OverlayRendererSpawnChunks(RendererToggle.OVERLAY_SPAWN_CHUNK_OVERLAY_REAL));
this.addRenderer(new OverlayRendererSpawnChunks(RendererToggle.OVERLAY_SPAWN_CHUNK_OVERLAY_PLAYER));
this.addRenderer(new OverlayRendererStructures());
this.addRenderer(SPAWNER_RENDERER);
this.addRenderer(WATER_FALL_RENDERER);
}
private void addRenderer(OverlayRendererBase renderer)
{
if (this.resourcesAllocated)
{
renderer.allocateGlResources();
}
this.renderers.add(renderer);
}
private void removeRenderer(OverlayRendererBase renderer)
{
this.renderers.remove(renderer);
if (this.resourcesAllocated)
{
renderer.deleteGlResources();
}
}
public void addShapeRenderer(ShapeBase renderer)
{
this.addRenderer(renderer);
}
public void removeShapeRenderer(ShapeBase renderer)
{
this.removeRenderer(renderer);
}
public void render(Entity entity, Minecraft mc, float partialTicks)
{
double x = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks;
double y = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks;
double z = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks;
Vec3d cameraPos = new Vec3d(x, y, z);
this.update(cameraPos, entity, mc);
this.draw(cameraPos, mc);
}
protected void update(Vec3d cameraPos, Entity entity, Minecraft mc)
{
this.checkVideoSettings();
this.countActive = 0;
for (OverlayRendererBase renderer : this.renderers)
{
if (renderer.shouldRender(mc))
{
if (renderer.needsUpdate(entity, mc))
{
renderer.lastUpdatePos = new BlockPos(entity);
renderer.setUpdatePosition(cameraPos);
renderer.update(cameraPos, entity, mc);
}
++this.countActive;
}
}
}
protected void draw(Vec3d cameraPos, Minecraft mc)
{
if (this.resourcesAllocated && this.countActive > 0)
{
GlStateManager.pushMatrix();
GlStateManager.disableTexture2D();
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.01F);
GlStateManager.disableCull();
GlStateManager.disableLighting();
GlStateManager.depthMask(false);
GlStateManager.doPolygonOffset(-3f, -3f);
GlStateManager.enablePolygonOffset();
fi.dy.masa.malilib.render.RenderUtils.setupBlend();
fi.dy.masa.malilib.render.RenderUtils.color(1f, 1f, 1f, 1f);
if (OpenGlHelper.useVbo())
{
GlStateManager.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GlStateManager.glEnableClientState(GL11.GL_COLOR_ARRAY);
}
double cx = cameraPos.x;
double cy = cameraPos.y;
double cz = cameraPos.z;
for (IOverlayRenderer renderer : this.renderers)
{
if (renderer.shouldRender(mc))
{
Vec3d updatePos = renderer.getUpdatePosition();
GlStateManager.pushMatrix();
GlStateManager.translate(updatePos.x - cx, updatePos.y - cy, updatePos.z - cz);
renderer.draw();
GlStateManager.popMatrix();
}
}
if (OpenGlHelper.useVbo())
{
OpenGlHelper.glBindBuffer(OpenGlHelper.GL_ARRAY_BUFFER, 0);
GlStateManager.resetColor();
GlStateManager.glDisableClientState(GL11.GL_VERTEX_ARRAY);
GlStateManager.glDisableClientState(GL11.GL_COLOR_ARRAY);
}
fi.dy.masa.malilib.render.RenderUtils.color(1f, 1f, 1f, 1f);
GlStateManager.doPolygonOffset(0f, 0f);
GlStateManager.disablePolygonOffset();
GlStateManager.disableBlend();
GlStateManager.enableDepth();
GlStateManager.enableCull();
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.popMatrix();
}
}
protected void checkVideoSettings()
{
boolean vboLast = this.useVbo;
this.useVbo = OpenGlHelper.useVbo();
if (vboLast != this.useVbo || this.resourcesAllocated == false)
{
this.deleteGlResources();
this.allocateGlResources();
}
}
protected void allocateGlResources()
{
if (this.resourcesAllocated == false)
{
for (OverlayRendererBase renderer : this.renderers)
{
renderer.allocateGlResources();
}
this.resourcesAllocated = true;
}
}
protected void deleteGlResources()
{
if (this.resourcesAllocated)
{
for (OverlayRendererBase renderer : this.renderers)
{
renderer.deleteGlResources();
}
this.resourcesAllocated = false;
}
}
public JsonObject toJson()
{
JsonObject obj = new JsonObject();
for (OverlayRendererBase renderer : this.renderers)
{
String id = renderer.getSaveId();
if (id.isEmpty() == false)
{
obj.add(id, renderer.toJson());
}
}
return obj;
}
public void fromJson(JsonObject obj)
{
for (OverlayRendererBase renderer : this.renderers)
{
String id = renderer.getSaveId();
if (id.isEmpty() == false && JsonUtils.hasObject(obj, id))
{
renderer.fromJson(obj.get(id).getAsJsonObject());
}
}
}
}
| lgpl-3.0 |
hongliangpan/manydesigns.cn | trunk/portofino-database/liquibase-core-2.0.5-sources/liquibase/change/custom/CustomTaskChange.java | 1285 | package liquibase.change.custom;
import liquibase.database.Database;
import liquibase.exception.CustomChangeException;
/**
* Interface to implement when creating a custom change that does not actually generate SQL.
* If you are updating a database through SQL, implementing CustomSqlChange is preferred because the SQL can either be executed
* directly or saved to a text file for later use depending on the migration mode used.
* To allow the change to be rolled back, also implement the CustomTaskRollback interface.
* If your change requires sql-based logic and non-sql-based logic, it is best to create a change set that contains a mix of CustomSqlChange and CustomTaskChange calls.
*
* @see liquibase.change.custom.CustomTaskRollback
* @see liquibase.change.custom.CustomSqlChange
*/
public interface CustomTaskChange extends CustomChange {
/**
* Method called to run the change logic.
* @param database
* @throws liquibase.exception.CustomChangeException an exception occurs while processing this change
* @throws liquibase.exception.UnsupportedChangeException if this change is not supported by the {@link liquibase.database.Database} passed as argument
*/
public void execute(Database database) throws CustomChangeException;
}
| lgpl-3.0 |
omni-compiler/omni-compiler | XcodeML-Exc-Tools/src/exc/xmpF/XMPinfo.java | 4597 | package exc.xmpF;
import exc.object.*;
import exc.block.*;
import java.util.Vector;
/**
* information for each XMP directive
*/
public class XMPinfo
{
private XMPinfo parent;
private Block block; /* back link */
XMPpragma pragma; /* directives */
XMPenv env;
BlockList body;
XMPobjectsRef on_ref;
Vector<Ident> info_vars;
Vector<Xobject> info_vars2;
Xobject async_id;
Vector<Xobject> waitAsyncIds;
// loop info for loop
Vector<XMPdimInfo> loop_dims; // and on_ref
int loop_type;
// for reflect
Vector<XMParray> reflectArrays; // and async_id
Vector<XMPdimInfo> widthList;
// for reduction
int reduction_op;
Vector<Ident> reduction_vars;
Vector<Vector<Ident>> reduction_pos_vars;
// for bcast
XMPobjectsRef bcast_from; // and on_ref, info_vars
// for gmove
Xobject gmoveLeft,gmoveRight;
Xobject gmoveOpt;
// for template_fix
XMPtemplate template;
XobjList sizeList;
XobjList distList;
// for task
boolean nocomm_flag;
// for acc
//Xobject accOpt;
boolean acc_flag;
public XMPinfo(XMPpragma pragma, XMPinfo parent, Block b, XMPenv env) {
this.pragma = pragma;
this.parent = parent;
this.block = b;
this.env = env;
}
public Block getBlock() {
return block;
}
public void setBody(BlockList body) { this.body = body; }
public BlockList getBody() { return body; }
public void setOnRef(XMPobjectsRef ref) { on_ref = ref; }
public XMPobjectsRef getOnRef() { return on_ref; }
public Vector<Ident> getInfoVarIdents() { return info_vars; }
public Vector<Xobject> getInfoVars() { return info_vars2; }
public void setAsyncId(Xobject async_id) { this.async_id = async_id; }
public Xobject getAsyncId() { return async_id; }
public void setWaitAsyncIds(Vector<Xobject> waitAsyncIds){
this.waitAsyncIds = waitAsyncIds;
}
public Vector<Xobject> getWaitAsyncIds() { return waitAsyncIds; }
/*
* for loop
*/
public void setLoopInfo(Vector<XMPdimInfo> dims, XMPobjectsRef ref){
loop_dims = dims;
on_ref = ref;
}
public void setLoopInfo(Vector<XMPdimInfo> dims, XMPobjectsRef ref, int type, Vector<XMPdimInfo> list){
loop_dims = dims;
on_ref = ref;
loop_type = type;
widthList = list;
}
public int getLoopDim() { return loop_dims.size(); }
public int getLoopType() { return loop_type; }
public XMPdimInfo getLoopDimInfo(int i) { return loop_dims.elementAt(i); }
public Xobject getLoopVar(int i) {
return loop_dims.elementAt(i).getLoopVar();
}
public void setReflectArrays(Vector<XMParray> arrays){
reflectArrays = arrays;
}
public void addReflectArray(XMParray array){
reflectArrays.add(array);
}
public void setReflectArrays(Vector<XMParray> arrays, Vector<XMPdimInfo> list){
reflectArrays = arrays;
widthList = list;
}
public Vector<XMParray> getReflectArrays(){ return reflectArrays; }
// also used for loop
public Vector<XMPdimInfo> getWidthList() {
return widthList;
}
public void setReductionInfo(int op, Vector<Ident> vars, Vector<Vector<Ident>> pos_vars){
reduction_op = op;
reduction_vars = vars;
reduction_pos_vars = pos_vars;
}
public void setBcastInfo(XMPobjectsRef from, XMPobjectsRef on,
Vector<Xobject> vars){
bcast_from = from;
on_ref = on;
info_vars2 = vars;
}
public int getReductionOp() { return reduction_op; }
public Vector<Ident> getReductionVars() { return reduction_vars; }
public Vector<Vector<Ident>> getReductionPosVars() { return reduction_pos_vars; }
public XMPobjectsRef getBcastFrom() { return bcast_from; }
/* for gmove */
public void setGmoveOperands(Xobject left, Xobject right){
gmoveLeft = left;
gmoveRight = right;
}
public Xobject getGmoveLeft() { return gmoveLeft; }
public Xobject getGmoveRight() { return gmoveRight; }
public void setGmoveOpt(Xobject _gmoveOpt){
gmoveOpt = _gmoveOpt;
}
public Xobject getGmoveOpt() { return gmoveOpt; }
public void setTemplateFix(XMPtemplate t, XobjList sList, XobjList dList){
template = t;
sizeList = sList;
distList = dList;
}
public XMPtemplate getTemplate() { return template; }
public XobjList getSizeList() { return sizeList; }
public XobjList getDistList() { return distList; }
public void setNocomm(Xobject nocomm){
nocomm_flag = (nocomm.getInt() == 1);
}
public boolean isNocomm() { return nocomm_flag; }
public void setAcc(Xobject acc) {
acc_flag = ! acc.isZeroConstant();
}
public boolean isAcc() { return acc_flag; }
}
| lgpl-3.0 |
zenframework/z8 | org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/db/Delete.java | 1362 | package org.zenframework.z8.server.db;
import java.sql.SQLException;
import org.zenframework.z8.server.base.query.Query;
import org.zenframework.z8.server.engine.IDatabase;
import org.zenframework.z8.server.logs.Trace;
import org.zenframework.z8.server.types.guid;
public class Delete extends DmlStatement {
private guid recordId;
static public Delete create(Query query, guid recordId) {
Connection connection = query.getConnection();
IDatabase database = connection.database();
DatabaseVendor vendor = database.vendor();
String sql = "delete from " + database.tableName(query.name()) + " where " + vendor.quote(query.primaryKey().name()) + "=?";
Delete delete = (Delete)connection.getStatement(sql);
return delete != null ? delete.initialize(recordId) : new Delete(query.getConnection(), sql, Integer.MAX_VALUE - query.priority(), recordId);
}
private Delete(Connection connection, String sql, int priority, guid recordId) {
super(connection, sql, priority);
initialize(recordId);
}
private Delete initialize(guid recordId) {
this.recordId = recordId;
return this;
}
@Override
public void prepare() throws SQLException {
super.prepare();
set(1, FieldType.Guid, recordId);
}
@Override
protected void log() {
Trace.logEvent(sql() + '\n' + "recordId: " + recordId);
}
}
| lgpl-3.0 |
PierreR/sonarqube | sonar-core/src/main/java/org/sonar/core/util/DefaultHttpDownloader.java | 13643 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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.core.util;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.annotation.Nullable;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.sonar.api.config.Settings;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.api.utils.SonarException;
import org.sonar.api.utils.log.Loggers;
/**
* This component downloads HTTP files
*
* @since 2.2
*/
public class DefaultHttpDownloader extends HttpDownloader {
private final BaseHttpDownloader downloader;
private final Integer readTimeout;
private final Integer connectTimeout;
public DefaultHttpDownloader(Server server, Settings settings) {
this(server, settings, null);
}
public DefaultHttpDownloader(Server server, Settings settings, @Nullable Integer readTimeout) {
this(server, settings, null, readTimeout);
}
public DefaultHttpDownloader(Server server, Settings settings, @Nullable Integer connectTimeout, @Nullable Integer readTimeout) {
this.readTimeout = readTimeout;
this.connectTimeout = connectTimeout;
downloader = new BaseHttpDownloader(settings.getProperties(), server.getVersion());
}
public DefaultHttpDownloader(Settings settings) {
this(settings, null);
}
public DefaultHttpDownloader(Settings settings, @Nullable Integer readTimeout) {
this(settings, null, readTimeout);
}
public DefaultHttpDownloader(Settings settings, @Nullable Integer connectTimeout, @Nullable Integer readTimeout) {
this.readTimeout = readTimeout;
this.connectTimeout = connectTimeout;
downloader = new BaseHttpDownloader(settings.getProperties(), null);
}
@Override
protected String description(URI uri) {
return String.format("%s (%s)", uri.toString(), getProxySynthesis(uri));
}
@Override
protected String[] getSupportedSchemes() {
return new String[] {"http", "https"};
}
@Override
protected byte[] readBytes(URI uri) {
return download(uri);
}
@Override
protected String readString(URI uri, Charset charset) {
try {
return CharStreams.toString(CharStreams.newReaderSupplier(downloader.newInputSupplier(uri, this.connectTimeout, this.readTimeout), charset));
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
@Override
public String downloadPlainText(URI uri, String encoding) {
return readString(uri, Charset.forName(encoding));
}
@Override
public byte[] download(URI uri) {
try {
return ByteStreams.toByteArray(downloader.newInputSupplier(uri, this.connectTimeout, this.readTimeout));
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
public String getProxySynthesis(URI uri) {
return downloader.getProxySynthesis(uri);
}
@Override
public InputStream openStream(URI uri) {
try {
return downloader.newInputSupplier(uri, this.connectTimeout, this.readTimeout).getInput();
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
@Override
public void download(URI uri, File toFile) {
try {
Files.copy(downloader.newInputSupplier(uri, this.connectTimeout, this.readTimeout), toFile);
} catch (IOException e) {
FileUtils.deleteQuietly(toFile);
throw failToDownload(uri, e);
}
}
private SonarException failToDownload(URI uri, IOException e) {
throw new SonarException(String.format("Fail to download: %s (%s)", uri, getProxySynthesis(uri)), e);
}
public static class BaseHttpDownloader {
private static final String GET = "GET";
private static final String HTTP_PROXY_USER = "http.proxyUser";
private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword";
private static final List<String> PROXY_SETTINGS = ImmutableList.of(
"http.proxyHost", "http.proxyPort", "http.nonProxyHosts",
"http.auth.ntlm.domain", "socksProxyHost", "socksProxyPort");
private String userAgent;
public BaseHttpDownloader(Map<String, String> settings, @Nullable String userAgent) {
initProxy(settings);
initUserAgent(userAgent);
}
private void initProxy(Map<String, String> settings) {
propagateProxySystemProperties(settings);
if (requiresProxyAuthentication(settings)) {
registerProxyCredentials(settings);
}
}
private void initUserAgent(@Nullable String sonarVersion) {
userAgent = (sonarVersion == null ? "SonarQube" : String.format("SonarQube %s", sonarVersion));
System.setProperty("http.agent", userAgent);
}
private String getProxySynthesis(URI uri) {
return getProxySynthesis(uri, ProxySelector.getDefault());
}
@VisibleForTesting
static String getProxySynthesis(URI uri, ProxySelector proxySelector) {
List<Proxy> proxies = proxySelector.select(uri);
if (proxies.size() == 1 && proxies.get(0).type().equals(Proxy.Type.DIRECT)) {
return "no proxy";
}
List<String> descriptions = Lists.newArrayList();
for (Proxy proxy : proxies) {
if (proxy.type() != Proxy.Type.DIRECT) {
descriptions.add(proxy.type() + " proxy: " + proxy.address());
}
}
return Joiner.on(", ").join(descriptions);
}
private void registerProxyCredentials(Map<String, String> settings) {
Authenticator.setDefault(new ProxyAuthenticator(
settings.get(HTTP_PROXY_USER),
settings.get(HTTP_PROXY_PASSWORD)));
}
private boolean requiresProxyAuthentication(Map<String, String> settings) {
return settings.containsKey(HTTP_PROXY_USER);
}
private void propagateProxySystemProperties(Map<String, String> settings) {
for (String key : PROXY_SETTINGS) {
if (settings.containsKey(key)) {
System.setProperty(key, settings.get(key));
}
}
}
public InputSupplier<InputStream> newInputSupplier(URI uri) {
return newInputSupplier(uri, GET, null, null, null, null);
}
public InputSupplier<InputStream> newInputSupplier(URI uri, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, GET, readTimeoutMillis);
}
/**
* @since 5.2
*/
public InputSupplier<InputStream> newInputSupplier(URI uri, @Nullable Integer connectTimeoutMillis, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, GET, connectTimeoutMillis, readTimeoutMillis);
}
/**
* @since 5.2
*/
public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, @Nullable Integer connectTimeoutMillis, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, requestMethod, null, null, connectTimeoutMillis, readTimeoutMillis);
}
public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, requestMethod, null, null, null, readTimeoutMillis);
}
public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password) {
return newInputSupplier(uri, GET, login, password);
}
/**
* @since 5.0
*/
public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password) {
return newInputSupplier(uri, requestMethod, login, password, null, null);
}
public InputSupplier<InputStream> newInputSupplier(URI uri, String login, String password, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, GET, login, password, readTimeoutMillis);
}
/**
* @since 5.0
*/
public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password, @Nullable Integer readTimeoutMillis) {
return newInputSupplier(uri, requestMethod, login, password, null, readTimeoutMillis);
}
/**
* @since 5.2
*/
public InputSupplier<InputStream> newInputSupplier(URI uri, String requestMethod, String login, String password, @Nullable Integer connectTimeoutMillis,
@Nullable Integer readTimeoutMillis) {
int read = readTimeoutMillis != null ? readTimeoutMillis : TIMEOUT_MILLISECONDS;
int connect = connectTimeoutMillis != null ? connectTimeoutMillis : TIMEOUT_MILLISECONDS;
return new HttpInputSupplier(uri, requestMethod, userAgent, login, password, connect, read);
}
private static class HttpInputSupplier implements InputSupplier<InputStream> {
private final String login;
private final String password;
private final URI uri;
private final String userAgent;
private final int connectTimeoutMillis;
private final int readTimeoutMillis;
private final String requestMethod;
HttpInputSupplier(URI uri, String requestMethod, String userAgent, String login, String password, int connectTimeoutMillis, int readTimeoutMillis) {
this.uri = uri;
this.requestMethod = requestMethod;
this.userAgent = userAgent;
this.login = login;
this.password = password;
this.readTimeoutMillis = readTimeoutMillis;
this.connectTimeoutMillis = connectTimeoutMillis;
}
/**
* @throws IOException any I/O error, not limited to the network connection
* @throws HttpException if HTTP response code > 400
*/
@Override
public InputStream getInput() throws IOException {
Loggers.get(getClass()).debug("Download: " + uri + " (" + getProxySynthesis(uri, ProxySelector.getDefault()) + ")");
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
connection.setRequestMethod(requestMethod);
HttpsTrust.INSTANCE.trust(connection);
// allow both GZip and Deflate (ZLib) encodings
connection.setRequestProperty("Accept-Encoding", "gzip");
if (!Strings.isNullOrEmpty(login)) {
String encoded = Base64.encodeBase64String((login + ":" + password).getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encoded);
}
connection.setConnectTimeout(connectTimeoutMillis);
connection.setReadTimeout(readTimeoutMillis);
connection.setUseCaches(true);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("User-Agent", userAgent);
// establish connection, get response headers
connection.connect();
// obtain the encoding returned by the server
String encoding = connection.getContentEncoding();
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
InputStream errorResponse = null;
try {
errorResponse = connection.getErrorStream();
if (errorResponse != null) {
String errorResponseContent = IOUtils.toString(errorResponse);
throw new HttpException(uri, responseCode, errorResponseContent);
}
throw new HttpException(uri, responseCode);
} finally {
IOUtils.closeQuietly(errorResponse);
}
}
InputStream resultingInputStream;
// create the appropriate stream wrapper based on the encoding type
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
resultingInputStream = new GZIPInputStream(connection.getInputStream());
} else {
resultingInputStream = connection.getInputStream();
}
return resultingInputStream;
}
}
private static class ProxyAuthenticator extends Authenticator {
private final PasswordAuthentication auth;
ProxyAuthenticator(String user, String password) {
auth = new PasswordAuthentication(user, password == null ? new char[0] : password.toCharArray());
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return auth;
}
}
}
}
| lgpl-3.0 |
nypgit/alto | src/alto/hash/Private.java | 2147 | /*
* Copyright (C) 1998, 2009 John Pritchard and the Alto Project Group.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package alto.hash;
/**
* <p> Support for cipher text: a payload or content block </p>
*
* <p> A user can attach a transcoder with his key. </p>
*
* @author jdp
* @since 1.2
*/
public interface Private {
/**
* Read plain text with cipher (a null cipher is reading code text.
*/
public interface Input {
/**
* @return An input stream for reading plain text.
*/
public java.io.InputStream getPrivateInput();
}
/**
* Write code text with cipher (a null cipher is writing plain text.
*/
public interface Output {
/**
* @return An output stream for writing plain text.
*/
public java.io.OutputStream getPrivateOutput();
}
/**
*
*/
public interface Cipher {
/**
* Install a transcoder into the plain text I/O
* chain.
*/
public Private setPrivateCipher(Cipher cipher);
}
/**
* Cipher text coding.
*/
public interface Coder {
/**
* Base64 coding.
*/
public interface B64
extends Coder
{
/**
* Install a base 64 coder into the plain text I/O chain.
*/
public Private setPrivateCoderB64();
}
}
}
| lgpl-3.0 |
Ugachaga/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/block/BlockCampFire.java | 4226 | package com.darkona.adventurebackpack.block;
import java.util.Random;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import com.darkona.adventurebackpack.CreativeTabAB;
import com.darkona.adventurebackpack.reference.ModInfo;
import com.darkona.adventurebackpack.util.CoordsUtils;
/**
* Created on 05/01/2015
*
* @author Darkona
*/
public class BlockCampFire extends BlockContainer
{
private IIcon icon;
public BlockCampFire()
{
super(Material.rock);
this.setTickRandomly(true);
this.setCreativeTab(CreativeTabAB.ADVENTURE_BACKPACK_CREATIVE_TAB);
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister)
{
icon = iconRegister.registerIcon(ModInfo.MOD_ID + ":campFire");
}
@Override
public String getUnlocalizedName()
{
return "blockCampFire";
}
@Override
public TileEntity createNewTileEntity(World world, int p_149915_2_)
{
return new TileCampfire();
}
@Override
public int tickRate(World p_149738_1_)
{
return 30;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public int getRenderType()
{
return -1;
}
@Override
public boolean isNormalCube()
{
return false;
}
@Override
public boolean isBlockNormalCube()
{
return false;
}
@SideOnly(Side.CLIENT)
@Override
public void randomDisplayTick(World world, int posX, int posY, int posZ, Random rnd)
{
float rndX = posX + rnd.nextFloat();
float rndY = (posY + 1) - rnd.nextFloat() * 0.1F;
float rndZ = posZ + rnd.nextFloat();
world.spawnParticle("largesmoke", rndX, rndY, rndZ, 0.0D, 0.0D, 0.0D);
for (int i = 0; i < 4; i++)
{
rndX = posX + 0.5f - (float) rnd.nextGaussian() * 0.08f;
rndY = (float) (posY + 1f - Math.cos((float) rnd.nextGaussian() * 0.1f));
rndZ = posZ + 0.5f - (float) rnd.nextGaussian() * 0.08f;
//world.spawnParticle("flame", posX+Math.sin(i/4), posY, posZ+Math.cos(i/4), 0.0D, 0.0D, 0.0D);
world.spawnParticle("flame", rndX, rndY + 0.16, rndZ, 0.0D, 0.0D, 0.0D);
}
}
@Override
public TileEntity createTileEntity(World world, int metadata)
{
return new TileCampfire();
}
@Override
public boolean hasTileEntity(int meta)
{
return true;
}
@Override
public int getLightValue(IBlockAccess world, int x, int y, int z)
{
return 11;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess blockAccess, int x, int y, int z)
{
this.setBlockBounds(0.2F, 0.0F, 0.2F, 0.8F, 0.15F, 0.8F);
}
@Override
public IIcon getIcon(IBlockAccess p_149673_1_, int p_149673_2_, int p_149673_3_, int p_149673_4_, int p_149673_5_)
{
return icon;
}
@Override
public IIcon getIcon(int p_149691_1_, int p_149691_2_)
{
return icon;
}
@Override
public boolean isBed(IBlockAccess world, int x, int y, int z, EntityLivingBase player)
{
return true;
}
@Override
public ChunkCoordinates getBedSpawnPosition(IBlockAccess world, int x, int y, int z, EntityPlayer player)
{
for (int i = y - 5; i <= y + 5; i++)
{
ChunkCoordinates spawn = CoordsUtils.getNearestEmptyChunkCoordinatesSpiral(world, x, z, x, i, z, 8, true, 1, (byte) 0, true);
if (spawn != null)
{
return spawn;
}
}
return null;
}
}
| lgpl-3.0 |
isartcanyameres/mqnaas | core.api/src/main/java/org/mqnaas/core/api/ICapability.java | 793 | package org.mqnaas.core.api;
import org.mqnaas.core.api.annotations.DependingOn;
/**
* <p>
* <code>ICapability</code> is a marker interface to identify capability interfaces and their implementations.
* </p>
*
* <p>
* Like {@link IApplication}s, <code>ICapability</code>s can depend on other capabilities to provide their services, which may be expressed by
* annotating attributes with the {@link DependingOn} annotation. Services provided by a given capability implementation will only get available if
* all capability dependencies are resolved.
* </p>
*
* TODO Define a mechanism that can be used to initialize capabilities after dependency resolution (see {@link IApplication} for another use-case of
* this initialization mechanism).
*/
public interface ICapability {
}
| lgpl-3.0 |