repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
kellydavid/DistributedFileSystem | dfs-config/src/main/java/com/kellydavid/dfs/config/Configurator.java | 1740 | package com.kellydavid.dfs.config;
import java.io.*;
import java.util.HashMap;
/**
* Created by david on 31/01/2016.
*/
public class Configurator {
private String filename;
private HashMap<String, String> configuration;
public Configurator(String filename){
this.filename = filename;
configuration = new HashMap<String, String>();
}
public void loadConfiguration(){
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
while (line != null) {
addConfigLine(line);
line = reader.readLine();
}
reader.close();
}catch(FileNotFoundException fnfe){
System.err.println("Could not find configuration file.");
}catch(IOException ioe){
System.err.println("Error reading from configuration file.");
}finally{
try {
if (reader != null)
reader.close();
}catch(IOException ioe){
System.err.println("Error closing file.");
}
}
}
private void addConfigLine(String line){
String split[] = line.split("=");
if(split.length != 2){
return;
}else {
String key = split[0];
String value = split[1];
if (!configuration.containsKey(key)) {
configuration.put(key, value);
} else {
System.err.println("Warning duplicate value for " + key + " encountered.");
}
}
}
public String getValue(String key){
return configuration.get(key);
}
}
| gpl-2.0 |
dcgibbons/herald | src/net/sourceforge/herald/MessengerProtocol.java | 5265 | /*
* MessengerProtocol.java
*
* Herald, An Instant Messenging Application
*
* Copyright © 2000 Chad Gibbons
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.sourceforge.herald;
/**
* This class contains field definitions and utilities as defined by
* the MSN Messenger V1.0 Protocol document.
*/
public final class MessengerProtocol {
public final static int PORT = 1863;
public final static String DIALECT_NAME = "MSNP2";
public final static String END_OF_COMMAND = "\r\n";
public final static String CMD_ACK = "ACK";
public final static String CMD_ADD = "ADD";
public final static String CMD_ANS = "ANS";
public final static String CMD_BLP = "BLP";
public final static String CMD_BYE = "BYE";
public final static String CMD_CAL = "CAL";
public final static String CMD_CHG = "CHG";
public final static String CMD_FLN = "FLN";
public final static String CMD_GTC = "GTC";
public final static String CMD_INF = "INF";
public final static String CMD_ILN = "ILN";
public final static String CMD_IRO = "IRO";
public final static String CMD_JOI = "JOI";
public final static String CMD_LST = "LST";
public final static String CMD_MSG = "MSG";
public final static String CMD_NAK = "NAK";
public final static String CMD_NLN = "NLN";
public final static String CMD_OUT = "OUT";
public final static String CMD_REM = "REM";
public final static String CMD_RNG = "RNG";
public final static String CMD_SYN = "SYN";
public final static String CMD_USR = "USR";
public final static String CMD_VER = "VER";
public final static String CMD_XFR = "XFR";
public final static String ERR_SYNTAX_ERROR = "200";
public final static String ERR_INVALID_PARAMETER = "201";
public final static String ERR_INVALID_USER = "205";
public final static String ERR_FQDN_MISSING = "206";
public final static String ERR_ALREADY_LOGIN = "207";
public final static String ERR_INVALID_USERNAME = "208";
public final static String ERR_INVALID_FRIENDLY_NAME = "209";
public final static String ERR_LIST_FULL = "210";
public final static String ERR_NOT_ON_LIST = "216";
public final static String ERR_ALREADY_IN_THE_MODE = "218";
public final static String ERR_ALREADY_IN_OPPOSITE_LIST = "219";
public final static String ERR_SWITCHBOARD_FAILED = "280";
public final static String ERR_NOTIFY_XFER_FAILED = "281";
public final static String ERR_REQUIRED_FIELDS_MISSING = "300";
public final static String ERR_NOT_LOGGED_IN = "302";
public final static String ERR_INTERNAL_SERVER = "500";
public final static String ERR_DB_SERVER = "501";
public final static String ERR_FILE_OPERATION = "510";
public final static String ERR_MEMORY_ALLOC = "520";
public final static String ERR_SERVER_BUSY = "600";
public final static String ERR_SERVER_UNAVAILABLE = "601";
public final static String ERR_PERR_NS_DOWN = "601";
public final static String ERR_DB_CONNECT = "603";
public final static String ERR_SERVER_GOING_DOWN = "604";
public final static String ERR_CREATE_CONNECTION = "707";
public final static String ERR_BLOCKING_WRITE = "711";
public final static String ERR_SESSION_OVERLOAD = "712";
public final static String ERR_USER_TOO_ACTIVE = "713";
public final static String ERR_TOO_MANY_SESSIONS = "714";
public final static String ERR_NOT_EXPECTED = "715";
public final static String ERR_BAD_FRIEND_FILE = "717";
public final static String ERR_AUTHENTICATION_FAILED = "911";
public final static String ERR_NOT_ALLOWED_WHEN_OFFLINE = "913";
public final static String ERR_NOT_ACCEPTING_NEW_USERS = "920";
public final static String STATE_ONLINE = "NLN";
public final static String STATE_OFFLINE = "FLN";
public final static String STATE_HIDDEN = "HDN";
public final static String STATE_BUSY = "BSY";
public final static String STATE_IDLE = "IDL";
public final static String STATE_BRB = "BRB";
public final static String STATE_AWAY = "AWY";
public final static String STATE_PHONE = "PHN";
public final static String STATE_LUNCH = "LUN";
/**
* Retrieves the next available transaction ID that is unique
* within this virtual machine context.
*
* @returns int a signed 32-bit transaction ID
*/
public static synchronized int getTransactionID() {
return transactionID++;
}
public static synchronized void reset() {
transactionID = 0;
}
private static int transactionID = 0;
}
| gpl-2.0 |
zulfikar2/CSPortfolio | JAVA/SAD_Search/ModelDisplay.java | 1120 | import java.awt.Graphics;
/**
* Interface to used to communicate between a model
* and its display
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public interface ModelDisplay
{
/** method to notify the thing that displays that
* the model has changed */
public void modelChanged();
/** method to add the model to the world
* @param model the model object to add */
public void addModel(Object model);
/**
* Method to remove the model from the world
* @param model the model object to remove */
public void remove(Object model);
/**
* Method that returns the graphics context
* for this model display
* @return the graphics context
*/
public Graphics getGraphics();
/**
* Method to clear the background
*/
public void clearBackground();
/** Method to get the width of the display
* @return the width in pixels of the display
*/
public int getWidth();
/** Method to get the height of the display
* @return the height in pixels of the display
*/
public int getHeight();
} | gpl-2.0 |
leeclarke/CAHServer | src/main/java/com/meadowhawk/cah/dao/AbstractJpaDAO.java | 1157 | package com.meadowhawk.cah.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
public abstract class AbstractJpaDAO<T> {
public enum DBSortOrder{
DESC, ASC
}
protected Class<T> clazz;
@PersistenceContext
EntityManager entityManager;
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
@Transactional(readOnly = true)
public T findOne(Long id) {
return entityManager.find(clazz, id);
}
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<T> findAll() {
return entityManager.createQuery("from " + clazz.getName()).getResultList();
}
@Transactional
public void save(T entity) {
entityManager.persist(entity);
}
@Transactional
public void update(T entity) {
entityManager.merge(entity);
}
@Transactional
public void delete(T entity) {
entityManager.remove(entityManager.merge(entity));
}
@Transactional
public void deleteById(Long entityId) {
final T entity = findOne( entityId );
if(entity != null){
delete( entity );
}
}
}
| gpl-2.0 |
phantamanta44/PWarfare | src/main/java/io/github/phantamanta44/pwarfare/gui/RespawnGui.java | 6436 | package io.github.phantamanta44.pwarfare.gui;
import io.github.phantamanta44.pwarfare.Game;
import io.github.phantamanta44.pwarfare.data.GameMap;
import io.github.phantamanta44.pwarfare.data.GameMap.GameMode;
import io.github.phantamanta44.pwarfare.data.GamePlayer;
import io.github.phantamanta44.pwarfare.data.GamePlayer.GameTeam;
import io.github.phantamanta44.pwarfare.data.GamePlayer.PlayerState;
import io.github.phantamanta44.pwarfare.data.GameSquad;
import io.github.phantamanta44.pwarfare.objective.ConqObjective;
import io.github.phantamanta44.pwarfare.util.StackFactory;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
public class RespawnGui extends GameGui {
public static final String[] classNames = new String[] {"ASSAULT", "ENGINEER", "SUPPORT", "RECON"};
private GamePlayer player;
private boolean canRespawn = false;
private Object point;
public RespawnGui(GamePlayer pl) {
super("DEPLOY", 5);
player = pl;
generateLoadoutGui();
inv.setItem(40, StackFactory.generateStack(Material.BOOK, 1, 0, "Edit Loadout"));
inv.setItem(43, StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 8, ChatColor.AQUA + "DEPLOY"));
inv.setItem(44, StackFactory.generateStack(Material.STAINED_GLASS_PANE, player.getTimeToRespawn(), 8, ChatColor.AQUA + "DEPLOY"));
if (Game.INSTANCE.getCurrentMap().getGameMode() == GameMode.CONQ)
setupConqGui();
}
private void setupConqGui() {
ConqObjective obj = (ConqObjective)Game.INSTANCE.getCurrentMap().getObjective();
ItemStack blueIs = StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 11, ChatColor.DARK_GRAY + "Select a spawn point.");
ItemStack greenIs = StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 5, ChatColor.DARK_GRAY + "Select a spawn point.");
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 9; x++)
inv.setItem(y * 9 + x, blueIs);
}
for (int i = 0; i < 9; i++)
inv.setItem(27 + i, greenIs);
inv.setItem(10, StackFactory.generateStack(Material.STAINED_CLAY, 1, 9, "Deploy on Team Spawn"));
for (int i = 0; i < 3; i++) {
GameTeam flagOwner = obj.getFlagStatus(i);
if (flagOwner == player.getTeam())
inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.STAINED_CLAY, 1, 14, ChatColor.BLUE + "Deploy on Point " + ConqObjective.flagName[i]));
else if (flagOwner == GameTeam.NONE)
inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.WOOL, 1, 0, "Point " + ConqObjective.flagName[i]));
else
inv.setItem(i * 2 + 12, StackFactory.generateStack(Material.STAINED_CLAY, 1, 1, "Point " + ConqObjective.flagName[i]));
}
GameSquad squad = player.getSquad();
if (squad != null) {
for (int i = 0; i < 3; i++) {
try {
GamePlayer member = squad.members.get(i);
if (member.getState() == PlayerState.INGAME)
inv.setItem(27 + i, StackFactory.generateStack(Material.ARMOR_STAND, 1, 0, ChatColor.BLUE + "Deploy on " + member.getName()));
else
inv.setItem(27 + i, StackFactory.generateStack(Material.STEP, 1, 0, member.getPlayer().getName()));
} catch (Throwable th) { }
}
}
}
private void generateLoadoutGui() {
for (int i = 36; i <= 39; i++)
inv.setItem(i, StackFactory.generateStack(Material.STAINED_GLASS, 1, player.getKitIndex() == (i - 36) ? 9 : 8, classNames[i - 36]));
}
@Override
protected void inventoryClicked(InventoryClickEvent event) {
event.setCancelled(true);
if (event.getCurrentItem() != null) {
ItemStack stack = event.getCurrentItem();
if (event.getSlot() >= 36 && event.getSlot() <= 39) {
player.setKit(event.getSlot() - 36);
generateLoadoutGui();
}
else if (event.getSlot() == 40) {
killGui();
new LoadoutGui(player).showGui(player.getPlayer());
}
else if (event.getSlot() >= 43) {
if (canRespawn && point != null) {
if (point instanceof Location)
player.getPlayer().teleport((Location)point);
else if (point instanceof Entity)
player.getPlayer().teleport((Entity)point);
player.receiveKit();
player.setState(PlayerState.INGAME);
}
}
else if (Game.INSTANCE.getCurrentMap().getGameMode() == GameMode.CONQ)
onConqClick(stack, event);
}
}
@SuppressWarnings("deprecation")
private void onConqClick(ItemStack stack, InventoryClickEvent event) {
GameMap map = Game.INSTANCE.getCurrentMap();
if (event.getSlot() == 10) {
point = map.getSpawnPoint(player.getTeam());
setupConqGui();
inv.setItem(10, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, "Deploy on Team Spawn"));
}
else if (event.getSlot() == 12) {
if (stack.getData().getData() == (byte)14) {
point = ((ConqObjective)map.getObjective()).getCap(0).toLocation(map.getWorld());
setupConqGui();
inv.setItem(12, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point A"));
}
}
else if (event.getSlot() == 14) {
if (stack.getData().getData() == (byte)14) {
point = ((ConqObjective)map.getObjective()).getCap(1).toLocation(map.getWorld());
setupConqGui();
inv.setItem(14, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point B"));
}
}
else if (event.getSlot() == 16) {
if (stack.getData().getData() == (byte)14) {
point = ((ConqObjective)map.getObjective()).getCap(2).toLocation(map.getWorld());
setupConqGui();
inv.setItem(16, StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on Point C"));
}
}
else if (event.getSlot() >= 27 && event.getSlot() <= 29) {
int i = 27 - event.getSlot();
if (player.getSquad() != null && player.getSquad().members.size() >= i) {
point = player.getSquad().members.get(i).getPlayer();
setupConqGui();
inv.setItem(event.getSlot(), StackFactory.generateStack(Material.STAINED_GLASS, 1, 5, ChatColor.BLUE + "Deploy on " + player.getSquad().members.get(i).getName()));
}
}
}
@Override
public void tick(long tick) {
if (player.getTimeToRespawn() <= 0) {
if (canRespawn = false) {
canRespawn = true;
for (int i = 0; i < 2; i++)
inv.setItem(43 + i, StackFactory.generateStack(Material.STAINED_GLASS_PANE, 1, 9, ChatColor.AQUA + "DEPLOY"));
}
}
else
inv.getItem(44).setAmount(player.getTimeToRespawn());
}
}
| gpl-2.0 |
actiontech/dble | src/main/java/com/actiontech/dble/route/factory/RouteStrategyFactory.java | 589 | /*
* Copyright (C) 2016-2022 ActionTech.
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher.
*/
package com.actiontech.dble.route.factory;
import com.actiontech.dble.route.RouteStrategy;
import com.actiontech.dble.route.impl.DefaultRouteStrategy;
/**
* RouteStrategyFactory
*
* @author wang.dw
*/
public final class RouteStrategyFactory {
private static RouteStrategy defaultStrategy = new DefaultRouteStrategy();
private RouteStrategyFactory() {
}
public static RouteStrategy getRouteStrategy() {
return defaultStrategy;
}
}
| gpl-2.0 |
guillep19/grails-responsys-ws-integration | ResponsysClientLib/src/com/rsys/ws/RetrieveLinkRecords.java | 19195 |
/**
* RetrieveLinkRecords.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST)
*/
package com.rsys.ws;
/**
* RetrieveLinkRecords bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class RetrieveLinkRecords
implements org.apache.axis2.databinding.ADBBean{
public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName(
"urn:ws.rsys.com",
"retrieveLinkRecords",
"");
/**
* field for LinkTable
*/
protected com.rsys.ws.InteractObject localLinkTable ;
/**
* Auto generated getter method
* @return com.rsys.ws.InteractObject
*/
public com.rsys.ws.InteractObject getLinkTable(){
return localLinkTable;
}
/**
* Auto generated setter method
* @param param LinkTable
*/
public void setLinkTable(com.rsys.ws.InteractObject param){
this.localLinkTable=param;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME);
return factory.createOMElement(dataSource,MY_QNAME);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"urn:ws.rsys.com");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":retrieveLinkRecords",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"retrieveLinkRecords",
xmlWriter);
}
}
if (localLinkTable==null){
writeStartElement(null, "urn:ws.rsys.com", "linkTable", xmlWriter);
// write the nil attribute
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","nil","1",xmlWriter);
xmlWriter.writeEndElement();
}else{
localLinkTable.serialize(new javax.xml.namespace.QName("urn:ws.rsys.com","linkTable"),
xmlWriter);
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("urn:ws.rsys.com")){
return "";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("urn:ws.rsys.com",
"linkTable"));
elementList.add(localLinkTable==null?null:
localLinkTable);
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static RetrieveLinkRecords parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
RetrieveLinkRecords object =
new RetrieveLinkRecords();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"retrieveLinkRecords".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (RetrieveLinkRecords)com.rsys.ws.fault.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("urn:ws.rsys.com","linkTable").equals(reader.getName())){
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
object.setLinkTable(null);
reader.next();
reader.next();
}else{
object.setLinkTable(com.rsys.ws.InteractObject.Factory.parse(reader));
reader.next();
}
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.edi.esb.camel/src/main/java/de/metas/edi/esb/pojo/invoice/cctop/Cctop111V.java | 4293 | package de.metas.edi.esb.pojo.invoice.cctop;
/*
* #%L
* de.metas.edi.esb
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.io.Serializable;
import java.util.Date;
public class Cctop111V implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 6774551274028670314L;
private String cOrderID;
private String mInOutID;
private Date dateOrdered;
private Date movementDate;
private String poReference;
private String shipmentDocumentno;
public final String getcOrderID()
{
return cOrderID;
}
public final void setcOrderID(final String cOrderID)
{
this.cOrderID = cOrderID;
}
public final String getmInOutID()
{
return mInOutID;
}
public final void setmInOutID(final String mInOutID)
{
this.mInOutID = mInOutID;
}
public Date getDateOrdered()
{
return dateOrdered;
}
public void setDateOrdered(final Date dateOrdered)
{
this.dateOrdered = dateOrdered;
}
public Date getMovementDate()
{
return movementDate;
}
public void setMovementDate(final Date movementDate)
{
this.movementDate = movementDate;
}
public String getPoReference()
{
return poReference;
}
public void setPoReference(final String poReference)
{
this.poReference = poReference;
}
public String getShipmentDocumentno()
{
return shipmentDocumentno;
}
public void setShipmentDocumentno(final String shipmentDocumentno)
{
this.shipmentDocumentno = shipmentDocumentno;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (cOrderID == null ? 0 : cOrderID.hashCode());
result = prime * result + (dateOrdered == null ? 0 : dateOrdered.hashCode());
result = prime * result + (mInOutID == null ? 0 : mInOutID.hashCode());
result = prime * result + (movementDate == null ? 0 : movementDate.hashCode());
result = prime * result + (poReference == null ? 0 : poReference.hashCode());
result = prime * result + (shipmentDocumentno == null ? 0 : shipmentDocumentno.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop111V other = (Cctop111V)obj;
if (cOrderID == null)
{
if (other.cOrderID != null)
{
return false;
}
}
else if (!cOrderID.equals(other.cOrderID))
{
return false;
}
if (dateOrdered == null)
{
if (other.dateOrdered != null)
{
return false;
}
}
else if (!dateOrdered.equals(other.dateOrdered))
{
return false;
}
if (mInOutID == null)
{
if (other.mInOutID != null)
{
return false;
}
}
else if (!mInOutID.equals(other.mInOutID))
{
return false;
}
if (movementDate == null)
{
if (other.movementDate != null)
{
return false;
}
}
else if (!movementDate.equals(other.movementDate))
{
return false;
}
if (poReference == null)
{
if (other.poReference != null)
{
return false;
}
}
else if (!poReference.equals(other.poReference))
{
return false;
}
if (shipmentDocumentno == null)
{
if (other.shipmentDocumentno != null)
{
return false;
}
}
else if (!shipmentDocumentno.equals(other.shipmentDocumentno))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop111V [cOrderID=" + cOrderID + ", mInOutID=" + mInOutID + ", dateOrdered=" + dateOrdered + ", movementDate=" + movementDate + ", poReference="
+ poReference
+ ", shipmentDocumentno=" + shipmentDocumentno + "]";
}
}
| gpl-2.0 |
judgels/uriel | app/org/iatoki/judgels/uriel/contest/manager/ContestManagerModel_.java | 678 | package org.iatoki.judgels.uriel.contest.manager;
import org.iatoki.judgels.play.model.AbstractModel_;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(ContestManagerModel.class)
public abstract class ContestManagerModel_ extends AbstractModel_ {
public static volatile SingularAttribute<ContestManagerModel, Long> id;
public static volatile SingularAttribute<ContestManagerModel, String> userJid;
public static volatile SingularAttribute<ContestManagerModel, String> contestJid;
}
| gpl-2.0 |
Myselia/MyseliaStem | src/main/java/com/myselia/stem/communication/seekers/LocalHostSeek.java | 1391 | package com.myselia.stem.communication.seekers;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import com.myselia.stem.communication.CommunicationDock;
public class LocalHostSeek implements Seek {
private volatile static LocalHostSeek uniqueInstance;
private DatagramSocket socket = null;
private String seekerName = "Local Host Seeker";
private LocalHostSeek() {
}
public void discoverComponents(byte[] infoPacket) throws IOException {
DatagramPacket networkPacket = new DatagramPacket(infoPacket, infoPacket.length,
InetAddress.getByName("127.0.0.1"), CommunicationDock.Component_Listen_Port);
socket.send(networkPacket);
}
@Override
public boolean hasSocket() {
if (socket == null)
return false;
return true;
}
@Override
public void setSocket(DatagramSocket socket) {
this.socket = socket;
}
public String printStatus(String componentType, String packet) {
return seekerName
+ "\n\t|-> Looking for: " + componentType + " on local port: " + CommunicationDock.Stem_Broadcast_Port
+ "\n\t|-> With packet: " + packet;
}
public static LocalHostSeek getInstance() {
if (uniqueInstance == null) {
synchronized (LocalNetworkSeek.class) {
if (uniqueInstance == null) {
uniqueInstance = new LocalHostSeek();
}
}
}
return uniqueInstance;
}
}
| gpl-2.0 |
graeme-lockley/string-calculator-java6-pbt | src/test/java/kata/MyCollections.java | 1712 | package kata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class MyCollections {
public static String join(Collection collection) {
return join(collection, "");
}
public static String join(Collection collection, String separator) {
StringBuilder sb = new StringBuilder();
for (Object o : collection) {
sb.append(separator).append(o.toString());
}
return sb.substring(separator.length());
}
public static <T> List<T> filter(List<T> items, Predicate<T> predicate) {
List<T> result = new ArrayList<T>();
for (T item : items) {
if (predicate.evaluate(item)) {
result.add(item);
}
}
return result;
}
public static <T> boolean exists(List<T> items, Predicate<T> predicate) {
for (T item : items) {
if (predicate.evaluate(item)) {
return true;
}
}
return false;
}
public static <S> S reduce(List<S> items, FoldFunction<S, S> foldFunction) {
Iterator<S> iterator = items.iterator();
S first = iterator.next();
return reduce(iterator, first, foldFunction);
}
public static <S, T> T reduce(List<S> items, T initial, FoldFunction<S, T> foldFunction) {
return reduce(items.iterator(), initial, foldFunction);
}
private static <S, T> T reduce(Iterator<S> items, T initial, FoldFunction<S, T> foldFunction) {
T result = initial;
while (items.hasNext()) {
result = foldFunction.execute(result, items.next());
}
return result;
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | sdk/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileCreationPage.java | 49017 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Eclipse Public License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.eclipse.org/org/documents/epl-v10.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ide.eclipse.adt.internal.wizards.newxmlfile;
import static com.android.SdkConstants.DOT_XML;
import static com.android.SdkConstants.HORIZONTAL_SCROLL_VIEW;
import static com.android.SdkConstants.LINEAR_LAYOUT;
import static com.android.SdkConstants.RES_QUALIFIER_SEP;
import static com.android.SdkConstants.SCROLL_VIEW;
import static com.android.SdkConstants.VALUE_FILL_PARENT;
import static com.android.SdkConstants.VALUE_MATCH_PARENT;
import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP_CHAR;
import static com.android.ide.eclipse.adt.internal.wizards.newxmlfile.ChooseConfigurationPage.RES_FOLDER_ABS;
import com.android.SdkConstants;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.ide.common.resources.configuration.ResourceQualifier;
import com.android.ide.eclipse.adt.AdtConstants;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.AdtUtils;
import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
import com.android.ide.eclipse.adt.internal.editors.IconFactory;
import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.ProjectCombo;
import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.ide.eclipse.adt.internal.sdk.Sdk.TargetChangeListener;
import com.android.resources.ResourceFolderType;
import com.android.sdklib.IAndroidTarget;
import com.android.utils.Pair;
import com.android.utils.SdkUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
/**
* This is the first page of the {@link NewXmlFileWizard} which provides the ability to create
* skeleton XML resources files for Android projects.
* <p/>
* This page is used to select the project, resource type and file name.
*/
class NewXmlFileCreationPage extends WizardPage {
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
// Ensure the initial focus is in the Name field; you usually don't need
// to edit the default text field (the project name)
if (visible && mFileNameTextField != null) {
mFileNameTextField.setFocus();
}
validatePage();
}
/**
* Information on one type of resource that can be created (e.g. menu, pref, layout, etc.)
*/
static class TypeInfo {
private final String mUiName;
private final ResourceFolderType mResFolderType;
private final String mTooltip;
private final Object mRootSeed;
private ArrayList<String> mRoots = new ArrayList<String>();
private final String mXmlns;
private final String mDefaultAttrs;
private final String mDefaultRoot;
private final int mTargetApiLevel;
public TypeInfo(String uiName,
String tooltip,
ResourceFolderType resFolderType,
Object rootSeed,
String defaultRoot,
String xmlns,
String defaultAttrs,
int targetApiLevel) {
mUiName = uiName;
mResFolderType = resFolderType;
mTooltip = tooltip;
mRootSeed = rootSeed;
mDefaultRoot = defaultRoot;
mXmlns = xmlns;
mDefaultAttrs = defaultAttrs;
mTargetApiLevel = targetApiLevel;
}
/** Returns the UI name for the resource type. Unique. Never null. */
String getUiName() {
return mUiName;
}
/** Returns the tooltip for the resource type. Can be null. */
String getTooltip() {
return mTooltip;
}
/**
* Returns the name of the {@link ResourceFolderType}.
* Never null but not necessarily unique,
* e.g. two types use {@link ResourceFolderType#XML}.
*/
String getResFolderName() {
return mResFolderType.getName();
}
/**
* Returns the matching {@link ResourceFolderType}.
* Never null but not necessarily unique,
* e.g. two types use {@link ResourceFolderType#XML}.
*/
ResourceFolderType getResFolderType() {
return mResFolderType;
}
/**
* Returns the seed used to fill the root element values.
* The seed might be either a String, a String array, an {@link ElementDescriptor},
* a {@link DocumentDescriptor} or null.
*/
Object getRootSeed() {
return mRootSeed;
}
/**
* Returns the default root element that should be selected by default. Can be
* null.
*
* @param project the associated project, or null if not known
*/
String getDefaultRoot(IProject project) {
return mDefaultRoot;
}
/**
* Returns the list of all possible root elements for the resource type.
* This can be an empty ArrayList but not null.
* <p/>
* TODO: the root list SHOULD depend on the currently selected project, to include
* custom classes.
*/
ArrayList<String> getRoots() {
return mRoots;
}
/**
* If the generated resource XML file requires an "android" XMLNS, this should be set
* to {@link SdkConstants#NS_RESOURCES}. When it is null, no XMLNS is generated.
*/
String getXmlns() {
return mXmlns;
}
/**
* When not null, this represent extra attributes that must be specified in the
* root element of the generated XML file. When null, no extra attributes are inserted.
*
* @param project the project to get the attributes for
* @param root the selected root element string, never null
*/
String getDefaultAttrs(IProject project, String root) {
return mDefaultAttrs;
}
/**
* When not null, represents an extra string that should be written inside
* the element when constructed
*
* @param project the project to get the child content for
* @param root the chosen root element
* @return a string to be written inside the root element, or null if nothing
*/
String getChild(IProject project, String root) {
return null;
}
/**
* The minimum API level required by the current SDK target to support this feature.
*
* @return the minimum API level
*/
public int getTargetApiLevel() {
return mTargetApiLevel;
}
}
/**
* TypeInfo, information for each "type" of file that can be created.
*/
private static final TypeInfo[] sTypes = {
new TypeInfo(
"Layout", // UI name
"An XML file that describes a screen layout.", // tooltip
ResourceFolderType.LAYOUT, // folder type
AndroidTargetData.DESCRIPTOR_LAYOUT, // root seed
LINEAR_LAYOUT, // default root
SdkConstants.NS_RESOURCES, // xmlns
"", // not used, see below
1 // target API level
) {
@Override
String getDefaultRoot(IProject project) {
// TODO: Use GridLayout by default for new SDKs
// (when we've ironed out all the usability issues)
//Sdk currentSdk = Sdk.getCurrent();
//if (project != null && currentSdk != null) {
// IAndroidTarget target = currentSdk.getTarget(project);
// // fill_parent was renamed match_parent in API level 8
// if (target != null && target.getVersion().getApiLevel() >= 13) {
// return GRID_LAYOUT;
// }
//}
return LINEAR_LAYOUT;
};
// The default attributes must be determined dynamically since whether
// we use match_parent or fill_parent depends on the API level of the
// project
@Override
String getDefaultAttrs(IProject project, String root) {
Sdk currentSdk = Sdk.getCurrent();
String fill = VALUE_FILL_PARENT;
if (currentSdk != null) {
IAndroidTarget target = currentSdk.getTarget(project);
// fill_parent was renamed match_parent in API level 8
if (target != null && target.getVersion().getApiLevel() >= 8) {
fill = VALUE_MATCH_PARENT;
}
}
// Only set "vertical" orientation of LinearLayouts by default;
// for GridLayouts for example we want to rely on the real default
// of the layout
String size = String.format(
"android:layout_width=\"%1$s\"\n" //$NON-NLS-1$
+ "android:layout_height=\"%2$s\"", //$NON-NLS-1$
fill, fill);
if (LINEAR_LAYOUT.equals(root)) {
return "android:orientation=\"vertical\"\n" + size; //$NON-NLS-1$
} else {
return size;
}
}
@Override
String getChild(IProject project, String root) {
// Create vertical linear layouts inside new scroll views
if (SCROLL_VIEW.equals(root) || HORIZONTAL_SCROLL_VIEW.equals(root)) {
return " <LinearLayout " //$NON-NLS-1$
+ getDefaultAttrs(project, root).replace('\n', ' ')
+ "></LinearLayout>\n"; //$NON-NLS-1$
}
return null;
}
},
new TypeInfo("Values", // UI name
"An XML file with simple values: colors, strings, dimensions, etc.", // tooltip
ResourceFolderType.VALUES, // folder type
SdkConstants.TAG_RESOURCES, // root seed
null, // default root
null, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("Drawable", // UI name
"An XML file that describes a drawable.", // tooltip
ResourceFolderType.DRAWABLE, // folder type
AndroidTargetData.DESCRIPTOR_DRAWABLE, // root seed
null, // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("Menu", // UI name
"An XML file that describes an menu.", // tooltip
ResourceFolderType.MENU, // folder type
SdkConstants.TAG_MENU, // root seed
null, // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("Color List", // UI name
"An XML file that describes a color state list.", // tooltip
ResourceFolderType.COLOR, // folder type
AndroidTargetData.DESCRIPTOR_COLOR, // root seed
"selector", //$NON-NLS-1$ // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("Property Animation", // UI name
"An XML file that describes a property animation", // tooltip
ResourceFolderType.ANIMATOR, // folder type
AndroidTargetData.DESCRIPTOR_ANIMATOR, // root seed
"set", //$NON-NLS-1$ // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
11 // target API level
),
new TypeInfo("Tween Animation", // UI name
"An XML file that describes a tween animation.", // tooltip
ResourceFolderType.ANIM, // folder type
AndroidTargetData.DESCRIPTOR_ANIM, // root seed
"set", //$NON-NLS-1$ // default root
null, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("AppWidget Provider", // UI name
"An XML file that describes a widget provider.", // tooltip
ResourceFolderType.XML, // folder type
AndroidTargetData.DESCRIPTOR_APPWIDGET_PROVIDER, // root seed
null, // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
3 // target API level
),
new TypeInfo("Preference", // UI name
"An XML file that describes preferences.", // tooltip
ResourceFolderType.XML, // folder type
AndroidTargetData.DESCRIPTOR_PREFERENCES, // root seed
SdkConstants.CLASS_NAME_PREFERENCE_SCREEN, // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
1 // target API level
),
new TypeInfo("Searchable", // UI name
"An XML file that describes a searchable.", // tooltip
ResourceFolderType.XML, // folder type
AndroidTargetData.DESCRIPTOR_SEARCHABLE, // root seed
null, // default root
SdkConstants.NS_RESOURCES, // xmlns
null, // default attributes
1 // target API level
),
// Still missing: Interpolator, Raw and Mipmap. Raw should probably never be in
// this menu since it's not often used for creating XML files.
};
private NewXmlFileWizard.Values mValues;
private ProjectCombo mProjectButton;
private Text mFileNameTextField;
private Combo mTypeCombo;
private IStructuredSelection mInitialSelection;
private ResourceFolderType mInitialFolderType;
private boolean mInternalTypeUpdate;
private TargetChangeListener mSdkTargetChangeListener;
private Table mRootTable;
private TableViewer mRootTableViewer;
// --- UI creation ---
/**
* Constructs a new {@link NewXmlFileCreationPage}.
* <p/>
* Called by {@link NewXmlFileWizard#createMainPage}.
*/
protected NewXmlFileCreationPage(String pageName, NewXmlFileWizard.Values values) {
super(pageName);
mValues = values;
setPageComplete(false);
}
public void setInitialSelection(IStructuredSelection initialSelection) {
mInitialSelection = initialSelection;
}
public void setInitialFolderType(ResourceFolderType initialType) {
mInitialFolderType = initialType;
}
/**
* Called by the parent Wizard to create the UI for this Wizard Page.
*
* {@inheritDoc}
*
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
@Override
@SuppressWarnings("unused") // SWT constructors have side effects, they aren't unused
public void createControl(Composite parent) {
// This UI is maintained with WindowBuilder.
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout(2, false /*makeColumnsEqualWidth*/));
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
// label before type radios
Label typeLabel = new Label(composite, SWT.NONE);
typeLabel.setText("Resource Type:");
mTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
mTypeCombo.setToolTipText("What type of resource would you like to create?");
mTypeCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (mInitialFolderType != null) {
mTypeCombo.setEnabled(false);
}
mTypeCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TypeInfo type = getSelectedType();
if (type != null) {
onSelectType(type);
}
}
});
// separator
Label separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
GridData gd2 = new GridData(GridData.GRAB_HORIZONTAL);
gd2.horizontalAlignment = SWT.FILL;
gd2.horizontalSpan = 2;
separator.setLayoutData(gd2);
// Project: [button]
String tooltip = "The Android Project where the new resource file will be created.";
Label projectLabel = new Label(composite, SWT.NONE);
projectLabel.setText("Project:");
projectLabel.setToolTipText(tooltip);
ProjectChooserHelper helper =
new ProjectChooserHelper(getShell(), null /* filter */);
mProjectButton = new ProjectCombo(helper, composite, mValues.project);
mProjectButton.setToolTipText(tooltip);
mProjectButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mProjectButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IProject project = mProjectButton.getSelectedProject();
if (project != mValues.project) {
changeProject(project);
}
};
});
// Filename: [text]
Label fileLabel = new Label(composite, SWT.NONE);
fileLabel.setText("File:");
fileLabel.setToolTipText("The name of the resource file to create.");
mFileNameTextField = new Text(composite, SWT.BORDER);
mFileNameTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mFileNameTextField.setToolTipText(tooltip);
mFileNameTextField.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
mValues.name = mFileNameTextField.getText();
validatePage();
}
});
// separator
Label rootSeparator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
GridData gd = new GridData(GridData.GRAB_HORIZONTAL);
gd.horizontalAlignment = SWT.FILL;
gd.horizontalSpan = 2;
rootSeparator.setLayoutData(gd);
// Root Element:
// [TableViewer]
Label rootLabel = new Label(composite, SWT.NONE);
rootLabel.setText("Root Element:");
new Label(composite, SWT.NONE);
mRootTableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
mRootTable = mRootTableViewer.getTable();
GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
tableGridData.heightHint = 200;
mRootTable.setLayoutData(tableGridData);
setControl(composite);
// Update state the first time
setErrorMessage(null);
setMessage(null);
initializeFromSelection(mInitialSelection);
updateAvailableTypes();
initializeFromFixedType();
initializeRootValues();
installTargetChangeListener();
initialSelectType();
validatePage();
}
private void initialSelectType() {
TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
int typeIndex = getTypeComboIndex(mValues.type);
if (typeIndex == -1) {
typeIndex = 0;
} else {
assert mValues.type == types[typeIndex];
}
mTypeCombo.select(typeIndex);
onSelectType(types[typeIndex]);
updateRootCombo(types[typeIndex]);
}
private void installTargetChangeListener() {
mSdkTargetChangeListener = new TargetChangeListener() {
@Override
public IProject getProject() {
return mValues.project;
}
@Override
public void reload() {
if (mValues.project != null) {
changeProject(mValues.project);
}
}
};
AdtPlugin.getDefault().addTargetListener(mSdkTargetChangeListener);
}
@Override
public void dispose() {
if (mSdkTargetChangeListener != null) {
AdtPlugin.getDefault().removeTargetListener(mSdkTargetChangeListener);
mSdkTargetChangeListener = null;
}
super.dispose();
}
/**
* Returns the selected root element string, if any.
*
* @return The selected root element string or null.
*/
public String getRootElement() {
int index = mRootTable.getSelectionIndex();
if (index >= 0) {
Object[] roots = (Object[]) mRootTableViewer.getInput();
return roots[index].toString();
}
return null;
}
/**
* Called by {@link NewXmlFileWizard} to initialize the page with the selection
* received by the wizard -- typically the current user workbench selection.
* <p/>
* Things we expect to find out from the selection:
* <ul>
* <li>The project name, valid if it's an android nature.</li>
* <li>The current folder, valid if it's a folder under /res</li>
* <li>An existing filename, in which case the user will be asked whether to override it.</li>
* </ul>
* <p/>
* The selection can also be set to a {@link Pair} of {@link IProject} and a workspace
* resource path (where the resource path does not have to exist yet, such as res/anim/).
*
* @param selection The selection when the wizard was initiated.
*/
private boolean initializeFromSelection(IStructuredSelection selection) {
if (selection == null) {
return false;
}
// Find the best match in the element list. In case there are multiple selected elements
// select the one that provides the most information and assign them a score,
// e.g. project=1 + folder=2 + file=4.
IProject targetProject = null;
String targetWsFolderPath = null;
String targetFileName = null;
int targetScore = 0;
for (Object element : selection.toList()) {
if (element instanceof IAdaptable) {
IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
IProject project = res != null ? res.getProject() : null;
// Is this an Android project?
try {
if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
continue;
}
} catch (CoreException e) {
// checking the nature failed, ignore this resource
continue;
}
int score = 1; // we have a valid project at least
IPath wsFolderPath = null;
String fileName = null;
assert res != null; // Eclipse incorrectly thinks res could be null, so tell it no
if (res.getType() == IResource.FOLDER) {
wsFolderPath = res.getProjectRelativePath();
} else if (res.getType() == IResource.FILE) {
if (SdkUtils.endsWithIgnoreCase(res.getName(), DOT_XML)) {
fileName = res.getName();
}
wsFolderPath = res.getParent().getProjectRelativePath();
}
// Disregard this folder selection if it doesn't point to /res/something
if (wsFolderPath != null &&
wsFolderPath.segmentCount() > 1 &&
SdkConstants.FD_RESOURCES.equals(wsFolderPath.segment(0))) {
score += 2;
} else {
wsFolderPath = null;
fileName = null;
}
score += fileName != null ? 4 : 0;
if (score > targetScore) {
targetScore = score;
targetProject = project;
targetWsFolderPath = wsFolderPath != null ? wsFolderPath.toString() : null;
targetFileName = fileName;
}
} else if (element instanceof Pair<?,?>) {
// Pair of Project/String
@SuppressWarnings("unchecked")
Pair<IProject,String> pair = (Pair<IProject,String>)element;
targetScore = 1;
targetProject = pair.getFirst();
targetWsFolderPath = pair.getSecond();
targetFileName = "";
}
}
if (targetProject == null) {
// Try to figure out the project from the active editor
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorPart activeEditor = page.getActiveEditor();
if (activeEditor instanceof AndroidXmlEditor) {
Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
if (input instanceof FileEditorInput) {
FileEditorInput fileInput = (FileEditorInput) input;
targetScore = 1;
IFile file = fileInput.getFile();
targetProject = file.getProject();
IPath path = file.getParent().getProjectRelativePath();
targetWsFolderPath = path != null ? path.toString() : null;
}
}
}
}
}
if (targetProject == null) {
// If we didn't find a default project based on the selection, check how many
// open Android projects we can find in the current workspace. If there's only
// one, we'll just select it by default.
IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
if (projects != null && projects.length == 1) {
targetScore = 1;
targetProject = projects[0].getProject();
}
}
// Now set the UI accordingly
if (targetScore > 0) {
mValues.project = targetProject;
mValues.folderPath = targetWsFolderPath;
mProjectButton.setSelectedProject(targetProject);
mFileNameTextField.setText(targetFileName != null ? targetFileName : ""); //$NON-NLS-1$
// If the current selection context corresponds to a specific file type,
// select it.
if (targetWsFolderPath != null) {
int pos = targetWsFolderPath.lastIndexOf(WS_SEP_CHAR);
if (pos >= 0) {
targetWsFolderPath = targetWsFolderPath.substring(pos + 1);
}
String[] folderSegments = targetWsFolderPath.split(RES_QUALIFIER_SEP);
if (folderSegments.length > 0) {
String folderName = folderSegments[0];
selectTypeFromFolder(folderName);
}
}
}
return true;
}
private void initializeFromFixedType() {
if (mInitialFolderType != null) {
for (TypeInfo type : sTypes) {
if (type.getResFolderType() == mInitialFolderType) {
mValues.type = type;
updateFolderPath(type);
break;
}
}
}
}
/**
* Given a folder name, such as "drawable", select the corresponding type in
* the dropdown.
*/
void selectTypeFromFolder(String folderName) {
List<TypeInfo> matches = new ArrayList<TypeInfo>();
boolean selected = false;
TypeInfo selectedType = getSelectedType();
for (TypeInfo type : sTypes) {
if (type.getResFolderName().equals(folderName)) {
matches.add(type);
selected |= type == selectedType;
}
}
if (matches.size() == 1) {
// If there's only one match, select it if it's not already selected
if (!selected) {
selectType(matches.get(0));
}
} else if (matches.size() > 1) {
// There are multiple type candidates for this folder. This can happen
// for /res/xml for example. Check to see if one of them is currently
// selected. If yes, leave the selection unchanged. If not, deselect all type.
if (!selected) {
selectType(null);
}
} else {
// Nothing valid was selected.
selectType(null);
}
}
/**
* Initialize the root values of the type infos based on the current framework values.
*/
private void initializeRootValues() {
IProject project = mValues.project;
for (TypeInfo type : sTypes) {
// Clear all the roots for this type
ArrayList<String> roots = type.getRoots();
if (roots.size() > 0) {
roots.clear();
}
// depending of the type of the seed, initialize the root in different ways
Object rootSeed = type.getRootSeed();
if (rootSeed instanceof String) {
// The seed is a single string, Add it as-is.
roots.add((String) rootSeed);
} else if (rootSeed instanceof String[]) {
// The seed is an array of strings. Add them as-is.
for (String value : (String[]) rootSeed) {
roots.add(value);
}
} else if (rootSeed instanceof Integer && project != null) {
// The seed is a descriptor reference defined in AndroidTargetData.DESCRIPTOR_*
// In this case add all the children element descriptors defined, recursively,
// and avoid infinite recursion by keeping track of what has already been added.
// Note: if project is null, the root list will be empty since it has been
// cleared above.
// get the AndroidTargetData from the project
IAndroidTarget target = null;
AndroidTargetData data = null;
target = Sdk.getCurrent().getTarget(project);
if (target == null) {
// A project should have a target. The target can be missing if the project
// is an old project for which a target hasn't been affected or if the
// target no longer exists in this SDK. Simply log the error and dismiss.
AdtPlugin.log(IStatus.INFO,
"NewXmlFile wizard: no platform target for project %s", //$NON-NLS-1$
project.getName());
continue;
} else {
data = Sdk.getCurrent().getTargetData(target);
if (data == null) {
// We should have both a target and its data.
// However if the wizard is invoked whilst the platform is still being
// loaded we can end up in a weird case where we have a target but it
// doesn't have any data yet.
// Lets log a warning and silently ignore this root.
AdtPlugin.log(IStatus.INFO,
"NewXmlFile wizard: no data for target %s, project %s", //$NON-NLS-1$
target.getName(), project.getName());
continue;
}
}
IDescriptorProvider provider = data.getDescriptorProvider((Integer)rootSeed);
ElementDescriptor descriptor = provider.getDescriptor();
if (descriptor != null) {
HashSet<ElementDescriptor> visited = new HashSet<ElementDescriptor>();
initRootElementDescriptor(roots, descriptor, visited);
}
// Sort alphabetically.
Collections.sort(roots);
}
}
}
/**
* Helper method to recursively insert all XML names for the given {@link ElementDescriptor}
* into the roots array list. Keeps track of visited nodes to avoid infinite recursion.
* Also avoids inserting the top {@link DocumentDescriptor} which is generally synthetic
* and not a valid root element.
*/
private void initRootElementDescriptor(ArrayList<String> roots,
ElementDescriptor desc, HashSet<ElementDescriptor> visited) {
if (!(desc instanceof DocumentDescriptor)) {
String xmlName = desc.getXmlName();
if (xmlName != null && xmlName.length() > 0) {
roots.add(xmlName);
}
}
visited.add(desc);
for (ElementDescriptor child : desc.getChildren()) {
if (!visited.contains(child)) {
initRootElementDescriptor(roots, child, visited);
}
}
}
/**
* Changes mProject to the given new project and update the UI accordingly.
* <p/>
* Note that this does not check if the new project is the same as the current one
* on purpose, which allows a project to be updated when its target has changed or
* when targets are loaded in the background.
*/
private void changeProject(IProject newProject) {
mValues.project = newProject;
// enable types based on new API level
updateAvailableTypes();
initialSelectType();
// update the folder name based on API level
updateFolderPath(mValues.type);
// update the Type with the new descriptors.
initializeRootValues();
// update the combo
updateRootCombo(mValues.type);
validatePage();
}
private void onSelectType(TypeInfo type) {
// Do nothing if this is an internal modification or if the widget has been
// deselected.
if (mInternalTypeUpdate) {
return;
}
mValues.type = type;
if (type == null) {
return;
}
// update the combo
updateRootCombo(type);
// update the folder path
updateFolderPath(type);
validatePage();
}
/** Updates the selected type in the type dropdown control */
private void setSelectedType(TypeInfo type) {
TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
if (types != null) {
for (int i = 0, n = types.length; i < n; i++) {
if (types[i] == type) {
mTypeCombo.select(i);
break;
}
}
}
}
/** Returns the selected type in the type dropdown control */
private TypeInfo getSelectedType() {
int index = mTypeCombo.getSelectionIndex();
if (index != -1) {
TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
return types[index];
}
return null;
}
/** Returns the selected index in the type dropdown control */
private int getTypeComboIndex(TypeInfo type) {
TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
for (int i = 0, n = types.length; i < n; i++) {
if (type == types[i]) {
return i;
}
}
return -1;
}
/** Updates the folder path to reflect the given type */
private void updateFolderPath(TypeInfo type) {
String wsFolderPath = mValues.folderPath;
String newPath = null;
FolderConfiguration config = mValues.configuration;
ResourceQualifier qual = config.getInvalidQualifier();
if (qual == null) {
// The configuration is valid. Reformat the folder path using the canonical
// value from the configuration.
newPath = RES_FOLDER_ABS + config.getFolderName(type.getResFolderType());
} else {
// The configuration is invalid. We still update the path but this time
// do it manually on the string.
if (wsFolderPath.startsWith(RES_FOLDER_ABS)) {
wsFolderPath = wsFolderPath.replaceFirst(
"^(" + RES_FOLDER_ABS +")[^-]*(.*)", //$NON-NLS-1$ //$NON-NLS-2$
"\\1" + type.getResFolderName() + "\\2"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
newPath = RES_FOLDER_ABS + config.getFolderName(type.getResFolderType());
}
}
if (newPath != null && !newPath.equals(wsFolderPath)) {
mValues.folderPath = newPath;
}
}
/**
* Helper method that fills the values of the "root element" combo box based
* on the currently selected type radio button. Also disables the combo is there's
* only one choice. Always select the first root element for the given type.
*
* @param type The currently selected {@link TypeInfo}, or null
*/
private void updateRootCombo(TypeInfo type) {
IBaseLabelProvider labelProvider = new ColumnLabelProvider() {
@Override
public Image getImage(Object element) {
return IconFactory.getInstance().getIcon(element.toString());
}
};
mRootTableViewer.setContentProvider(new ArrayContentProvider());
mRootTableViewer.setLabelProvider(labelProvider);
if (type != null) {
// get the list of roots. The list can be empty but not null.
ArrayList<String> roots = type.getRoots();
mRootTableViewer.setInput(roots.toArray());
int index = 0; // default is to select the first one
String defaultRoot = type.getDefaultRoot(mValues.project);
if (defaultRoot != null) {
index = roots.indexOf(defaultRoot);
}
mRootTable.select(index < 0 ? 0 : index);
mRootTable.showSelection();
}
}
/**
* Helper method to select the current type in the type dropdown
*
* @param type The TypeInfo matching the radio button to selected or null to deselect them all.
*/
private void selectType(TypeInfo type) {
mInternalTypeUpdate = true;
mValues.type = type;
if (type == null) {
if (mTypeCombo.getSelectionIndex() != -1) {
mTypeCombo.deselect(mTypeCombo.getSelectionIndex());
}
} else {
setSelectedType(type);
}
updateRootCombo(type);
mInternalTypeUpdate = false;
}
/**
* Add the available types in the type combobox, based on whether they are available
* for the current SDK.
* <p/>
* A type is available either if:
* - if mProject is null, API level 1 is considered valid
* - if mProject is !null, the project->target->API must be >= to the type's API level.
*/
private void updateAvailableTypes() {
IProject project = mValues.project;
IAndroidTarget target = project != null ? Sdk.getCurrent().getTarget(project) : null;
int currentApiLevel = 1;
if (target != null) {
currentApiLevel = target.getVersion().getApiLevel();
}
List<String> items = new ArrayList<String>(sTypes.length);
List<TypeInfo> types = new ArrayList<TypeInfo>(sTypes.length);
for (int i = 0, n = sTypes.length; i < n; i++) {
TypeInfo type = sTypes[i];
if (type.getTargetApiLevel() <= currentApiLevel) {
items.add(type.getUiName());
types.add(type);
}
}
mTypeCombo.setItems(items.toArray(new String[items.size()]));
mTypeCombo.setData(types.toArray(new TypeInfo[types.size()]));
}
/**
* Validates the fields, displays errors and warnings.
* Enables the finish button if there are no errors.
*/
private void validatePage() {
String error = null;
String warning = null;
// -- validate type
TypeInfo type = mValues.type;
if (error == null) {
if (type == null) {
error = "One of the types must be selected (e.g. layout, values, etc.)";
}
}
// -- validate project
if (mValues.project == null) {
error = "Please select an Android project.";
}
// -- validate type API level
if (error == null) {
IAndroidTarget target = Sdk.getCurrent().getTarget(mValues.project);
int currentApiLevel = 1;
if (target != null) {
currentApiLevel = target.getVersion().getApiLevel();
}
assert type != null;
if (type.getTargetApiLevel() > currentApiLevel) {
error = "The API level of the selected type (e.g. AppWidget, etc.) is not " +
"compatible with the API level of the project.";
}
}
// -- validate filename
if (error == null) {
String fileName = mValues.getFileName();
assert type != null;
ResourceFolderType folderType = type.getResFolderType();
error = ResourceNameValidator.create(true, folderType).isValid(fileName);
}
// -- validate destination file doesn't exist
if (error == null) {
IFile file = mValues.getDestinationFile();
if (file != null && file.exists()) {
warning = "The destination file already exists";
}
}
// -- update UI & enable finish if there's no error
setPageComplete(error == null);
if (error != null) {
setMessage(error, IMessageProvider.ERROR);
} else if (warning != null) {
setMessage(warning, IMessageProvider.WARNING);
} else {
setErrorMessage(null);
setMessage(null);
}
}
/**
* Returns the {@link TypeInfo} for the given {@link ResourceFolderType}, or null if
* not found
*
* @param folderType the {@link ResourceFolderType} to look for
* @return the corresponding {@link TypeInfo}
*/
static TypeInfo getTypeInfo(ResourceFolderType folderType) {
for (TypeInfo typeInfo : sTypes) {
if (typeInfo.getResFolderType() == folderType) {
return typeInfo;
}
}
return null;
}
}
| gpl-2.0 |
cjdev/httpobjects | core/src/main/java/org/httpobjects/ConnectionInfo.java | 2931 | /**
* Copyright (C) 2011, 2012 Commission Junction Inc.
*
* This file is part of httpobjects.
*
* httpobjects 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, or (at your option)
* any later version.
*
* httpobjects 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 httpobjects; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package org.httpobjects;
public class ConnectionInfo {
// String protocolVersion
// String protocol;
public final String localAddress;
public final Integer localPort;
public final String remoteAddress;
public final Integer remotePort;
public ConnectionInfo(String localAddress, Integer localPort, String remoteAddress, Integer remotePort) {
super();
this.localAddress = notNull(localAddress);
this.localPort = notNull(localPort);
this.remoteAddress = notNull(remoteAddress);
this.remotePort = notNull(remotePort);
}
private static <T> T notNull(T value){
if(value==null) throw new IllegalArgumentException("Null not allowed");
return value;
}
public String show() {
return "ConnectionInfo(" +
"localAddress = " + localAddress + "," +
"localPort = " + localPort + "," +
"remoteAddress = " + remoteAddress + "," +
"remotePort = " + remotePort + ")";
}
public boolean eq(ConnectionInfo that) {
return this.show().equals(that.show());
}
}
| gpl-2.0 |
petersalomonsen/frinika | src/uk/org/toot/midi/misc/GM.java | 20219 | // Copyright (C) 2005 - 2007 Steve Taylor.
// Distributed under the Toot Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.toot.org.uk/LICENSE_1_0.txt)
package uk.org.toot.midi.misc;
import uk.org.toot.music.tonality.Pitch;
/** Support for General MIDI Instrument Family and Family names. */
public class GM
{
// GM Level 2
public final static int HIGH_Q = 27;
public final static int SLAP = 28;
public final static int SCRATCH = 29;
public final static int SCRATCH_2 = 30;
public final static int STICKS = 31;
public final static int SQUARE = 32;
public final static int METRONOME = 33;
public final static int METRONOME_2 = 34;
// GM Level 1
public final static int ACOUSTIC_BASS_DRUM = 35;
public final static int BASS_DRUM_1 = 36;
public final static int SIDE_STICK = 37;
public final static int ACOUSTIC_SNARE = 38;
public final static int HAND_CLAP = 39;
public final static int ELECTRIC_SNARE = 40;
public final static int LOW_FLOOR_TOM = 41;
public final static int CLOSED_HI_HAT = 42;
public final static int HI_FLOOR_TOM = 43;
public final static int PEDAL_HI_HAT = 44;
public final static int LOW_TOM = 45;
public final static int OPEN_HI_HAT = 46;
public final static int LOW_MID_TOM = 47;
public final static int HI_MID_TOM = 48;
public final static int CRASH_CYMBAL_1 = 49;
public final static int HI_TOM = 50;
public final static int RIDE_CYMBAL_1 = 51;
public final static int CHINESE_CYMBAL = 52;
public final static int RIDE_BELL = 53;
public final static int TAMBOURINE = 54;
public final static int SPLASH_CYMBAL = 55;
public final static int COWBELL = 56;
public final static int CRASH_CYMBAL_2 = 57;
public final static int VIBRASLAP = 58;
public final static int RIDE_CYMBAL_2 = 59;
public final static int HI_BONGO = 60;
public final static int LOW_BONGO = 61;
public final static int MUTE_HI_CONGA = 62;
public final static int OPEN_HI_CONGA = 63;
public final static int LOW_CONGA = 64;
public final static int HI_TIMBALE = 65;
public final static int LOW_TIMBALE = 66;
public final static int HI_AGOGO = 67;
public final static int LOW_AGOGO = 68;
public final static int CABASA = 69;
public final static int MARACAS = 70;
public final static int SHORT_WHISTLE = 71;
public final static int LONG_WHISTLE = 72;
public final static int SHORT_GUIRO = 73;
public final static int LONG_GUIRO = 74;
public final static int CLAVES = 75;
public final static int HI_WOOD_BLOCK = 76;
public final static int LOW_WOOD_BLOCK = 77;
public final static int MUTE_CUICA = 78;
public final static int OPEN_CUICA = 79;
public final static int MUTE_TRIANGLE = 80;
public final static int OPEN_TRIANGLE = 81;
// GM Level 2
public final static int SHAKER = 82;
public final static int JINGLE_BELL = 83;
public final static int BELL_TREE = 84;
public final static int CASTANETS = 85;
public final static int MUTE_SURDO = 86;
public final static int OPEN_SURDO = 87;
static public String melodicFamilyName(int family) {
switch (family) {
case 0:
return "Piano";
case 1:
return "Chromatic Percussion";
case 2:
return "Organ";
case 3:
return "Guitar";
case 4:
return "Bass";
case 5:
return "Solo Strings";
case 6:
return "Ensemble";
case 7:
return "Brass";
case 8:
return "Reed";
case 9:
return "Pipe";
case 10:
return "Synth Lead";
case 11:
return "Synth Pad";
case 12:
return "Synth Effects";
case 13:
return "Ethnic";
case 14:
return "Percussive";
case 15:
return "Sound Effects";
}
return family + "?";
}
static public String melodicProgramName(int program) {
switch (program) {
case 0:
return "Acoustic Grand Piano";
case 1:
return "Bright Acoustic Piano";
case 2:
return "Electric Grand Piano";
case 3:
return "Honky-tonk Piano";
case 4:
return "Rhodes Piano";
case 5:
return "Chorused Piano";
case 6:
return "Harpsichord";
case 7:
return "Clavinet";
case 8:
return "Celesta";
case 9:
return "Glockenspiel";
case 10:
return "Music Box";
case 11:
return "Vibraphone";
case 12:
return "Marimba";
case 13:
return "Xylophone";
case 14:
return "Tubular Bells";
case 15:
return "Dulcimer";
case 16:
return "Hammond Organ";
case 17:
return "Percussive Organ";
case 18:
return "Rock Organ";
case 19:
return "Church Organ";
case 20:
return "Reed Organ";
case 21:
return "Accordion";
case 22:
return "Harmonica";
case 23:
return "Tango Accordion";
case 24:
return "Acoustic Guitar (nylon)";
case 25:
return "Acoustic Guitar (steel)";
case 26:
return "Electric Guitar (jazz)";
case 27:
return "Electric Guitar (clean)";
case 28:
return "Electric Guitar (muted)";
case 29:
return "Overdriven Guitar";
case 30:
return "Distortion Guitar";
case 31:
return "Guitar Harmonics";
case 32:
return "Acoustic Bass";
case 33:
return "Electric Bass (finger)";
case 34:
return "Electric Bass (pick)";
case 35:
return "Fretless Bass";
case 36:
return "Slap Bass 1";
case 37:
return "Slap Bass 2";
case 38:
return "Synth Bass 1";
case 39:
return "Synth Bass 2";
case 40:
return "Violin";
case 41:
return "Viola";
case 42:
return "Cello";
case 43:
return "Contrabass";
case 44:
return "Tremelo Strings";
case 45:
return "Pizzicato Strings";
case 46:
return "Orchestral Harp";
case 47:
return "Timpani";
case 48:
return "String Ensemble 1";
case 49:
return "String Ensemble 2";
case 50:
return "SynthStrings 1";
case 51:
return "SynthStrings 2";
case 52:
return "Choir Aahs";
case 53:
return "Voice Oohs";
case 54:
return "Synth Voice";
case 55:
return "Orchestra Hit";
case 56:
return "Trumpet";
case 57:
return "Trombone";
case 58:
return "Tuba";
case 59:
return "Muted Trumpet";
case 60:
return "French Horn";
case 61:
return "Brass Section";
case 62:
return "Synth Brass 1";
case 63:
return "Synth Brass 2";
case 64:
return "Soprano Sax";
case 65:
return "Alto Sax";
case 66:
return "Tenor Sax";
case 67:
return "Baritone Sax";
case 68:
return "Oboe";
case 69:
return "English Horn";
case 70:
return "Bassoon";
case 71:
return "Clarinet";
case 72:
return "Piccolo";
case 73:
return "Flute";
case 74:
return "Recorder";
case 75:
return "Pan Flute";
case 76:
return "Bottle Blow";
case 77:
return "Shakuhachi";
case 78:
return "Whistle";
case 79:
return "Ocarina";
case 80:
return "Lead 1 (square)";
case 81:
return "Lead 2 (sawtooth)";
case 82:
return "Lead 3 (calliope lead)";
case 83:
return "Lead 4 (chiff lead)";
case 84:
return "Lead 5 (charang)";
case 85:
return "Lead 6 (voice)";
case 86:
return "Lead 7 (fifths)";
case 87:
return "Lead 8 (bass + lead)";
case 88:
return "Pad 1 (new age)";
case 89:
return "Pad 2 (warm)";
case 90:
return "Pad 3 (polysynth)";
case 91:
return "Pad 4 (choir)";
case 92:
return "Pad 5 (bowed)";
case 93:
return "Pad 6 (metallic)";
case 94:
return "Pad 7 (halo)";
case 95:
return "Pad 8 (sweep)";
case 96:
return "FX 1 (rain)";
case 97:
return "FX 2 (soundtrack)";
case 98:
return "FX 3 (crystal)";
case 99:
return "FX 4 (atmosphere)";
case 100:
return "FX 5 (brightness)";
case 101:
return "FX 6 (goblins)";
case 102:
return "FX 7 (echoes)";
case 103:
return "FX 8 (sci-fi)";
case 104:
return "Sitar";
case 105:
return "Banjo";
case 106:
return "Shamisen";
case 107:
return "Koto";
case 108:
return "Kalimba";
case 109:
return "Bagpipe";
case 110:
return "Fiddle";
case 111:
return "Shanai";
case 112:
return "Tinkle Bell";
case 113:
return "Agogo";
case 114:
return "Steel Drums";
case 115:
return "Woodblock";
case 116:
return "Taiko Drum";
case 117:
return "Melodic Tom";
case 118:
return "Synth Drum";
case 119:
return "Reverse Cymbal";
case 120:
return "Guitar Fret Noise";
case 121:
return "Breath Noise";
case 122:
return "Seashore";
case 123:
return "Bird Tweet";
case 124:
return "Telephone Ring";
case 125:
return "Helicopter";
case 126:
return "Applause";
case 127:
return "Gunshot";
}
return program + "?";
}
// hats
public final static int[] HATS = {
OPEN_HI_HAT, CLOSED_HI_HAT, PEDAL_HI_HAT
};
// bass drums
public final static int[] BASS_DRUMS = {
ACOUSTIC_BASS_DRUM, BASS_DRUM_1
};
// snares
public final static int[] SNARES = {
ACOUSTIC_SNARE, ELECTRIC_SNARE, SIDE_STICK, HAND_CLAP
};
// toms
public final static int[] TOMS = {
HI_TOM, HI_MID_TOM, LOW_MID_TOM, LOW_TOM, HI_FLOOR_TOM, LOW_FLOOR_TOM
};
// cymbals
public final static int[] CYMBALS = {
RIDE_BELL, RIDE_CYMBAL_1, RIDE_CYMBAL_2, CRASH_CYMBAL_1,
CRASH_CYMBAL_2, CHINESE_CYMBAL, SPLASH_CYMBAL
};
// perc single
public final static int[] PERCS = {
TAMBOURINE, COWBELL, VIBRASLAP, CABASA, MARACAS, CLAVES
};
// perc multi
public final static int[] MULTI_PERCS = {
HI_BONGO, LOW_BONGO,
MUTE_HI_CONGA, OPEN_HI_CONGA, LOW_CONGA,
HI_TIMBALE, LOW_TIMBALE,
HI_AGOGO, LOW_AGOGO,
SHORT_WHISTLE, LONG_WHISTLE,
SHORT_GUIRO, LONG_GUIRO,
HI_WOOD_BLOCK, LOW_WOOD_BLOCK,
MUTE_CUICA, OPEN_CUICA,
MUTE_TRIANGLE, OPEN_TRIANGLE
};
static public int drumFamilyCount() { return 7; }
static public String drumFamilyName(int f) {
switch ( f ) {
case 0: return "Cymbals";
case 1: return "Hi Hats";
case 2: return "Snares";
case 3: return "Toms";
case 4: return "Bass Drums";
case 5: return "Percussion";
case 6: return "Multi Percussion";
default: return "?";
}
}
static public int[] drumFamily(int f) {
switch ( f ) {
case 0: return CYMBALS;
case 1: return HATS;
case 2: return SNARES;
case 3: return TOMS;
case 4: return BASS_DRUMS;
case 5: return PERCS;
case 6: return MULTI_PERCS;
default: return null;
}
}
static public String drumProgramName(int program) {
switch (program) {
case 0: return "Standard Kit";
case 1: return "Standard Kit 1";
case 2: return "Standard Kit 2";
case 3: return "Standard Kit 3";
case 4: return "Standard Kit 4";
case 5: return "Standard Kit 5";
case 6: return "Standard Kit 6";
case 7: return "Standard Kit 7";
case 8: return "Room Kit";
case 9: return "Room Kit 1";
case 10: return "Room Kit 2";
case 11: return "Room Kit 3";
case 12: return "Room Kit 4";
case 13: return "Room Kit 5";
case 14: return "Room Kit 6";
case 15: return "Room Kit 7";
case 16: return "Power Kit";
case 17: return "Power Kit 1";
case 18: return "Power Kit 2";
case 24: return "Electronic Kit";
case 25: return "TR-808 Kit";
case 32: return "Jazz Kit";
case 33: return "Jazz Kit 1";
case 34: return "Jazz Kit 2";
case 35: return "Jazz Kit 3";
case 36: return "Jazz Kit 4";
case 40: return "Brush Kit";
case 41: return "Brush Kit 1";
case 42: return "Brush Kit 2";
case 48: return "Orchestra Kit";
case 56: return "Sound FX Kit";
case 127: return "CM-64/CM-32L Kit";
}
return String.valueOf(program);
}
static public String drumName(int drum) {
if (drum < HIGH_Q || drum > OPEN_SURDO) {
return Pitch.name(drum);
}
switch (drum) {
// Level 2
case HIGH_Q:
return "High Q";
case SLAP:
return "Slap";
case SCRATCH:
return "Scratch";
case SCRATCH_2:
return "Scratch 2";
case STICKS:
return "Sticks";
case SQUARE:
return "Square";
case METRONOME:
return "Metronome";
case METRONOME_2:
return "Metronome 2";
// Level 1
case ACOUSTIC_BASS_DRUM:
return "Acoustic Bass Drum";
case BASS_DRUM_1:
return "Bass Drum 1";
case SIDE_STICK:
return "Side Stick";
case ACOUSTIC_SNARE:
return "Acoustic Snare";
case HAND_CLAP:
return "Hand Clap";
case ELECTRIC_SNARE:
return "Electric Snare";
case LOW_FLOOR_TOM:
return "Low Floor Tom";
case CLOSED_HI_HAT:
return "Closed Hi-Hat";
case HI_FLOOR_TOM:
return "High Floor Tom";
case PEDAL_HI_HAT:
return "Pedal Hi-Hat";
case LOW_TOM:
return "Low Tom";
case OPEN_HI_HAT:
return "Open Hi-Hat";
case LOW_MID_TOM:
return "Low-Mid Tom";
case HI_MID_TOM:
return "Hi-Mid Tom";
case CRASH_CYMBAL_1:
return "Crash Cymbal 1";
case HI_TOM:
return "High Tom";
case RIDE_CYMBAL_1:
return "Ride Cymbal 1";
case CHINESE_CYMBAL:
return "Chinese Cymbal";
case RIDE_BELL:
return "Ride Bell";
case TAMBOURINE:
return "Tambourine";
case SPLASH_CYMBAL:
return "Splash Cymbal";
case COWBELL:
return "Cowbell";
case CRASH_CYMBAL_2:
return "Crash Cymbal 2";
case VIBRASLAP:
return "Vibraslap";
case RIDE_CYMBAL_2:
return "Ride Cymbal 2";
case HI_BONGO:
return "Hi Bongo";
case LOW_BONGO:
return "Low Bongo";
case MUTE_HI_CONGA:
return "Mute Hi Conga";
case OPEN_HI_CONGA:
return "Open Hi Conga";
case LOW_CONGA:
return "Low Conga";
case HI_TIMBALE:
return "High Timbale";
case LOW_TIMBALE:
return "Low Timbale";
case HI_AGOGO:
return "High Agogo";
case LOW_AGOGO:
return "Low Agogo";
case CABASA:
return "Cabasa";
case MARACAS:
return "Maracas";
case SHORT_WHISTLE:
return "Short Whistle";
case LONG_WHISTLE:
return "Long Whistle";
case SHORT_GUIRO:
return "Short Guiro";
case LONG_GUIRO:
return "Long Guiro";
case CLAVES:
return "Claves";
case HI_WOOD_BLOCK:
return "Hi Wood Block";
case LOW_WOOD_BLOCK:
return "Low Wood Block";
case MUTE_CUICA:
return "Mute Cuica";
case OPEN_CUICA:
return "Open Cuica";
case MUTE_TRIANGLE:
return "Mute Triangle";
case OPEN_TRIANGLE:
return "Open Triangle";
// Level 2
case SHAKER:
return "Shaker";
case JINGLE_BELL:
return "Jingle Bell";
case BELL_TREE:
return "Bell Tree";
case CASTANETS:
return "Castanets";
case MUTE_SURDO:
return "Mute Surdo";
case OPEN_SURDO:
return "Open Surdo";
}
return drum + "?";
}
}
| gpl-2.0 |
Norkart/NK-VirtualGlobe | Xj3D/src/java/org/web3d/vrml/renderer/common/nodes/surface/BaseImage2D.java | 22301 | /*****************************************************************************
* Web3d.org Copyright (c) 2001
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.web3d.vrml.renderer.common.nodes.surface;
// Standard imports
import java.awt.Rectangle;
import java.util.HashMap;
// Application specific imports
import org.web3d.vrml.lang.*;
import org.web3d.vrml.nodes.*;
/**
* Common implementation of a Image2D node.
* <p>
*
* @author Justin Couch
* @version $Revision: 1.12 $
*/
public abstract class BaseImage2D extends BaseSurfaceChildNode
implements VRMLSurfaceChildNodeType {
/** Secondary type constant */
private static final int[] SECONDARY_TYPE =
{ TypeConstants.SensorNodeType, TypeConstants.TimeDependentNodeType };
// Field index constants
/** The field index for fixedSize. */
protected static final int FIELD_FIXED_SIZE = LAST_SURFACE_CHILD_INDEX + 1;
/** The field index for texture. */
protected static final int FIELD_TEXTURE = LAST_SURFACE_CHILD_INDEX + 2;
/** The field index for isActive. */
protected static final int FIELD_ISACTIVE = LAST_SURFACE_CHILD_INDEX + 3;
/** The field index for enabled. */
protected static final int FIELD_ENABLED = LAST_SURFACE_CHILD_INDEX + 4;
/** The field index for isOvery. */
protected static final int FIELD_ISOVER = LAST_SURFACE_CHILD_INDEX + 5;
/** The field index for touchTime. */
protected static final int FIELD_TOUCHTIME = LAST_SURFACE_CHILD_INDEX + 6;
/** The field index for trackPoint_changed. */
protected static final int FIELD_TRACKPOINT_CHANGED =
LAST_SURFACE_CHILD_INDEX + 7;
/** The field index for windowRelative. */
protected static final int FIELD_WINDOW_RELATIVE =
LAST_SURFACE_CHILD_INDEX + 8;
/** The last field index used by this class */
protected static final int LAST_IMAGE2D_INDEX = FIELD_WINDOW_RELATIVE;
/** Number of fields constant */
protected static final int NUM_FIELDS = LAST_IMAGE2D_INDEX + 1;
/** Message for when the proto is not a Appearance */
protected static final String TEXTURE_PROTO_MSG =
"Proto does not describe a Texture2D object";
/** Message for when the node in setValue() is not a Appearance */
protected static final String TEXTURE_NODE_MSG =
"Node does not describe a Texture2D object";
/** Array of VRMLFieldDeclarations */
private static VRMLFieldDeclaration[] fieldDecl;
/** Hashmap between a field name and its index */
private static HashMap fieldMap;
/** Listing of field indexes that have nodes */
private static int[] nodeFields;
// The VRML field values
/** The value of the fixedSize field. */
protected boolean vfFixedSize;
/** The value of the texture exposedField. */
protected VRMLTexture2DNodeType vfTexture;
/** Proto version of the texture */
protected VRMLProtoInstance pTexture;
/** The value of the isActive eventOut */
protected boolean vfIsActive;
/** The value of the windowRelative field */
protected boolean vfWindowRelative;
/** The value of the enabled exposedField */
protected boolean vfEnabled;
/** The value of the isOver eventOut */
protected boolean vfIsOver;
/** The value of the touchTime eventOut */
protected double vfTouchTime;
/** The value of th trackPoint_changed eventOut */
protected float[] vfTrackPoint;
/**
* Static constructor to build the field representations of this node
* once for all users.
*/
static {
nodeFields = new int[] { FIELD_TEXTURE, FIELD_METADATA };
fieldDecl = new VRMLFieldDeclaration[NUM_FIELDS];
fieldMap = new HashMap(NUM_FIELDS * 3);
fieldDecl[FIELD_METADATA] =
new VRMLFieldDeclaration(FieldConstants.EXPOSEDFIELD,
"SFNode",
"metadata");
fieldDecl[FIELD_VISIBLE] =
new VRMLFieldDeclaration(FieldConstants.EXPOSEDFIELD,
"SFBool",
"visible");
fieldDecl[FIELD_BBOX_SIZE] =
new VRMLFieldDeclaration(FieldConstants.FIELD,
"SFVec2f",
"bboxSize");
fieldDecl[FIELD_FIXED_SIZE] =
new VRMLFieldDeclaration(FieldConstants.FIELD,
"SFBool",
"fixedSize");
fieldDecl[FIELD_WINDOW_RELATIVE] =
new VRMLFieldDeclaration(FieldConstants.FIELD,
"SFBool",
"windowRelative");
fieldDecl[FIELD_TEXTURE] =
new VRMLFieldDeclaration(FieldConstants.EXPOSEDFIELD,
"SFNode",
"texture");
fieldDecl[FIELD_ENABLED] =
new VRMLFieldDeclaration(FieldConstants.EXPOSEDFIELD,
"SFBool",
"enabled");
fieldDecl[FIELD_ISACTIVE] =
new VRMLFieldDeclaration(FieldConstants.EVENTOUT,
"SFBool",
"isActive");
fieldDecl[FIELD_ISOVER] =
new VRMLFieldDeclaration(FieldConstants.EVENTOUT,
"SFBool",
"isOver");
fieldDecl[FIELD_TOUCHTIME] =
new VRMLFieldDeclaration(FieldConstants.EVENTOUT,
"SFTime",
"touchTime");
fieldDecl[FIELD_TRACKPOINT_CHANGED] =
new VRMLFieldDeclaration(FieldConstants.EVENTOUT,
"SFVec2f",
"trackPoint_changed");
Integer idx = new Integer(FIELD_METADATA);
fieldMap.put("metadata", idx);
fieldMap.put("set_metadata", idx);
fieldMap.put("metadata_changed", idx);
idx = new Integer(FIELD_VISIBLE);
fieldMap.put("visible", idx);
fieldMap.put("set_visible", idx);
fieldMap.put("visible_changed", idx);
idx = new Integer(FIELD_TEXTURE);
fieldMap.put("texture", idx);
fieldMap.put("set_texture", idx);
fieldMap.put("texture_changed", idx);
idx = new Integer(FIELD_ENABLED);
fieldMap.put("enabled", idx);
fieldMap.put("set_enabled", idx);
fieldMap.put("enabled_changed", idx);
fieldMap.put("bboxSize", new Integer(FIELD_BBOX_SIZE));
fieldMap.put("fixedSize", new Integer(FIELD_FIXED_SIZE));
fieldMap.put("windowRelative", new Integer(FIELD_WINDOW_RELATIVE));
fieldMap.put("isActive", new Integer(FIELD_ISACTIVE));
fieldMap.put("isOver", new Integer(FIELD_ISOVER));
fieldMap.put("touchTime", new Integer(FIELD_TOUCHTIME));
fieldMap.put("trackPoint_changed",
new Integer(FIELD_TRACKPOINT_CHANGED));
}
/**
* Construct a new default Overlay object
*/
protected BaseImage2D() {
super("Image2D");
hasChanged = new boolean[NUM_FIELDS];
// Set the default values for the fields
vfFixedSize = true;
vfIsActive = false;
vfEnabled = true;
vfIsOver = false;
vfTouchTime = 0;
vfWindowRelative = false;
vfTrackPoint = new float[2];
}
/**
* Construct a new instance of this node based on the details from the
* given node. If the node is not the same type, an exception will be
* thrown.
*
* @param node The node to copy
* @throws IllegalArgumentException The node is not the same type
*/
protected BaseImage2D(VRMLNodeType node) {
this();
checkNodeType(node);
copy((VRMLSurfaceChildNodeType)node);
try {
int index = node.getFieldIndex("fixedSize");
VRMLFieldData data = node.getFieldValue(index);
vfFixedSize = data.booleanValue;
index = node.getFieldIndex("enabled");
data = node.getFieldValue(index);
vfEnabled = data.booleanValue;
index = node.getFieldIndex("windowRelative");
data = node.getFieldValue(index);
vfWindowRelative = data.booleanValue;
} catch(VRMLException ve) {
throw new IllegalArgumentException(ve.getMessage());
}
}
//----------------------------------------------------------
// Methods required by the VRMLSensorNodeType interface.
//----------------------------------------------------------
/**
* Accessor method to set a new value for the enabled field
*
* @param state The new enabled state
*/
public void setEnabled(boolean state) {
if(state != vfEnabled) {
vfEnabled = state;
hasChanged[FIELD_ENABLED] = true;
fireFieldChanged(FIELD_ENABLED);
}
}
/**
* Accessor method to get current value of the enabled field.
* The default value is <code>true</code>.
*
* @return The value of the enabled field
*/
public boolean getEnabled() {
return vfEnabled;
}
/**
* Accessor method to get current value of the isActive field.
*
* @return The current value of isActive
*/
public boolean getIsActive () {
return vfIsActive;
}
//----------------------------------------------------------
// Methods required by the VRMLNodeType interface.
//----------------------------------------------------------
/**
* Get the index of the given field name. If the name does not exist for
* this node then return a value of -1.
*
* @param fieldName The name of the field we want the index from
* @return The index of the field name or -1
*/
public int getFieldIndex(String fieldName) {
Integer index = (Integer)fieldMap.get(fieldName);
return (index == null) ? -1 : index.intValue();
}
/**
* Get the list of indices that correspond to fields that contain nodes
* ie MFNode and SFNode). Used for blind scene graph traversal without
* needing to spend time querying for all fields etc. If a node does
* not have any fields that contain nodes, this shall return null. The
* field list covers all field types, regardless of whether they are
* readable or not at the VRML-level.
*
* @return The list of field indices that correspond to SF/MFnode fields
* or null if none
*/
public int[] getNodeFieldIndices() {
return nodeFields;
}
/**
* Notification that the construction phase of this node has finished.
* If the node would like to do any internal processing, such as setting
* up geometry, then go for it now.
*/
public void setupFinished() {
if(!inSetup)
return;
super.setupFinished();
if (pTexture != null)
pTexture.setupFinished();
if (vfTexture != null)
vfTexture.setupFinished();
}
/**
* Get the declaration of the field at the given index. This allows for
* reverse lookup if needed. If the field does not exist, this will give
* a value of null.
*
* @param index The index of the field to get information
* @return A representation of this field's information
*/
public VRMLFieldDeclaration getFieldDeclaration(int index) {
if(index < 0 || index > LAST_IMAGE2D_INDEX)
return null;
return fieldDecl[index];
}
/**
* Get the number of fields.
*
* @param The number of fields.
*/
public int getNumFields() {
return fieldDecl.length;
}
/**
* Get the secondary type of this node. Replaces the instanceof mechanism
* for use in switch statements.
*
* @return The secondary type
*/
public int[] getSecondaryType() {
return SECONDARY_TYPE;
}
/**
* Get the value of a field. If the field is a primitive type, it will
* return a class representing the value. For arrays or nodes it will
* return the instance directly.
*
* @param index The index of the field to change.
* @return The class representing the field value
* @throws InvalidFieldException The field index is not known
*/
public VRMLFieldData getFieldValue(int index) throws InvalidFieldException {
VRMLFieldData fieldData = fieldLocalData.get();
switch(index) {
case FIELD_FIXED_SIZE:
fieldData.clear();
fieldData.booleanValue = vfFixedSize;
fieldData.dataType = VRMLFieldData.BOOLEAN_DATA;
break;
case FIELD_WINDOW_RELATIVE:
fieldData.clear();
fieldData.booleanValue = vfWindowRelative;
fieldData.dataType = VRMLFieldData.BOOLEAN_DATA;
break;
case FIELD_ENABLED:
fieldData.clear();
fieldData.booleanValue = vfEnabled;
fieldData.dataType = VRMLFieldData.BOOLEAN_DATA;
break;
case FIELD_ISACTIVE:
fieldData.clear();
fieldData.booleanValue = vfIsActive;
fieldData.dataType = VRMLFieldData.BOOLEAN_DATA;
break;
case FIELD_ISOVER:
fieldData.clear();
fieldData.booleanValue = vfIsOver;
fieldData.dataType = VRMLFieldData.BOOLEAN_DATA;
break;
case FIELD_TOUCHTIME:
fieldData.clear();
fieldData.doubleValue = vfTouchTime;
fieldData.dataType = VRMLFieldData.DOUBLE_DATA;
break;
case FIELD_TRACKPOINT_CHANGED:
fieldData.clear();
fieldData.floatArrayValue = vfTrackPoint;
fieldData.numElements = 1;
fieldData.dataType = VRMLFieldData.FLOAT_ARRAY_DATA;
break;
case FIELD_TEXTURE:
fieldData.clear();
if(pTexture == null)
fieldData.nodeValue = vfTexture;
else
fieldData.nodeValue = pTexture;
fieldData.dataType = VRMLFieldData.NODE_DATA;
break;
default:
super.getFieldValue(index);
}
return fieldData;
}
/**
* Send a routed value from this node to the given destination node. The
* route should use the appropriate setValue() method of the destination
* node. It should not attempt to cast the node up to a higher level.
* Routing should also follow the standard rules for the loop breaking and
* other appropriate rules for the specification.
*
* @param time The time that this route occurred (not necessarily epoch
* time. Should be treated as a relative value only)
* @param srcIndex The index of the field in this node that the value
* should be sent from
* @param destNode The node reference that we will be sending the value to
* @param destIndex The index of the field in the destination node that
* the value should be sent to.
*/
public void sendRoute(double time,
int srcIndex,
VRMLNodeType destNode,
int destIndex) {
// Simple impl for now. ignores time and looping
try {
switch(srcIndex) {
case FIELD_FIXED_SIZE:
destNode.setValue(destIndex, vfFixedSize);
break;
case FIELD_WINDOW_RELATIVE:
destNode.setValue(destIndex, vfWindowRelative);
break;
case FIELD_ENABLED:
destNode.setValue(destIndex, vfEnabled);
break;
case FIELD_ISACTIVE:
destNode.setValue(destIndex, vfIsActive);
break;
case FIELD_ISOVER:
destNode.setValue(destIndex, vfIsOver);
break;
case FIELD_TOUCHTIME:
destNode.setValue(destIndex, vfTouchTime);
break;
case FIELD_TRACKPOINT_CHANGED:
destNode.setValue(destIndex, vfTrackPoint, 2);
break;
default:
super.sendRoute(time, srcIndex, destNode, destIndex);
}
} catch(InvalidFieldException ife) {
System.err.println("sendRoute: No field! " + ife.getFieldName());
} catch(InvalidFieldValueException ifve) {
System.err.println("sendRoute: Invalid field value: " +
ifve.getMessage());
}
}
/**
* Set the value of the field from the raw string. This requires the
* implementation to parse the string in the given format for the field
* type. If the field type does not match the requirements for that index
* then an exception will be thrown. If the destination field is a string,
* then the leading and trailing quote characters will be stripped before
* calling this method.
*
* @param index The index of destination field to set
* @param value The raw value string to be parsed
* @throws InvalidFieldFormatException The string was not in a correct form
* for this field.
*/
public void setValue(int index, boolean value)
throws InvalidFieldFormatException, InvalidFieldValueException,
InvalidFieldException {
switch(index) {
case FIELD_FIXED_SIZE:
if(!inSetup)
throw new InvalidFieldAccessException(
"fixedSize is an initializeOnly field");
vfFixedSize = value;
break;
case FIELD_WINDOW_RELATIVE:
if(!inSetup)
throw new InvalidFieldAccessException(
"windowRelative is an initializeOnly field");
vfWindowRelative = value;
break;
case FIELD_ENABLED:
vfEnabled = value;
if(!inSetup) {
hasChanged[FIELD_ENABLED] = true;
fireFieldChanged(FIELD_ENABLED);
}
break;
default:
super.setValue(index, value);
}
}
/**
* Set the value of the field at the given index as an array of nodes.
* This would be used to set MFNode field types.
*
* @param index The index of destination field to set
* @param value The new value to use for the node
* @throws InvalidFieldException The field index is not know
*/
public void setValue(int index, VRMLNodeType child)
throws InvalidFieldException {
switch(index) {
case FIELD_TEXTURE:
setTextureNode(child);
if(!inSetup) {
hasChanged[FIELD_TEXTURE] = true;
fireFieldChanged(FIELD_TEXTURE);
}
break;
default:
super.setValue(index, child);
}
}
//----------------------------------------------------------
// Local Methods
//----------------------------------------------------------
/**
* Called to set the texture node to be used. May be overridden by the
* derived class, but must also call this version first to ensure
* everything is valid node types and the fields correctly set.
*
* @param texture The new texture node instance to use
* @throws InvalidFieldValueException The node is not the required type
*/
protected void setTextureNode(VRMLNodeType texture)
throws InvalidFieldValueException {
if(texture == null) {
vfTexture = null;
} else {
VRMLNodeType node;
if(texture instanceof VRMLProtoInstance) {
pTexture = (VRMLProtoInstance)texture;
node = pTexture.getImplementationNode();
if(!(node instanceof VRMLTexture2DNodeType)) {
throw new InvalidFieldValueException(TEXTURE_PROTO_MSG);
}
} else if(texture != null &&
(!(texture instanceof VRMLTexture2DNodeType))) {
throw new InvalidFieldValueException(TEXTURE_NODE_MSG);
} else {
pTexture = null;
node = texture;
}
vfTexture = (VRMLTexture2DNodeType)node;
}
if (!inSetup) {
hasChanged[FIELD_TEXTURE] = true;
fireFieldChanged(FIELD_TEXTURE);
}
}
/**
* Send notification that the track point has changed. The values passed
* should be in surface coordinates and this will adjust as necessary for
* the windowRelative field setting when generating the eventOut. Assumes
* standard window coordinates with X across and Y down.
*
* @param x The x position of the mouse
* @param h The y position of the mouse
*/
protected void setTrackPoint(int x, int y) {
if(!vfWindowRelative) {
vfTrackPoint[0] = x;
vfTrackPoint[1] = y;
} else {
vfTrackPoint[0] = x - screenLocation[0];
vfTrackPoint[1] = y - screenLocation[1];
}
hasChanged[FIELD_TRACKPOINT_CHANGED] = true;
fireFieldChanged(FIELD_TRACKPOINT_CHANGED);
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/inlining/info/ExactInlineInfo.java | 3520 | /*
* Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.phases.common.inlining.info;
import org.graalvm.collections.EconomicSet;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.spi.CoreProviders;
import org.graalvm.compiler.phases.common.inlining.info.elem.Inlineable;
import org.graalvm.compiler.phases.util.Providers;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* Represents an inlining opportunity where the compiler can statically determine a monomorphic
* target method and therefore is able to determine the called method exactly.
*/
public class ExactInlineInfo extends AbstractInlineInfo {
protected final ResolvedJavaMethod concrete;
private Inlineable inlineableElement;
private boolean suppressNullCheck;
public ExactInlineInfo(Invoke invoke, ResolvedJavaMethod concrete) {
super(invoke);
this.concrete = concrete;
assert concrete != null;
}
public void suppressNullCheck() {
suppressNullCheck = true;
}
@Override
public EconomicSet<Node> inline(CoreProviders providers, String reason) {
return inline(invoke, concrete, inlineableElement, !suppressNullCheck, reason);
}
@Override
public void tryToDevirtualizeInvoke(Providers providers) {
// nothing todo, can already be bound statically
}
@Override
public int numberOfMethods() {
return 1;
}
@Override
public ResolvedJavaMethod methodAt(int index) {
assert index == 0;
return concrete;
}
@Override
public double probabilityAt(int index) {
assert index == 0;
return 1.0;
}
@Override
public double relevanceAt(int index) {
assert index == 0;
return 1.0;
}
@Override
public String toString() {
return "exact " + concrete.format("%H.%n(%p):%r");
}
@Override
public Inlineable inlineableElementAt(int index) {
assert index == 0;
return inlineableElement;
}
@Override
public void setInlinableElement(int index, Inlineable inlineableElement) {
assert index == 0;
this.inlineableElement = inlineableElement;
}
@Override
public boolean shouldInline() {
return concrete.shouldBeInlined();
}
}
| gpl-2.0 |
hs94/FoodFinderApp | src/cs499/examples/semesterproject/AndroidFoodBankOwnerServlet.java | 18694 | package cs499.examples.semesterproject;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class AndroidFoodBankOwnerServlet extends HttpServlet
{
boolean debug = false;
private String sqlliteDbUrl;
@Override
public void init(ServletConfig config) throws ServletException
{
sqlliteDbUrl = config.getInitParameter("sqlliteDbUrl");
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType ("TEXT/HTML");
PrintWriter out = res.getWriter ();
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1> </body>");
out.println("</html");
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (!debug)
res.setContentType("application/json");
else if (debug)
res.setContentType ("TEXT/HTML");
PrintWriter out = res.getWriter ();
String action = req.getParameter("action");
if (debug)
out.println("doPost Action: " + action);
if (action.equals("registerfoodplace"))
registerFoodPlace(out, req, res);
else if (action.equals("enterorganization"))
{
registerOrganization(out,req,res);
}
else if (action.equals("searchplaces"))
{
searchPlaces (out,req,res);
}
else if (action.equals("authenticate"))
{
authenticateUser (out,req,res);
}
else if (action.equals("additems"))
{
addItemsToPlace (out,req,res);
}
else if (action.equals("searchitems"))
{
searchItems (out,req,res);
}
else if (action.equals("requestitems"))
{
requestItem (out,req,res);
}
else if (action.equals("viewrequests"))
{
viewRequests (out,req,res);
}
}
public void viewRequests (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
ResultSet rs = null;
//int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
System.out.println("ownername: " + req.getParameter("ownerName"));
query = "select sender, organization.name as org_name ,itemname from request, foodplace, organization where " +
"request.sender=organization.member and request.placename=foodplace.name and " +
"foodplace.ownername=" + "'" + req.getParameter("ownerName") + "'";
rs = s.executeQuery(query);
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (rs != null)
{
System.out.println("Creating JSON....");
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
}
else
{
out.println("Hey! Your resultset is null or empty");
out.flush();
}
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void requestItem (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Search Food Bank Data </h1>");
}
Statement s = null;
//ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
String[] selectedItems = null;
System.out.println("senderName: " + req.getParameter("senderName"));
System.out.println("placeName: " + req.getParameter("placeName"));
System.out.println("selectedItems: " + req.getParameter("selectedItems"));
if (req.getParameter("selectedItems") != null)
{
selectedItems = req.getParameter("selectedItems").split(",");
}
if (selectedItems != null && selectedItems.length > 0)
{
s = c.createStatement();
for (int i = 0; i < selectedItems.length; i ++)
{
query = "insert into request (sender, placename, itemname)"
+ " values (" + "'" + req.getParameter("senderName")
+ "'" + ", " + "'" + req.getParameter("placeName")
+ "'" + ", " + "'" + selectedItems[i]
+ "'" + ")";
queryExecuted = s.executeUpdate(query);
}
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Selected items inserted into db");
}
else
{
System.out.println("No selected items");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void searchItems (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Search Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
//int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
System.out.println(req.getParameter("placeName"));
s = c.createStatement();
query = "select * from items where foodplacename=" + "'" + req.getParameter("placeName")
+ "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (rs != null)
{
System.out.println("Creating JSON....");
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
}
else
{
out.println("Hey! Your resultset is null or empty");
out.flush();
}
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void addItemsToPlace(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
query = "select * from foodplace where ownername=" + "'" + req.getParameter("ownername") + "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (debug)
{
out.println("username: " + req.getParameter("ownername") + "<br/>");
out.println("itemName: " + req.getParameter("itemName") + "<br/>");
out.println("itemQuantity: " + req.getParameter("itemQuantity") + "<br/>");
out.println("Restaurant name: " + rs.getString("name") + "<br/>");
}
query = "insert into items (foodplacename, itemtype, itemname) values ("
+ "'" + rs.getString("name") + "'" + ", " + req.getParameter("itemQuantity")
+ ", " + "'" + req.getParameter("itemName") + "'" + ")";
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void authenticateUser(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
query = "select * from foodappuser where username=" + "'" + req.getParameter("loginUser") + "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public JSONArray convertToJSON( ResultSet rs ) throws SQLException, JSONException
{
JSONArray json = new JSONArray();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
int numColumns = rsmd.getColumnCount();
JSONObject obj = new JSONObject();
for (int i=1; i<numColumns+1; i++)
{
String column_name = rsmd.getColumnName(i);
if(rsmd.getColumnType(i)==java.sql.Types.ARRAY){
obj.put(column_name, rs.getArray(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BOOLEAN){
obj.put(column_name, rs.getBoolean(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BLOB){
obj.put(column_name, rs.getBlob(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.DOUBLE){
obj.put(column_name, rs.getDouble(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.FLOAT){
obj.put(column_name, rs.getFloat(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.INTEGER){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.NVARCHAR){
obj.put(column_name, rs.getNString(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.VARCHAR){
obj.put(column_name, rs.getString(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.TINYINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.SMALLINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.DATE){
obj.put(column_name, rs.getDate(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.TIMESTAMP){
obj.put(column_name, rs.getTimestamp(column_name));
}
else{
obj.put(column_name, rs.getObject(column_name));
}
}
json.put(obj);
}
return json;
}
public void searchPlaces(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
if (req.getParameter("searchCity").trim().equals("") && !req.getParameter("searchZip").trim().equals(""))
query = "select * from foodplace where zip=" + req.getParameter("searchZip");
else if (!req.getParameter("searchCity").trim().equals("") && req.getParameter("searchZip").trim().equals(""))
query = "select * from foodplace where city=" + "'" + req.getParameter("searchCity") + "'";
else
{
query = "select * from foodplace where zip=" + req.getParameter("searchZip")
+ " and city=" + "'" + req.getParameter("searchCity") + "'";
}
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Connection getDBConnection()
{
Connection c = null;
try
{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("org.sqlite.JDBC");
String dbPath = "";
//c = DriverManager.getConnection("jdbc:sqlite:/Users/haaris/Workspace/SQLite/sqlite-shell-win32-x86-3080100/foodbank.db");
//c = DriverManager.getConnection("jdbc:sqlite:/Users/haaris/apache-tomcat-7.0.47/webapps/foodapp/foodbank.db");
c = DriverManager.getConnection(sqlliteDbUrl);
return c;
}
catch (Exception e)
{
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
}
public void registerFoodPlace(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
out.println("<html> <head> </head> <body> ");
out.println("Place name: " + req.getParameter("foodPlaceName"));
out.println("Place address: " + req.getParameter("foodPlaceStreetAddress")
+ ", " + req.getParameter("foodPlaceCity") + ","
+ req.getParameter("foodPlaceState") +
req.getParameter("foodPlaceZip"));
System.out.println("Place name: " + req.getParameter("foodPlaceName"));
System.out.println("Place address: " + req.getParameter("foodPlaceStreetAddress")
+ ", " + req.getParameter("foodPlaceCity") + ","
+ req.getParameter("foodPlaceState") +
req.getParameter("foodPlaceZip"));
try
{
//c = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.8:1521/XE", "system", "admin");
//c = DriverManager.getConnection("jdbc:oracle:thin:@10.159.226.169:1521/XE", "system", "admin");
s = c.createStatement();
query = "insert into foodappuser (username, password, usertype) values (" + "'"+ req.getParameter("foodPlaceOwnerName") + "'"
+ ", " + "'" + req.getParameter("foodPlaceOwnerPassword") + "'" + ", 'owner')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
query = "insert into foodplace (ownername, name, streetaddress, city, state, zip, phonenumber)"
+ "values (" +"'"+ req.getParameter("foodPlaceOwnerName") + "'"
+ ", " + "'" + req.getParameter("foodPlaceName") + "'" +", '" + req.getParameter("foodPlaceStreetAddress") + "', '"
+ req.getParameter("foodPlaceCity")
+ "'" + ", '" + req.getParameter("foodPlaceState") + "'" + ", " + req.getParameter("foodPlaceZip") + ", "
+ req.getParameter("foodPlacePhone") + ")";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (SQLException e)
{
out.println("Exception: could not insert data" + e.getMessage());
out.println("</body> </html> ");
e.printStackTrace();
return;
}
}
public void registerOrganization(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
String query = "";
int queryExecuted = 0;
Connection c = getDBConnection();
if (c == null)
{
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
//c = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.8:1521/XE", "system", "admin");
//c = DriverManager.getConnection("jdbc:oracle:thin:@10.159.226.169:1521/XE", "system", "admin");
s = c.createStatement();
query = "insert into foodappuser (username, password, usertype) values (" + "'"+ req.getParameter("memberName") + "'"
+ ", " + "'" + req.getParameter("memberPassword") + "'" + ", 'organization')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
query = "insert into organization (member, name) values (" + "'"
+req.getParameter("memberName")+"', " + "'" +
req.getParameter("name")+"')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (SQLException e)
{
out.println("Exception: could not insert data" + e.getMessage());
out.println("</body> </html> ");
e.printStackTrace();
return;
}
}
} | gpl-2.0 |
MichaelChansn/RemoteControlSystem2.0_AndroidClient | src/com/ks/net/UDPScanThread.java | 2601 | package com.ks.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import com.ks.activitys.IndexActivity.IndexHandler;
import com.ks.net.enums.MessageEnums;
public class UDPScanThread extends Thread {
private static final int UDPPORT = 9999;
private ArrayList<String> servers;
private DatagramSocket dgSocket = null;
private IndexHandler handler;
public UDPScanThread(ArrayList<String> servers, IndexHandler handler) {
this.servers = servers;
this.handler = handler;
}
public void stopUDP() {
this.interrupt();
if (dgSocket != null) {
dgSocket.close();
dgSocket = null;
}
}
@Override
public void run() {
super.run();
try {
dgSocket = new DatagramSocket();
dgSocket.setSoTimeout(500);
byte b[] = (MessageEnums.UDPSCANMESSAGE + MessageEnums.NETSEPARATOR + android.os.Build.BRAND + "_"
+ android.os.Build.MODEL).getBytes();
DatagramPacket dgPacket = null;
dgPacket = new DatagramPacket(b, b.length, InetAddress.getByName("255.255.255.255"), UDPPORT);
dgSocket.send(dgPacket);
} catch (IOException e3) {
handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANFAIL.getValue());
e3.printStackTrace();
if (dgSocket != null)
dgSocket.close();
return;
}
long start = System.nanoTime();
/** scan for 5 seconds */
while (!isInterrupted() && (System.nanoTime() - start) / 1000000 < 1500) {
byte data[] = new byte[512];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
dgSocket.receive(packet);
String rec = new String(packet.getData(), packet.getOffset(), packet.getLength());
System.out.println(rec);
String[] msgGet = rec.split(MessageEnums.NETSEPARATOR);
if (msgGet != null && msgGet.length == 3 && msgGet[0].equalsIgnoreCase(MessageEnums.UDPSCANRETURN)) {
if (msgGet[1].trim().length() == 0) {
msgGet[1] = "Unknown";
}
String server = msgGet[1] + MessageEnums.UDPSEPARATOR + packet.getAddress().toString().substring(1)
+ ":" + msgGet[2];
servers.add(server);
}
} catch (SocketTimeoutException ex) {
ex.printStackTrace();
continue;
} catch (IOException e) {
e.printStackTrace();
//handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANFAIL.getValue());
if (dgSocket != null)
dgSocket.close();
return;
}
}
if (dgSocket != null) {
dgSocket.close();
}
if (!isInterrupted()) {
handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANOK.getValue());
}
}
}
| gpl-2.0 |
eurra/hmod-domain-mkp | src/hmod/domain/mkp/scripts/RemoveAndGreedyFillScript.java | 1721 |
package hmod.domain.mkp.scripts;
import flexbuilders.core.BuildException;
import flexbuilders.core.Buildable;
import flexbuilders.scripting.BuildScript;
import flexbuilders.tree.BranchBuilder;
import flexbuilders.tree.TreeHandler;
import static hmod.parser.builders.AlgorithmBuilders.*;
/**
*
* @author Enrique Urra C.
*/
public class RemoveAndGreedyFillScript extends BuildScript
{
private BranchBuilder callLoad, callMultiRemove, callGreedyFill, callSave;
private Buildable loadStart, multiRemoveStart, greedyFillStart, saveStart;
public RemoveAndGreedyFillScript(TreeHandler input) throws BuildException
{
super(input);
callLoad = branch(MKPIds.MKP_HEURISTIC_REMOVE_AND_GREEDY_FILL);
callMultiRemove = branch();
callGreedyFill = branch();
callSave = branch();
loadStart = ref(MKPIds.MKP_LOAD_SOLUTION);
multiRemoveStart = ref(MKPIds.MKP_OPERATION_MULTI_REMOVE);
greedyFillStart = ref(MKPIds.MKP_OPERATION_GREEDY_FILL);
saveStart = ref(MKPIds.MKP_SAVE_SOLUTION);
}
@Override
public void process() throws BuildException
{
callLoad.setBuildable(
subProcessStep().setNextStep(callMultiRemove).
setSubStep(loadStart)
);
callMultiRemove.setBuildable(
subProcessStep().setNextStep(callGreedyFill).
setSubStep(multiRemoveStart)
);
callGreedyFill.setBuildable(
subProcessStep().setNextStep(callSave).
setSubStep(greedyFillStart)
);
callSave.setBuildable(
subProcessStep().
setSubStep(saveStart)
);
}
}
| gpl-2.0 |
mchug/trasm | src/trasm/IdTable.java | 4205 | package trasm;
/**
* Таблица идентификаторов
*/
class IdTable extends AbstractTable {
/**
* Типы идентификаторов
*/
static enum IdType {
DB(1), DW(2), DD(4), LABEL(0);
private int size;
private IdType(int i) {
size = i;
}
/**
* Возвращает тип идентификатора в байтах(для DB,DW,DD)
*
* @return Тип идентификатора
*/
int getSize() {
return size;
}
}
/**
* Добавляет в таблицу новый элемент. Если элемент существует - записывает
* строчку как ошибочную.
*
* @param item Новый элемент
*/
void add(TableItem item) {
if (isExist(item.getName())) {
ErrorList.AddError();
} else {
super.add(item);
}
}
private static IdTable instance = null;
private IdTable() {
}
/**
* Возвращает единственный экземпляр таблицы идентификаторов
*
* @return Таблица идентификаторов
*/
static IdTable getInstance() {
if (instance == null) {
instance = new IdTable();
}
return instance;
}
/**
* Элемент таблицы идентификаторов
*/
static class IdInfo implements TableItem {
private final String name;
private final String segment;
private final int address;
private final IdType type;
/**
* Конструктор элемента таблицы идентификаторов
*
* @param name Имя нового элемента
* @param type Тип нового элемента
*/
public IdInfo(String name, IdType type) {
this.name = name;
this.segment = SegTable.getInstance().getCurrentSegment();
this.address = SegTable.getInstance().getCurrentAddress();
this.type = type;
}
/**
* Возвращает тип идентификатора
*
* @return Тип идентификатора
*/
public IdType getType() {
return type;
}
/**
* Возвращает смещение элемента
*
* @return Смещение элемента
*/
public int getAddress() {
return address;
}
/**
* Возвращает сегмент в котором объявлен элемент
*
* @return Сегмент элемента
*/
public String getSegment() {
return segment;
}
/**
* Возвращает имя элемента
*
* @return Имя элемента
*/
@Override
public String getName() {
return name;
}
/**
* Преобразовывает элемент в удобный для чтения вид
*
* @return Строка для печати
*/
@Override
public String toString() {
return String.format("%1$-8s %2$-8s %3$s:%4$s\n", name, type.toString(), segment, IOLib.toHex(address, 4));
}
}
/**
* Возвращает таблицу идентификторов в удобном для чтения виде
*
* @return Строка для печати
*/
@Override
public String toString() {
StringBuilder outStr;
outStr = new StringBuilder("Ім'я Тип Адреса\n");
for (TableItem tableItem : list) {
outStr = outStr.append(tableItem.toString());
}
return outStr.toString();
}
}
| gpl-2.0 |
rac021/blazegraph_1_5_3_cluster_2_nodes | bigdata-rdf/src/test/com/bigdata/rdf/sparql/ast/optimizers/TestASTFilterNormalizationOptimizer.java | 79136 | /**
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
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; version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on June 10, 2015
*/
package com.bigdata.rdf.sparql.ast.optimizers;
import java.util.ArrayList;
import java.util.List;
import org.openrdf.query.algebra.StatementPattern.Scope;
import com.bigdata.bop.IBindingSet;
import com.bigdata.bop.bindingSet.ListBindingSet;
import com.bigdata.rdf.internal.IV;
import com.bigdata.rdf.model.BigdataURI;
import com.bigdata.rdf.model.BigdataValue;
import com.bigdata.rdf.model.BigdataValueFactory;
import com.bigdata.rdf.sparql.ast.ASTContainer;
import com.bigdata.rdf.sparql.ast.AbstractASTEvaluationTestCase;
import com.bigdata.rdf.sparql.ast.ConstantNode;
import com.bigdata.rdf.sparql.ast.FilterNode;
import com.bigdata.rdf.sparql.ast.FunctionNode;
import com.bigdata.rdf.sparql.ast.FunctionRegistry;
import com.bigdata.rdf.sparql.ast.IQueryNode;
import com.bigdata.rdf.sparql.ast.IValueExpressionNode;
import com.bigdata.rdf.sparql.ast.JoinGroupNode;
import com.bigdata.rdf.sparql.ast.ProjectionNode;
import com.bigdata.rdf.sparql.ast.QueryHints;
import com.bigdata.rdf.sparql.ast.QueryNodeWithBindingSet;
import com.bigdata.rdf.sparql.ast.QueryRoot;
import com.bigdata.rdf.sparql.ast.QueryType;
import com.bigdata.rdf.sparql.ast.StatementPatternNode;
import com.bigdata.rdf.sparql.ast.StaticAnalysis;
import com.bigdata.rdf.sparql.ast.ValueExpressionNode;
import com.bigdata.rdf.sparql.ast.VarNode;
import com.bigdata.rdf.sparql.ast.eval.AST2BOpContext;
/**
* Test suite for the {@link ASTFilterNormalizationOptimizer} class and associated
* utility methods in {@link StaticAnalysis}.
*
* @author <a href="mailto:ms@metaphacts.com">Michael Schmidt</a>
*/
@SuppressWarnings({ "rawtypes" })
public class TestASTFilterNormalizationOptimizer extends AbstractASTEvaluationTestCase {
public TestASTFilterNormalizationOptimizer() {
}
public TestASTFilterNormalizationOptimizer(String name) {
super(name);
}
/**
* Test the {@link ASTFilterNormalizationOptimizer#extractToplevelConjuncts(
* com.bigdata.rdf.sparql.ast.IValueExpressionNode, List)} method.
*/
public void testExtractTopLevelConjunctsMethod() {
// conjunct 1
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
// conjunct 2
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode not1 = FunctionNode.NOT(bound2);
// conjunct 3
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode or1 =
FunctionNode.OR(FunctionNode.AND(bound3,bound4), bound5);
// conjunct 4
final FunctionNode bound6 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final FunctionNode toCheck =
FunctionNode.AND(bound1,
FunctionNode.AND(
not1, FunctionNode.AND(or1, bound6)));
final List<IValueExpressionNode> actual =
StaticAnalysis.extractToplevelConjuncts(
toCheck, new ArrayList<IValueExpressionNode>());
assertFalse(StaticAnalysis.isCNF(toCheck));
assertEquals(actual.size(), 4);
assertEquals(actual.get(0), bound1);
assertEquals(actual.get(1), not1);
assertEquals(actual.get(2), or1);
assertEquals(actual.get(3), bound6);
}
/**
* Test the {@link ASTFilterNormalizationOptimizer#constructFiltersForValueExpressionNode(
* IValueExpressionNode, List)} method.
*/
public void testConstructFiltersForValueExpressionNodeMethod() {
// conjunct 1
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode or1 =
FunctionNode.OR(FunctionNode.AND(bound3,bound4), bound5);
// conjunct 2
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode not1 = FunctionNode.NOT(bound2);
// conjunct 3
final FunctionNode bound6 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
// conjunct 4
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode base =
FunctionNode.AND(
FunctionNode.AND(
or1, FunctionNode.AND(not1, bound6)),bound1);
final ASTFilterNormalizationOptimizer filterOptimizer = new ASTFilterNormalizationOptimizer();
final List<FilterNode> filters =
filterOptimizer.constructFiltersForValueExpressionNode(
base, new ArrayList<FilterNode>());
assertFalse(StaticAnalysis.isCNF(base));
assertEquals(filters.size(), 4);
assertEquals(filters.get(0), new FilterNode(or1));
assertEquals(filters.get(1), new FilterNode(not1));
assertEquals(filters.get(2), new FilterNode(bound6));
assertEquals(filters.get(3), new FilterNode(bound1));
}
/**
* Test the {@link ASTFilterNormalizationOptimizer#toConjunctiveValueExpression(List)}
* method.
*/
public void testToConjunctiveValueExpressionMethod() {
// conjunct 1
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
// conjunct 2
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode not1 = FunctionNode.NOT(bound2);
// conjunct 3
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode or1 =
FunctionNode.OR(FunctionNode.AND(bound3,bound4), bound5);
// conjunct 4
final FunctionNode bound6 =
new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final List<IValueExpressionNode> baseConjuncts =
new ArrayList<IValueExpressionNode>();
baseConjuncts.add(bound1);
baseConjuncts.add(not1);
baseConjuncts.add(or1);
baseConjuncts.add(bound6);
final IValueExpressionNode expected =
FunctionNode.AND(
FunctionNode.AND(
FunctionNode.AND(bound1, not1),
or1),
bound6);
final IValueExpressionNode actual =
StaticAnalysis.toConjunctiveValueExpression(baseConjuncts);
assertFalse(StaticAnalysis.isCNF(actual));
assertEquals(expected, actual);
}
/**
* The FILTER
*
* <pre>
* SELECT ?s where { ?s ?p ?o . FILTER(?s=?o) }
* </pre>
*
* is not being modified.
*/
public void testFilterDecompositionNoOp() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
given.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
whereClause.addChild(
new FilterNode(
FunctionNode.EQ(new VarNode("s"), new VarNode("o"))));
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
expected.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
final FilterNode filterNode =
new FilterNode(
FunctionNode.EQ(new VarNode("s"), new VarNode("o")));
assertTrue(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* The FILTER
*
* <pre>
* SELECT ?s where { ?s ?p ?o . FILTER(?s=?o && ?s!=<http://www.test.com>) }
* </pre>
*
* is rewritten as
*
* <pre>
* SELECT ?s where { ?s ?p ?o . FILTER(?s=?o) . FILTER(?s!=<http://www.test.com>) }
* </pre>
*
*/
public void testSimpleConjunctiveFilter() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final BigdataValueFactory f = store.getValueFactory();
final BigdataURI testUri = f.createURI("http://www.test.com");
final IV test = makeIV(testUri);
final BigdataValue[] values = new BigdataValue[] { testUri };
store.getLexiconRelation()
.addTerms(values, values.length, false/* readOnly */);
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
final FilterNode filterNode =
new FilterNode(
FunctionNode.AND(
FunctionNode.EQ(new VarNode("s"), new VarNode("o")),
FunctionNode.NE(new VarNode("s"), new ConstantNode(test))));
assertTrue(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
whereClause.addChild(
new FilterNode(
FunctionNode.EQ(new VarNode("s"), new VarNode("o"))));
whereClause.addChild(
new FilterNode(
FunctionNode.NE(new VarNode("s"), new ConstantNode(test))));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* The FILTER
*
* <pre>
* SELECT ?s where { FILTER(NOT(?s<?o || BOUND(?o))) . OPTIONAL { ?s ?p ?o } }
* </pre>
*
* is rewritten as
*
* <pre>
* SELECT ?s where { OPTIONAL { ?s ?p ?o } . FILTER(?s>=?o) . FILTER(!BOUND(?s) }
* </pre>
*
*/
public void testSimpleDisjunctiveFilter() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.OR(
FunctionNode.LT(new VarNode("s"), new VarNode("o")),
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") }))));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
spn.setOptional(true);
whereClause.addChild(spn);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
spn.setOptional(true);
whereClause.addChild(spn);
whereClause.addChild(
new FilterNode(
FunctionNode.GE(new VarNode("s"), new VarNode("o"))));
whereClause.addChild(
new FilterNode(
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") }))));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test rewriting of negated leaves, such as !(?x=?y) -> ?x!=?y,
* !(?a<?b) -> ?a>=?b, etc. in
*/
public void testNegationLeafRewriting01() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final FunctionNode filterEq = FunctionNode.EQ(new VarNode("s"), new VarNode("o"));
final FunctionNode filterNeq = FunctionNode.NE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLe = FunctionNode.LE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLt = FunctionNode.LT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGe = FunctionNode.GE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGt = FunctionNode.GT(new VarNode("s"), new VarNode("o"));
final FunctionNode comb1 = FunctionNode.AND(filterEq, filterNeq);
final FunctionNode comb2 = FunctionNode.AND(filterLe, filterLt);
final FunctionNode comb3 = FunctionNode.AND(filterGt, filterGe);
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.AND(FunctionNode.AND(comb1, comb2),comb3)));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final FunctionNode filterEqInv = FunctionNode.NE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterNeqInv = FunctionNode.EQ(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLeInv = FunctionNode.GT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLtInv = FunctionNode.GE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGeInv = FunctionNode.LT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGtInv = FunctionNode.LE(new VarNode("s"), new VarNode("o"));
final FunctionNode comb1 = FunctionNode.OR(filterEqInv, filterNeqInv);
final FunctionNode comb2 = FunctionNode.OR(filterLeInv, filterLtInv);
final FunctionNode comb3 = FunctionNode.OR(filterGtInv, filterGeInv);
final FilterNode filterNode =
new FilterNode(
FunctionNode.OR(FunctionNode.OR(comb1, comb2),comb3));
assertTrue(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test rewriting of negated leaves, such as !(?x=?y) -> ?x!=?y,
* !(?a<?b) -> ?a>=?b, etc. (differs from v01 in tree shape).
*/
public void testNegationLeafRewriting02() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final FunctionNode filterEq = FunctionNode.EQ(new VarNode("s"), new VarNode("o"));
final FunctionNode filterNeq = FunctionNode.NE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLe = FunctionNode.LE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLt = FunctionNode.LT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGe = FunctionNode.GE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGt = FunctionNode.GT(new VarNode("s"), new VarNode("o"));
final FunctionNode comb1 = FunctionNode.AND(filterEq, filterNeq);
final FunctionNode comb2 = FunctionNode.AND(filterLe, filterLt);
final FunctionNode comb3 = FunctionNode.AND(filterGt, filterGe);
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.AND(comb1, FunctionNode.AND(comb2,comb3))));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final FunctionNode filterEqInv = FunctionNode.NE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterNeqInv = FunctionNode.EQ(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLeInv = FunctionNode.GT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterLtInv = FunctionNode.GE(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGeInv = FunctionNode.LT(new VarNode("s"), new VarNode("o"));
final FunctionNode filterGtInv = FunctionNode.LE(new VarNode("s"), new VarNode("o"));
final FunctionNode comb1 = FunctionNode.OR(filterEqInv, filterNeqInv);
final FunctionNode comb2 = FunctionNode.OR(filterLeInv, filterLtInv);
final FunctionNode comb3 = FunctionNode.OR(filterGtInv, filterGeInv);
final FilterNode filterNode =
new FilterNode(
FunctionNode.OR(comb1, FunctionNode.OR(comb2,comb3)));
assertTrue(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test level three pushing of negation.
*/
public void testNestedNegationRewriting() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final FunctionNode filterANot1 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") }));
final FunctionNode filterANot2 = FunctionNode.NOT(filterANot1);
final FunctionNode filterANot3 = FunctionNode.NOT(filterANot2);
final FunctionNode filterBNot1 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.EQ, null,
new ValueExpressionNode[] { new VarNode("s"), new VarNode("o") }));
final FunctionNode filterBNot2 = FunctionNode.NOT(filterBNot1);
final FunctionNode filterBNot3 = FunctionNode.NOT(filterBNot2);
final FunctionNode filterBNot4 = FunctionNode.NOT(filterBNot3);
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.AND(filterANot3, filterBNot4)));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final FunctionNode bound =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") });
final FunctionNode neq =
new FunctionNode(FunctionRegistry.NE, null,
new ValueExpressionNode[] { new VarNode("s"), new VarNode("o") });
FilterNode filterNode = new FilterNode(FunctionNode.OR(bound, neq));
assertTrue(StaticAnalysis.isCNF(filterNode));
// all NOT nodes should be resolved
whereClause.addChild(filterNode);
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test level three pushing of negation.
*/
public void testNestedNegationRewritingAndSplit() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final FunctionNode filterANot1 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") }));
final FunctionNode filterANot2 = FunctionNode.NOT(filterANot1);
final FunctionNode filterANot3 = FunctionNode.NOT(filterANot2);
final FunctionNode filterBNot1 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.EQ, null,
new ValueExpressionNode[] { new VarNode("s"), new VarNode("o") }));
final FunctionNode filterBNot2 = FunctionNode.NOT(filterBNot1);
final FunctionNode filterBNot3 = FunctionNode.NOT(filterBNot2);
final FunctionNode filterBNot4 = FunctionNode.NOT(filterBNot3);
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.OR(filterANot3, filterBNot4)));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final FunctionNode bound =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("o") });
final FunctionNode neq =
new FunctionNode(FunctionRegistry.NE, null,
new ValueExpressionNode[] { new VarNode("s"), new VarNode("o") });
whereClause.addChild(new FilterNode(bound));
whereClause.addChild(new FilterNode(neq));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test switch of OR over AND expression expression.
*/
public void testSimpleOrAndSwitch() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s5") });
final FilterNode filterNode =
new FilterNode(
FunctionNode.OR(
FunctionNode.AND(bound1, bound2),
FunctionNode.AND(bound3,
FunctionNode.AND(bound4, bound5))));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode and1 = FunctionNode.OR(bound1, bound3);
final FunctionNode and2 = FunctionNode.OR(bound1, bound4);
final FunctionNode and3 = FunctionNode.OR(bound1, bound5);
final FunctionNode and4 = FunctionNode.OR(bound2, bound3);
final FunctionNode and5 = FunctionNode.OR(bound2, bound4);
final FunctionNode and6 = FunctionNode.OR(bound2, bound5);
// after splitting, we should get the following conjuncts
whereClause.addChild(new FilterNode(and1));
whereClause.addChild(new FilterNode(and2));
whereClause.addChild(new FilterNode(and3));
whereClause.addChild(new FilterNode(and4));
whereClause.addChild(new FilterNode(and5));
whereClause.addChild(new FilterNode(and6));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test switch of OR over AND expression with top-level negation expression.
*/
public void testOrAndSwitchWithNegation() {
final ASTFilterNormalizationOptimizer rewriter =
new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setQueryHint(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode notBound1 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s1") }));
final FunctionNode notBound2 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s2") }));
final FunctionNode notBound3 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s3") }));
final FunctionNode notBound4 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s4") }));
final FunctionNode notBound5 =
FunctionNode.NOT(
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s5") }));
final FilterNode filterNode =
new FilterNode(
FunctionNode.NOT(
FunctionNode.AND(
FunctionNode.OR(notBound1, notBound2),
FunctionNode.OR(notBound3,
FunctionNode.OR(notBound4, notBound5)))));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setQueryHint(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 =
new FunctionNode(FunctionRegistry.BOUND, null,
new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode or1 = FunctionNode.OR(bound1, bound3);
final FunctionNode or2 = FunctionNode.OR(bound1, bound4);
final FunctionNode or3 = FunctionNode.OR(bound1, bound5);
final FunctionNode or4 = FunctionNode.OR(bound2, bound3);
final FunctionNode or5 = FunctionNode.OR(bound2, bound4);
final FunctionNode or6 = FunctionNode.OR(bound2, bound5);
// after splitting, we should get the following conjuncts
whereClause.addChild(new FilterNode(or1));
whereClause.addChild(new FilterNode(or2));
whereClause.addChild(new FilterNode(or3));
whereClause.addChild(new FilterNode(or4));
whereClause.addChild(new FilterNode(or5));
whereClause.addChild(new FilterNode(or6));
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test recursive optimization of OR - AND - OR - AND pattern.
*/
public void testOrAndSwitchRecursive() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode bound6 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final FunctionNode bound7 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s7") });
final FunctionNode bound8 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s8") });
final FunctionNode bound9 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s9") });
final FunctionNode bound10 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s10") });
final FunctionNode bound11 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s11") });
final FunctionNode bound12 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s12") });
final FunctionNode bound13 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s13") });
final FunctionNode bound14 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s14") });
final FunctionNode bound15 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s15") });
final FunctionNode bound16 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s16") });
final FilterNode filterNode =
new FilterNode(
FunctionNode.OR(
FunctionNode.AND(
FunctionNode.OR(
FunctionNode.AND(bound1, bound2),
FunctionNode.AND(bound3, bound4)
),
FunctionNode.OR(
FunctionNode.AND(bound5, bound6),
FunctionNode.AND(bound7, bound8)
)
),
FunctionNode.AND(
FunctionNode.OR(
FunctionNode.AND(bound9, bound10),
FunctionNode.AND(bound11, bound12)
),
FunctionNode.OR(
FunctionNode.AND(bound13, bound14),
FunctionNode.AND(bound15, bound16)
))));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode bound6 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final FunctionNode bound7 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s7") });
final FunctionNode bound8 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s8") });
final FunctionNode bound9 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s9") });
final FunctionNode bound10 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s10") });
final FunctionNode bound11 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s11") });
final FunctionNode bound12 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s12") });
final FunctionNode bound13 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s13") });
final FunctionNode bound14 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s14") });
final FunctionNode bound15 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s15") });
final FunctionNode bound16 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s16") });
/**
* Sketch of intended rewriting process (bottom-up)
*
* ### STEP 1: for the four leaf nodes we get the following.
*
* FunctionNode.OR(
* FunctionNode.AND(
* FunctionNode.AND(
* FunctionNode.OR(bound1,bound3)
* FunctionNode.OR(bound1,bound4)
* FunctionNode.OR(bound2,bound3)
* FunctionNode.OR(bound2,bound4)
* ),
* FunctionNode.AND(
* FunctionNode.OR(bound5,bound7)
* FunctionNode.OR(bound5,bound8)
* FunctionNode.OR(bound6,bound7)
* FunctionNode.OR(bound6,bound8)
* )
* ),
* FunctionNode.AND(
* FunctionNode.AND(
* FunctionNode.OR(bound9,bound11)
* FunctionNode.OR(bound9,bound12)
* FunctionNode.OR(bound10,bound11)
* FunctionNode.OR(bound10,bound12)
* ),
* FunctionNode.AND(
* FunctionNode.OR(bound13,bound15)
* FunctionNode.OR(bound13,bound16)
* FunctionNode.OR(bound14,bound15)
* FunctionNode.OR(bound14,bound16)
* )
* )
* )
*
* ### STEP 2: pushing down the top-level OR, we compute the cross
* product of the left and right disjuncts (we flatten
* out the and in the representation below):
*
* FunctionNode.AND(
* FunctionNode.AND(
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound3),
* FunctionNode.OR(bound9,bound11)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound3),
* FunctionNode.OR(bound9,bound12)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound3),
* FunctionNode.OR(bound10,bound11)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound3),
* FunctionNode.OR(bound10,bound12)
* ),
*
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound4),
* FunctionNode.OR(bound9,bound11)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound4),
* FunctionNode.OR(bound9,bound12)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound4),
* FunctionNode.OR(bound10,bound11)
* ),
* FunctionNode.OR(
* FunctionNode.OR(bound1,bound4),
* FunctionNode.OR(bound10,bound12)
* ),
*
* ...
*
* Each of those topmost OR expression gives us one FILTER expression
* in the end, resulting in 8x8 = 64 FILTERs. We construct them
* schematically below.
*/
final List<FunctionNode> lefts = new ArrayList<FunctionNode>();
lefts.add(FunctionNode.OR(bound1,bound3));
lefts.add(FunctionNode.OR(bound1,bound4));
lefts.add(FunctionNode.OR(bound2,bound3));
lefts.add(FunctionNode.OR(bound2,bound4));
lefts.add(FunctionNode.OR(bound5,bound7));
lefts.add(FunctionNode.OR(bound5,bound8));
lefts.add(FunctionNode.OR(bound6,bound7));
lefts.add(FunctionNode.OR(bound6,bound8));
final List<FunctionNode> rights = new ArrayList<FunctionNode>();
rights.add(FunctionNode.OR(bound9,bound11));
rights.add(FunctionNode.OR(bound9,bound12));
rights.add(FunctionNode.OR(bound10,bound11));
rights.add(FunctionNode.OR(bound10,bound12));
rights.add(FunctionNode.OR(bound13,bound15));
rights.add(FunctionNode.OR(bound13,bound16));
rights.add(FunctionNode.OR(bound14,bound15));
rights.add(FunctionNode.OR(bound14,bound16));
for (final FunctionNode left : lefts) {
for (final FunctionNode right : rights) {
whereClause.addChild(
new FilterNode(FunctionNode.OR(left, right)));
}
}
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test recursive optimization of OR - OR - AND pattern.
*/
public void testOrOrAndSwitch() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode bound6 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final FunctionNode bound7 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s7") });
final FunctionNode bound8 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s8") });
final FilterNode filterNode = new FilterNode(
FunctionNode.OR(
FunctionNode.OR(
FunctionNode.AND(bound1, bound2),
FunctionNode.AND(bound3, bound4)
),
FunctionNode.OR(
FunctionNode.AND(bound5, bound6),
FunctionNode.AND(bound7, bound8)
)));
assertFalse(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spn =
new StatementPatternNode(
new VarNode("s"), new VarNode("p"), new VarNode("o"),
null, Scope.DEFAULT_CONTEXTS);
whereClause.addChild(spn);
final FunctionNode bound1 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") });
final FunctionNode bound2 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s2") });
final FunctionNode bound3 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s3") });
final FunctionNode bound4 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s4") });
final FunctionNode bound5 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s5") });
final FunctionNode bound6 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s6") });
final FunctionNode bound7 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s7") });
final FunctionNode bound8 = new FunctionNode(FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s8") });
/**
*
* ### STEP 1: generates to OR connected leafs in CNF
*
* FunctionNode.OR(
* FunctionNode.AND(
* FunctionNode.AND(
* FunctionNode.OR(bound1, bound3),
* FunctionNode.OR(bound1, bound4)
* ),
* FunctionNode.AND(
* FunctionNode.OR(bound2, bound3),
* FunctionNode.OR(bound2, bound4)
* )
* ),
* FunctionNode.AND(
* FunctionNode.AND(
* FunctionNode.OR(bound5, bound7),
* FunctionNode.OR(bound5, bound8)
* ),
* FunctionNode.AND(
* FunctionNode.OR(bound6, bound7),
* FunctionNode.OR(bound6, bound8)
* )
* )
* )
*
* ### STEP 2: pushes down the uppermost OR expression
*
* Considers all OR-leafs in the left top-level AND expression
* and joins them with OR-leafs in the right top-level AND expression.
* After decomposing, this actually gives us 4x4 = 16 FILTERs.
*
*/
final List<FunctionNode> lefts = new ArrayList<FunctionNode>();
lefts.add(FunctionNode.OR(bound1,bound3));
lefts.add(FunctionNode.OR(bound1,bound4));
lefts.add(FunctionNode.OR(bound2,bound3));
lefts.add(FunctionNode.OR(bound2,bound4));
final List<FunctionNode> rights = new ArrayList<FunctionNode>();
rights.add(FunctionNode.OR(bound5,bound7));
rights.add(FunctionNode.OR(bound5,bound8));
rights.add(FunctionNode.OR(bound6,bound7));
rights.add(FunctionNode.OR(bound6,bound8));
for (final FunctionNode left : lefts) {
for (final FunctionNode right : rights) {
whereClause.addChild(
new FilterNode(FunctionNode.OR(left, right)));
}
}
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test removal of duplicate filter.
*/
public void testRemoveDuplicateFilter() {
final ASTFilterNormalizationOptimizer rewriter = new ASTFilterNormalizationOptimizer();
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s1"),
new VarNode("p1"), new VarNode("o1"), null/* c */,
Scope.DEFAULT_CONTEXTS)); // just noise
// two times exactly the same pattern
final FunctionNode simpleFunctionNode1 =
FunctionNode.NE(new VarNode("s1"), new VarNode("s2"));
final FunctionNode simpleFunctionNode2 =
FunctionNode.NE(new VarNode("s1"), new VarNode("s2"));
// three times the same pattern
final FunctionNode complexFunctionNode1 =
FunctionNode.OR(
FunctionNode.NE(new VarNode("s1"), new VarNode("s2")),
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") })));
final FunctionNode complexFunctionNode2 =
FunctionNode.OR(
FunctionNode.NE(new VarNode("s1"), new VarNode("s2")),
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") })));
final FunctionNode complexFunctionNode3 =
FunctionNode.OR(
FunctionNode.NE(new VarNode("s1"), new VarNode("s2")),
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") })));
whereClause.addChild(new FilterNode(simpleFunctionNode1));
whereClause.addChild(new FilterNode(simpleFunctionNode2));
whereClause.addChild(new FilterNode(complexFunctionNode1));
whereClause.addChild(new FilterNode(complexFunctionNode2));
whereClause.addChild(new StatementPatternNode(new VarNode("s2"),
new VarNode("p2"), new VarNode("o2"), null/* c */,
Scope.DEFAULT_CONTEXTS)); // just noise
whereClause.addChild(new FilterNode(complexFunctionNode3));
assertTrue(StaticAnalysis.isCNF(simpleFunctionNode1));
assertTrue(StaticAnalysis.isCNF(simpleFunctionNode2));
assertTrue(StaticAnalysis.isCNF(complexFunctionNode1));
assertTrue(StaticAnalysis.isCNF(complexFunctionNode2));
assertTrue(StaticAnalysis.isCNF(complexFunctionNode3));
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s1"),
new VarNode("p1"), new VarNode("o1"), null/* c */,
Scope.DEFAULT_CONTEXTS)); // just noise
// the simple function node
final FunctionNode simpleFunctionNode =
FunctionNode.NE(new VarNode("s1"), new VarNode("s2"));
// the complex function node
final FunctionNode complexFunctionNode =
FunctionNode.OR(
FunctionNode.NE(new VarNode("s1"), new VarNode("s2")),
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND,
null, new ValueExpressionNode[] { new VarNode("s1") })));
whereClause.addChild(new FilterNode(simpleFunctionNode));
whereClause.addChild(new StatementPatternNode(new VarNode("s2"),
new VarNode("p2"), new VarNode("o2"), null/* c */,
Scope.DEFAULT_CONTEXTS)); // just noise
whereClause.addChild(new FilterNode(complexFunctionNode));
assertTrue(StaticAnalysis.isCNF(simpleFunctionNode));
assertTrue(StaticAnalysis.isCNF(complexFunctionNode));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test removal of duplicate filter, where the duplicate is introduced
* through the CNF based decomposition process. This is a variant of test
* {@link TestASTFilterNormalizationOptimizer#testSimpleConjunctiveFilter()},
* where we just add a duplicate.
*/
public void testRemoveDuplicateGeneratedFilter() {
/*
* Note: DO NOT share structures in this test!!!!
*/
final BigdataValueFactory f = store.getValueFactory();
final BigdataURI testUri = f.createURI("http://www.test.com");
final IV test = makeIV(testUri);
final BigdataValue[] values = new BigdataValue[] { testUri };
store.getLexiconRelation()
.addTerms(values, values.length, false/* readOnly */);
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
final FilterNode filterNode =
new FilterNode(
FunctionNode.AND(
FunctionNode.EQ(new VarNode("s"), new VarNode("o")),
FunctionNode.NE(new VarNode("s"), new ConstantNode(test))));
// difference towards base test: this is the duplicate to be dropped
whereClause.addChild(
new FilterNode(
FunctionNode.EQ(new VarNode("s"), new VarNode("o"))));
assertTrue(StaticAnalysis.isCNF(filterNode));
whereClause.addChild(filterNode);
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
whereClause.addChild(new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o"), null/* c */,
Scope.DEFAULT_CONTEXTS));
whereClause.addChild(
new FilterNode(
FunctionNode.EQ(new VarNode("s"), new VarNode("o"))));
whereClause.addChild(
new FilterNode(
FunctionNode.NE(new VarNode("s"), new ConstantNode(test))));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final ASTFilterNormalizationOptimizer rewriter =
new ASTFilterNormalizationOptimizer();
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
/**
* Test removal of unsatisfiable filters. More precisely, the query
*
* SELECT ?s WHERE {
* ?s ?p ?o1 .
* { ?s ?p ?o2 }
* OPTIONAL { ?s ?p ?o3 }
*
* FILTER(bound(?o1))
* FILTER(bound(?o2))
* FILTER(bound(?o3))
*
* FILTER(!bound(?o1))
* FILTER(!bound(?o2))
* FILTER(!bound(?o3))
* FILTER(!bound(?o4))
*
* // some duplicates (which should be dropped)
* FILTER(!bound(?o2))
* FILTER(!bound(?o3))
* }
*
* will be rewritten to
*
* SELECT ?s WHERE {
* ?s ?p ?o1 .
* { ?s ?p ?o2 }
* OPTIONAL { ?s ?p ?o3 }
*
* // ?o1 and ?o2 are definitely bound, so we can't optimize away
* FILTER(bound(?o3))
*
* // ?o4 is the only variable that is definitely not bound
* FILTER(!bound(?o1))
* FILTER(!bound(?o2))
* FILTER(!bound(?o3))
* }
*
*/
public void testRemoveUnsatisfiableFilters() {
/*
* Note: DO NOT share structures in this test!!!!
*/
final IBindingSet[] bsets = new IBindingSet[] { new ListBindingSet() };
// The source AST.
final QueryRoot given = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
given.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
given.setWhereClause(whereClause);
final StatementPatternNode spo1 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o1"), null/* c */,
Scope.DEFAULT_CONTEXTS);
final StatementPatternNode spo2 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o2"), null/* c */,
Scope.DEFAULT_CONTEXTS);
final JoinGroupNode jgn = new JoinGroupNode(spo2);
final StatementPatternNode spo3 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o3"), null/* c */,
Scope.DEFAULT_CONTEXTS);
spo3.setOptional(true);
whereClause.addChild(spo1);
whereClause.addChild(jgn);
whereClause.addChild(spo3);
final FunctionNode filterBound1 =
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o1")});
final FunctionNode filterBound2 =
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o2")});
final FunctionNode filterBound3 =
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o3")});
final FunctionNode filterNotBound1 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o1")}));
final FunctionNode filterNotBound2 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o2")}));
final FunctionNode filterNotBound3 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o3")}));
final FunctionNode filterNotBound4 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o4")}));
whereClause.addChild(new FilterNode(filterBound1));
whereClause.addChild(new FilterNode(filterBound2));
whereClause.addChild(new FilterNode(filterBound3));
whereClause.addChild(new FilterNode(filterNotBound1));
whereClause.addChild(new FilterNode(filterNotBound2));
whereClause.addChild(new FilterNode(filterNotBound3));
whereClause.addChild(new FilterNode(filterNotBound4));
// add some duplicates (they should be removed)
whereClause.addChild(new FilterNode(filterNotBound2));
whereClause.addChild(new FilterNode(filterNotBound3));
}
// The expected AST after the rewrite.
final QueryRoot expected = new QueryRoot(QueryType.SELECT);
{
final ProjectionNode projection = new ProjectionNode();
expected.setProjection(projection);
projection.addProjectionVar(new VarNode("s"));
final JoinGroupNode whereClause = new JoinGroupNode();
whereClause.setProperty(QueryHints.NORMALIZE_FILTER_EXPRESSIONS, "true");
expected.setWhereClause(whereClause);
final StatementPatternNode spo1 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o1"), null/* c */,
Scope.DEFAULT_CONTEXTS);
final StatementPatternNode spo2 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o2"), null/* c */,
Scope.DEFAULT_CONTEXTS);
final JoinGroupNode jgn = new JoinGroupNode(spo2);
final StatementPatternNode spo3 =
new StatementPatternNode(new VarNode("s"),
new VarNode("p"), new VarNode("o3"), null/* c */,
Scope.DEFAULT_CONTEXTS);
spo3.setOptional(true);
whereClause.addChild(spo1);
whereClause.addChild(jgn);
whereClause.addChild(spo3);
final FunctionNode filterBound3 =
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o3")});
final FunctionNode filterNotBound1 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o1")}));
final FunctionNode filterNotBound2 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o2")}));
final FunctionNode filterNotBound3 =
FunctionNode.NOT(
new FunctionNode(
FunctionRegistry.BOUND, null/* scalarValues */,
new ValueExpressionNode[] {
new VarNode("o3")}));
whereClause.addChild(new FilterNode(filterBound3));
whereClause.addChild(new FilterNode(filterNotBound1));
whereClause.addChild(new FilterNode(filterNotBound2));
whereClause.addChild(new FilterNode(filterNotBound3));
}
final AST2BOpContext context =
new AST2BOpContext(new ASTContainer(given), store);
final ASTFilterNormalizationOptimizer rewriter =
new ASTFilterNormalizationOptimizer();
final IQueryNode actual =
rewriter.optimize(context, new QueryNodeWithBindingSet(given, bsets)).
getQueryNode();
assertSameAST(expected, actual);
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest18518.java | 2872 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest18518")
public class BenchmarkTest18518 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar = doSomething(param);
java.security.Provider[] provider = java.security.Security.getProviders();
javax.crypto.Cipher c;
try {
if (provider.length > 1) {
c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
} else {
c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5PADDING", java.security.Security.getProvider("SunJCE"));
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);
return bar;
}
}
| gpl-2.0 |
joezxh/DATAX-UI | eshbase-console/src/main/java/net/iharding/core/timer/DataBaseCronTriggerBean.java | 1042 | package net.iharding.core.timer;
import java.text.ParseException;
import net.iharding.modules.task.model.TimeTask;
import net.iharding.modules.task.service.TimeTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
/**
* spring4.1 数据库的读取配置任务触发器
* @author zhangxuhui
* @date 2013-9-22
* @version 1.0
*/
public class DataBaseCronTriggerBean extends CronTriggerFactoryBean{
@Autowired
private TimeTaskService timeTaskService;
/**
* 读取数据库更新文件
*/
public void afterPropertiesSet() throws ParseException {
super.afterPropertiesSet();
TimeTask task = timeTaskService.findUniqueBy("taskId",this.getObject().getKey().getName());
if(task!=null && task.getIsEffect().equals("1") &&!task.getCronExpression().equals(this.getObject().getCronExpression())){
this.setCronExpression(task.getCronExpression());
DynamicTask.updateSpringMvcTaskXML(getObject(),task.getCronExpression());
}
}
}
| gpl-2.0 |
sungsoo/esper | esper/src/main/java/com/espertech/esper/epl/agg/access/AggregationStateSortedImpl.java | 5476 | /**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.agg.access;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.collection.MultiKeyUntyped;
import com.espertech.esper.epl.expression.ExprEvaluator;
import com.espertech.esper.epl.expression.ExprEvaluatorContext;
import java.util.*;
/**
* Implementation of access function for single-stream (not joins).
*/
public class AggregationStateSortedImpl implements AggregationStateWithSize, AggregationStateSorted
{
protected final AggregationStateSortedSpec spec;
protected final TreeMap<Object, Object> sorted;
protected int size;
/**
* Ctor.
* @param spec aggregation spec
*/
public AggregationStateSortedImpl(AggregationStateSortedSpec spec) {
this.spec = spec;
sorted = new TreeMap<Object, Object>(spec.getComparator());
}
public void clear() {
sorted.clear();
size = 0;
}
public void applyEnter(EventBean[] eventsPerStream, ExprEvaluatorContext exprEvaluatorContext)
{
EventBean theEvent = eventsPerStream[spec.getStreamId()];
if (theEvent == null) {
return;
}
if (referenceEvent(theEvent)) {
Object comparable = getComparable(spec.getCriteria(), eventsPerStream, true, exprEvaluatorContext);
Object existing = sorted.get(comparable);
if (existing == null) {
sorted.put(comparable, theEvent);
}
else if (existing instanceof EventBean) {
ArrayDeque coll = new ArrayDeque(2);
coll.add(existing);
coll.add(theEvent);
sorted.put(comparable, coll);
}
else {
ArrayDeque q = (ArrayDeque) existing;
q.add(theEvent);
}
size++;
}
}
protected boolean referenceEvent(EventBean theEvent) {
// no action
return true;
}
protected boolean dereferenceEvent(EventBean theEvent) {
// no action
return true;
}
public void applyLeave(EventBean[] eventsPerStream, ExprEvaluatorContext exprEvaluatorContext)
{
EventBean theEvent = eventsPerStream[spec.getStreamId()];
if (theEvent == null) {
return;
}
if (dereferenceEvent(theEvent)) {
Object comparable = getComparable(spec.getCriteria(), eventsPerStream, false, exprEvaluatorContext);
Object existing = sorted.get(comparable);
if (existing != null) {
if (existing.equals(theEvent)) {
sorted.remove(comparable);
size--;
}
else if (existing instanceof ArrayDeque) {
ArrayDeque q = (ArrayDeque) existing;
q.remove(theEvent);
if (q.isEmpty()) {
sorted.remove(comparable);
}
size--;
}
}
}
}
public EventBean getFirstValue() {
if (sorted.isEmpty()) {
return null;
}
Map.Entry<Object, Object> max = sorted.firstEntry();
return checkedPayload(max.getValue());
}
public EventBean getLastValue()
{
if (sorted.isEmpty()) {
return null;
}
Map.Entry<Object, Object> min = sorted.lastEntry();
return checkedPayload(min.getValue());
}
public Iterator<EventBean> iterator() {
return new AggregationStateSortedIterator(sorted, false);
}
public Iterator<EventBean> getReverseIterator() {
return new AggregationStateSortedIterator(sorted, true);
}
public Collection<EventBean> collectionReadOnly() {
return new AggregationStateSortedWrappingCollection(sorted, size);
}
public int size()
{
return size;
}
protected static Object getComparable(ExprEvaluator[] criteria, EventBean[] eventsPerStream, boolean istream, ExprEvaluatorContext exprEvaluatorContext) {
if (criteria.length == 1) {
return criteria[0].evaluate(eventsPerStream, istream, exprEvaluatorContext);
}
else {
Object[] result = new Object[criteria.length];
int count = 0;
for(ExprEvaluator expr : criteria) {
result[count++] = expr.evaluate(eventsPerStream, true, exprEvaluatorContext);
}
return new MultiKeyUntyped(result);
}
}
private EventBean checkedPayload(Object value) {
if (value instanceof EventBean) {
return (EventBean) value;
}
ArrayDeque<EventBean> q = (ArrayDeque<EventBean>) value;
return q.getFirst();
}
} | gpl-2.0 |
mabuyo/ready-set-press | app/src/main/java/com/cmput301/mmabuyo/readysetpress/GameshowResults.java | 2703 | /*
Copyright 2015 Michelle Mabuyo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cmput301.mmabuyo.readysetpress;
/**
* Created by mmabuyo on 2015-10-01.
* Purpose:
* This class is responsible for the multiplayer mode of the game. It stores and updates
* the results of two, three and four player games as persistent data.
* Design Rationale:
* Results are stored in integer arrays, the size of which depends on how many
* players are playing that round. The first value in the array corresponds to Player One, and
* so on and so forth.
* Outstanding Issues:
* None.
*/
public class GameshowResults {
protected int[] twoPlayerResults;
protected int[] threePlayerResults;
protected int[] fourPlayerResults;
protected MemoryManager memoryManager = new MemoryManager();
public GameshowResults() {
twoPlayerResults = new int[2];
threePlayerResults = new int[3];
fourPlayerResults = new int[4];
}
public int[] getTwoPlayerResults() {
return twoPlayerResults;
}
public void setTwoPlayerResults(int[] twoPlayerResults) {
this.twoPlayerResults = twoPlayerResults;
}
public int[] getThreePlayerResults() {
return threePlayerResults;
}
public void setThreePlayerResults(int[] threePlayerResults) {
this.threePlayerResults = threePlayerResults;
}
public int[] getFourPlayerResults() {
return fourPlayerResults;
}
public void setFourPlayerResults(int[] fourPlayerResults) {
this.fourPlayerResults = fourPlayerResults;
}
protected void addClick(Player player, int numberOfPlayers) {
switch(numberOfPlayers) {
case 2:
getTwoPlayerResults()[player.getPid()-1]++;
break;
case 3:
getThreePlayerResults()[player.getPid()-1]++;
break;
case 4:
getFourPlayerResults()[player.getPid()-1]++;
break;
}
}
protected void clear() {
this.setTwoPlayerResults(new int[2]);
this.setThreePlayerResults(new int[3]);
this.setFourPlayerResults(new int[4]);
}
}
| gpl-2.0 |
akademikbilisim/ab2015-android-a | ab2015-3/app/src/main/java/org/ab/akademikbilisim/Detay.java | 2025 | package org.ab.akademikbilisim;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Detay extends ActionBarActivity {
private Intent ben;
private String yazi;
private TextView girilenDeger;
private Button btnKapat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detay);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ben = getIntent();
yazi = ben.getStringExtra("gonderilen");
girilenDeger = (TextView) findViewById(R.id.girilen_deger);
girilenDeger.setText(yazi);
btnKapat = (Button) findViewById(R.id.btn_kapat);
btnKapat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detay, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id == android.R.id.home){
// geri butonuna tıklandı
finish();
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08513.java | 2265 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08513")
public class BenchmarkTest08513 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
try {
javax.naming.directory.DirContext dc = org.owasp.benchmark.helpers.Utils.getDirContext();
dc.search("name", bar, new javax.naming.directory.SearchControls());
} catch (javax.naming.NamingException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
cdparra/reminiscens-lifeapi | app/controllers/PublicMementoControl.java | 429 | package controllers;
import play.mvc.*;
public class PublicMementoControl extends Controller {
public static Result getRandomMemento(String lang) {
/** @TODO */
return TODO;
}
public static Result getMemento(Long mid) {
/** @TODO */
return TODO;
}
public static Result getMementoList(Long decade, String place, String lat,
String lon, String rad, String lang) {
/** @TODO */
return TODO;
}
}
| gpl-2.0 |
CodingDK/eCampus-Dmaa0214 | eCampus-Dmaa0214/src/dk/dmaa0214/controllerLayer/SPNewsScraper.java | 5592 | package dk.dmaa0214.controllerLayer;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.StringWebResponse;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HTMLParser;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import dk.dmaa0214.modelLayer.SPNews;
public class SPNewsScraper {
//public static void main(String [] args) {
// new SPNewsScraper();
//}
private WebClient webClient;
public SPNewsScraper(String user, String pass) {
webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setCssEnabled(false);
DefaultCredentialsProvider credentialProvider = (DefaultCredentialsProvider) webClient.getCredentialsProvider();
credentialProvider.addNTLMCredentials(user, pass, null, -1, "localhost", "UCN");
}
public void getSingleNews(SPNews spNews) throws FailingHttpStatusCodeException, NullPointerException, IOException {
int id = spNews.getId();
String siteDialogURL = "http://ecampus.ucn.dk/Noticeboard/Lists/NoticeBoard/DispForm.aspx?"
+ "NoticeBoardItem=" + id + "&WebID=87441127-db6f-4499-8c99-3dea925e04a8&IsDlg=1";
HtmlPage page = webClient.getPage(siteDialogURL);
DomNode div = page.getFirstByXPath("//td[@class='wt-2column-t1-td1']/div/div");
if(div == null) {
throw new NullPointerException("Nyhedstekst kunne ikke hentes. Internkode: #3");
}
DomNodeList<DomNode> list = div.getChildNodes();
String fullText = "";
for (int i = 5; i < list.size()-3; i++) {
DomNode dn = list.get(i);
fullText += dn.asXml();
}
StringWebResponse response = new StringWebResponse(fullText, page.getUrl());
HtmlPage newPage = HTMLParser.parseHtml(response, webClient.getCurrentWindow());
makeImgToBase64(newPage);
HtmlElement body = newPage.getBody();
spNews.setFullText(body.asXml());
}
private void makeImgToBase64(HtmlPage page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
@SuppressWarnings("unchecked")
List<HtmlImage> imageList = (List<HtmlImage>) page.getByXPath("//img");
for (HtmlImage image : imageList) {
InputStream ins = webClient.getPage("http://ecampus.ucn.dk" + image.getSrcAttribute()).getWebResponse().getContentAsStream();
byte[] imageBytes = new byte[0];
for(byte[] ba = new byte[ins.available()]; ins.read(ba) != -1;) {
byte[] baTmp = new byte[imageBytes.length + ba.length];
System.arraycopy(imageBytes, 0, baTmp, 0, imageBytes.length);
System.arraycopy(ba, 0, baTmp, imageBytes.length, ba.length);
imageBytes = baTmp;
}
image.setAttribute("src", "data:image/gif;base64," + DatatypeConverter.printBase64Binary(imageBytes));
}
}
public ArrayList<SPNews> getNewsList() throws NullPointerException, FailingHttpStatusCodeException, MalformedURLException, IOException {
String siteURL = "http://ecampus.ucn.dk/Noticeboard/_Layouts/NoticeBoard/Ajax.aspx?Action="
+ "GetNewsList&ShowBodyContent=SHORT100&WebId=87441127-db6f-4499-8c99-3dea925e04a8"
+ "&ChannelList=11776,4096,3811,3817,4311,4312,4313,4768,4314,4315,4316,4317,4310,"
+ "&DateFormat=dd/MM/yyyy HH:mm&List=Current,Archived&IncludeRead=true&MaxToShow=10"
+ "&Page=1&frontpageonly=false";
HtmlPage page = webClient.getPage(siteURL);
return ScrapeNewsList(page.asText());
}
private ArrayList<SPNews> ScrapeNewsList(String input) throws NullPointerException {
ArrayList<SPNews> newslist = new ArrayList<SPNews>();
int iStart = getNextIndex(input, 0);
if(!input.substring(0, iStart).equals("OK")) {
throw new NullPointerException("Nyhederne kan ikke læses. Internkode: #1. Status: " + input.substring(0, iStart));
}
String[] allNews = input.split("\\|\\$\\$\\|");
//System.out.println("count: " + (allNews.length-1));
for (int i = 1; i < allNews.length; i++) {
String[] singleNews = allNews[i].split("\\|\\$\\|");
if(singleNews.length != 11) {
throw new NullPointerException("Nyhederne kan ikke læses. Internkode: #2. Rapport: " + singleNews.length);
}
int id = getIntFromString(singleNews[0]);
String title = singleNews[1].trim();
String date = singleNews[2].trim();
boolean read = (getIntFromString(singleNews[3]) == 1);
String[] channelArray = singleNews[4].trim().split("\\|");
ArrayList<String> channels = new ArrayList<String>(Arrays.asList(channelArray));
String addedBy = singleNews[6].trim();
String text = singleNews[7].trim(); //7 and 8 is equal.
SPNews newsObj = new SPNews(id, title, date, channels, text, addedBy, read);
newslist.add(newsObj);
}
return newslist;
}
private int getIntFromString(String str) {
int ret = -1;
try {
ret = Integer.parseInt(str);
} catch (NumberFormatException e) {
ret = -1;
}
return ret;
}
private int getNextIndex(String text, int fromIndex){
int i = text.indexOf("|$|", fromIndex);
if (i == -1) {
throw new NullPointerException("Nyhederne kan ikke læses");
}
return i;
}
}
| gpl-2.0 |
smarr/Truffle | truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/TruffleExceptionTest.java | 31384 | /*
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.api.test;
import static com.oracle.truffle.api.test.RootNodeTest.verifyStackTraceElementGuestObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.regex.Pattern;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.PolyglotException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleLanguage;
import com.oracle.truffle.api.TruffleLogger;
import com.oracle.truffle.api.TruffleStackTrace;
import com.oracle.truffle.api.TruffleStackTraceElement;
import com.oracle.truffle.api.exception.AbstractTruffleException;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.ExceptionType;
import com.oracle.truffle.api.interop.InteropException;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.InvalidArrayIndexException;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.library.ExportLibrary;
import com.oracle.truffle.api.library.ExportMessage;
import com.oracle.truffle.api.nodes.ControlFlowException;
import com.oracle.truffle.api.nodes.DirectCallNode;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.profiles.BranchProfile;
import com.oracle.truffle.api.source.SourceSection;
import com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest;
import com.oracle.truffle.api.test.polyglot.ProxyLanguage;
import com.oracle.truffle.tck.tests.TruffleTestAssumptions;
public class TruffleExceptionTest extends AbstractPolyglotTest {
@BeforeClass
public static void runWithWeakEncapsulationOnly() {
TruffleTestAssumptions.assumeWeakEncapsulation();
}
private VerifyingHandler verifyingHandler;
@Before
public void setUp() {
verifyingHandler = new VerifyingHandler(AbstractTruffleException.class);
}
@Test
public void testTruffleException() {
setupEnv(createContext(verifyingHandler), new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
return createAST(AbstractTruffleException.class, languageInstance, (n) -> new TruffleExceptionImpl("Test exception", n), false);
}
});
verifyingHandler.expect(BlockNode.Kind.TRY, BlockNode.Kind.CATCH, BlockNode.Kind.FINALLY);
context.eval(ProxyLanguage.ID, "Test");
}
@Test
public void testTruffleExceptionCustomGuestObject() {
setupEnv(createContext(verifyingHandler), new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
return createAST(AbstractTruffleException.class, languageInstance, (n) -> new TruffleExceptionImpl("Test exception", n), true);
}
});
verifyingHandler.expect(BlockNode.Kind.TRY, BlockNode.Kind.CATCH, BlockNode.Kind.FINALLY);
context.eval(ProxyLanguage.ID, "Test");
}
@Test
public void testPolyglotStackTrace() {
testStackTraceImpl(new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode((n) -> {
return new TruffleExceptionImpl("Test exception", n);
});
return new TestRootNode(languageInstance, "test", null, throwNode).getCallTarget();
}
},
"<proxyLanguage> test",
"(org.graalvm.sdk/)?org.graalvm.polyglot.Context.eval");
}
@Test
public void testPolyglotStackTrace2() {
testStackTraceImpl(new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode((n) -> {
return new TruffleExceptionImpl("Test exception", n);
});
CallTarget throwTarget = new TestRootNode(languageInstance, "test-throw", null, throwNode).getCallTarget();
CallTarget innerInvokeTarget = new TestRootNode(languageInstance, "test-call-inner", null, new InvokeNode(throwTarget)).getCallTarget();
CallTarget outerInvokeTarget = new TestRootNode(languageInstance, "test-call-outer", null, new InvokeNode(innerInvokeTarget)).getCallTarget();
return outerInvokeTarget;
}
},
"<proxyLanguage> test-throw",
"<proxyLanguage> test-call-inner",
"<proxyLanguage> test-call-outer",
"(org.graalvm.sdk/)?org.graalvm.polyglot.Context.eval");
}
@Test
public void testPolyglotStackTraceInternalFrame() {
testStackTraceImpl(new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode((n) -> {
return new TruffleExceptionImpl("Test exception", n);
});
CallTarget throwTarget = new TestRootNode(languageInstance, "test-throw-internal", null, true, throwNode).getCallTarget();
CallTarget innerInvokeTarget = new TestRootNode(languageInstance, "test-call-inner", null, new InvokeNode(throwTarget)).getCallTarget();
CallTarget internalInvokeTarget = new TestRootNode(languageInstance, "test-call-internal", null, true, new InvokeNode(innerInvokeTarget)).getCallTarget();
CallTarget outerInvokeTarget = new TestRootNode(languageInstance, "test-call-outer", null, new InvokeNode(internalInvokeTarget)).getCallTarget();
return outerInvokeTarget;
}
},
"<proxyLanguage> test-call-inner",
"<proxyLanguage> test-call-outer",
"(org.graalvm.sdk/)?org.graalvm.polyglot.Context.eval");
}
@Test
public void testPolyglotStackTraceExplicitFillIn() {
testStackTraceImpl(new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode((n) -> {
TruffleExceptionImpl e = new TruffleExceptionImpl("Test exception", n);
TruffleStackTrace.fillIn(e);
return e;
});
return new TestRootNode(languageInstance, "test", null, throwNode).getCallTarget();
}
},
"<proxyLanguage> test",
"(org.graalvm.sdk/)?org.graalvm.polyglot.Context.eval");
}
@Test
public void testPolyglotStackTraceInternalError() {
testStackTraceImpl(new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode(new InternalExceptionFactory());
return new TestRootNode(languageInstance, "test", null, throwNode).getCallTarget();
}
},
Pattern.quote("com.oracle.truffle.api.test.TruffleExceptionTest$InternalExceptionFactory.apply"),
Pattern.quote("com.oracle.truffle.api.test.TruffleExceptionTest$ThrowNode.executeVoid"),
Pattern.quote("com.oracle.truffle.api.test.TruffleExceptionTest$TestRootNode.execute"),
"<proxyLanguage> test",
"(org.graalvm.sdk/)?org.graalvm.polyglot.Context.eval");
}
@Test
public void testExceptionFromCreateContext() {
String message = "Failed to create";
ExceptionType type = ExceptionType.EXIT;
assertFails(() -> setupEnv(Context.create(), new ProxyLanguage() {
@Override
protected LanguageContext createContext(Env env) {
throw new TruffleExceptionImpl(message, null, type, null);
}
}), PolyglotException.class, (pe) -> {
Assert.assertEquals(message, pe.getMessage());
Assert.assertTrue(pe.isExit());
Assert.assertFalse(pe.isInternalError());
Assert.assertEquals(0, pe.getExitStatus());
Assert.assertNull(pe.getGuestObject());
});
}
private void testStackTraceImpl(ProxyLanguage proxy, String... patterns) {
setupEnv(Context.create(), proxy);
assertFails(() -> context.eval(ProxyLanguage.ID, "Test"), PolyglotException.class, (pe) -> {
verifyStackTrace(pe, patterns);
});
}
static void verifyStackTrace(PolyglotException pe, String... patterns) {
StringWriter buffer = new StringWriter();
try (PrintWriter out = new PrintWriter(buffer)) {
pe.printStackTrace(out);
}
String[] lines = Arrays.stream(buffer.toString().split(System.lineSeparator())).map((l) -> l.trim()).filter((l) -> l.startsWith("at ")).map((l) -> {
int end = l.lastIndexOf('(');
if (end < 0) {
end = l.length();
}
return l.substring(3, end);
}).toArray((len) -> new String[len]);
Assert.assertTrue("Not enough lines " + Arrays.toString(lines), patterns.length <= lines.length);
for (int i = 0; i < lines.length && i < patterns.length; i++) {
String line = lines[i];
Pattern pattern = Pattern.compile(patterns[i]);
Assert.assertTrue("Expected " + patterns[i] + " but got " + line, pattern.matcher(line).matches());
}
}
@Test
public void testExceptionFromPolyglotExceptionConstructor() {
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.RUNTIME_ERROR, false);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.RUNTIME_ERROR, true, TruffleExceptionImpl.MessageKind.IS_EXCEPTION);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.RUNTIME_ERROR, true, TruffleExceptionImpl.MessageKind.GET_EXCEPTION_TYPE);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.EXIT, true, TruffleExceptionImpl.MessageKind.GET_EXCEPTION_EXIT_STATUS);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.PARSE_ERROR, true, TruffleExceptionImpl.MessageKind.IS_EXCEPTION_INCOMPLETE_SOURCE);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.RUNTIME_ERROR, true, TruffleExceptionImpl.MessageKind.HAS_SOURCE_LOCATION);
testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType.RUNTIME_ERROR, true, TruffleExceptionImpl.MessageKind.GET_SOURCE_LOCATION);
}
private void testExceptionFromPolyglotExceptionConstructorImpl(ExceptionType type, boolean internal, TruffleExceptionImpl.MessageKind... failOn) {
setupEnv(Context.create(), new ProxyLanguage() {
@Override
protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
ThrowNode throwNode = new ThrowNode((n) -> new TruffleExceptionImpl("test", n, type, new InjectException(failOn)));
return new TestRootNode(languageInstance, "test", "unnamed", throwNode).getCallTarget();
}
});
assertFails(() -> context.eval(ProxyLanguage.ID, "Test"), PolyglotException.class, (pe) -> {
Assert.assertEquals(internal, pe.isInternalError());
});
}
static Context createContext(VerifyingHandler handler) {
return Context.newBuilder().option(String.format("log.%s.level", handler.loggerName), "FINE").logHandler(handler).build();
}
static CallTarget createAST(Class<?> testClass, TruffleLanguage<ProxyLanguage.LanguageContext> lang,
ExceptionFactory exceptionObjectFactroy, boolean customStackTraceElementGuestObject) {
ThrowNode throwNode = new ThrowNode(exceptionObjectFactroy);
TryCatchNode tryCatch = new TryCatchNode(new BlockNode(testClass, BlockNode.Kind.TRY, throwNode),
new BlockNode(testClass, BlockNode.Kind.CATCH),
new BlockNode(testClass, BlockNode.Kind.FINALLY));
return new TestRootNode(lang, "test", customStackTraceElementGuestObject ? "unnamed" : null, tryCatch).getCallTarget();
}
@SuppressWarnings({"unchecked", "unused"})
static <T extends Throwable> T sthrow(Class<T> type, Throwable t) throws T {
throw (T) t;
}
static final class TestRootNode extends RootNode {
private final String name;
private final String ownerName;
private final boolean internal;
private final StackTraceElementGuestObject customStackTraceElementGuestObject;
@Child StatementNode body;
TestRootNode(TruffleLanguage<?> language, String name, String ownerName, StatementNode body) {
this(language, name, ownerName, false, body);
}
TestRootNode(TruffleLanguage<?> language, String name, String ownerName, boolean internal, StatementNode body) {
super(language);
this.name = name;
this.ownerName = ownerName;
this.internal = internal;
this.body = body;
this.customStackTraceElementGuestObject = ownerName != null ? new StackTraceElementGuestObject(name, ownerName) : null;
}
@Override
public String getQualifiedName() {
return ownerName != null ? ownerName + '.' + name : name;
}
@Override
public String getName() {
return name;
}
@Override
public Object execute(VirtualFrame frame) {
body.executeVoid(frame);
return true;
}
@Override
protected Object translateStackTraceElement(TruffleStackTraceElement element) {
if (customStackTraceElementGuestObject != null) {
return customStackTraceElementGuestObject;
} else {
return super.translateStackTraceElement(element);
}
}
@Override
public boolean isInternal() {
return internal;
}
}
@ExportLibrary(InteropLibrary.class)
static final class StackTraceElementGuestObject implements TruffleObject {
private final String name;
private final Object owner;
StackTraceElementGuestObject(String name, String ownerName) {
this.name = name;
this.owner = new OwnerMetaObject(ownerName);
}
@ExportMessage
@SuppressWarnings("static-method")
boolean hasExecutableName() {
return true;
}
@ExportMessage
Object getExecutableName() {
return name;
}
@ExportMessage
@SuppressWarnings("static-method")
boolean hasDeclaringMetaObject() {
return true;
}
@ExportMessage
Object getDeclaringMetaObject() {
return owner;
}
@ExportLibrary(InteropLibrary.class)
static final class OwnerMetaObject implements TruffleObject {
private final String name;
OwnerMetaObject(String name) {
this.name = name;
}
@ExportMessage
@SuppressWarnings("static-method")
boolean isMetaObject() {
return true;
}
@ExportMessage
@SuppressWarnings({"static-method", "unused"})
boolean isMetaInstance(Object object) {
return false;
}
@ExportMessage
Object getMetaQualifiedName() {
return name;
}
@ExportMessage
Object getMetaSimpleName() {
return name;
}
}
}
abstract static class StatementNode extends Node {
abstract void executeVoid(VirtualFrame frame);
}
static class BlockNode extends StatementNode {
enum Kind {
TRY,
CATCH,
FINALLY
}
@Children private StatementNode[] children;
BlockNode(Class<?> testClass, Kind kind, StatementNode... children) {
this.children = new StatementNode[children.length + 1];
this.children[0] = new LogNode(testClass, kind.name());
System.arraycopy(children, 0, this.children, 1, children.length);
}
@Override
@ExplodeLoop
void executeVoid(VirtualFrame frame) {
for (StatementNode child : children) {
child.executeVoid(frame);
}
}
}
private static class LogNode extends StatementNode {
private final TruffleLogger log;
private final String message;
LogNode(Class<?> testClass, String message) {
log = TruffleLogger.getLogger(ProxyLanguage.ID, testClass.getName());
this.message = message;
}
@Override
void executeVoid(VirtualFrame frame) {
log.fine(message);
}
}
private static final class TryCatchNode extends StatementNode {
@Child private BlockNode block;
@Child private BlockNode catchBlock;
@Child private BlockNode finallyBlock;
@Child private InteropLibrary exceptions = InteropLibrary.getFactory().createDispatched(5);
private final BranchProfile exceptionProfile = BranchProfile.create();
TryCatchNode(BlockNode block, BlockNode catchBlock, BlockNode finallyBlock) {
this.block = block;
this.catchBlock = catchBlock;
this.finallyBlock = finallyBlock;
}
@Override
void executeVoid(VirtualFrame frame) {
Throwable exception = null;
try {
block.executeVoid(frame);
} catch (Throwable ex) {
exception = executeCatchBlock(frame, ex, catchBlock);
}
// Java finally blocks that execute nodes are not allowed for
// compilation as code in finally blocks is duplicated
// by the Java bytecode compiler. This can lead to
// exponential code growth in worst cases.
if (finallyBlock != null) {
finallyBlock.executeVoid(frame);
}
if (exception != null) {
if (exception instanceof ControlFlowException) {
throw (ControlFlowException) exception;
}
try {
throw exceptions.throwException(exception);
} catch (UnsupportedMessageException ie) {
throw CompilerDirectives.shouldNotReachHere(ie);
}
}
}
@SuppressWarnings("unchecked")
private <T extends Throwable> Throwable executeCatchBlock(VirtualFrame frame, Throwable ex, BlockNode catchBlk) throws T {
if (ex instanceof ControlFlowException) {
// run finally blocks for control flow
return ex;
}
exceptionProfile.enter();
if (exceptions.isException(ex)) {
assertTruffleExceptionProperties(ex);
if (catchBlk != null) {
try {
catchBlk.executeVoid(frame);
return null;
} catch (Throwable catchEx) {
return executeCatchBlock(frame, catchEx, null);
}
} else {
// run finally blocks for any interop exception
return ex;
}
} else {
// do not run finally blocks for internal errors or unwinds
throw (T) ex;
}
}
@TruffleBoundary
private void assertTruffleExceptionProperties(Throwable ex) {
try {
Assert.assertEquals(ExceptionType.RUNTIME_ERROR, exceptions.getExceptionType(ex));
AbstractPolyglotTest.assertFails(() -> {
exceptions.getExceptionExitStatus(ex);
return null;
}, UnsupportedMessageException.class);
if (ex.getMessage() != null) {
Assert.assertTrue(exceptions.hasExceptionMessage(ex));
Assert.assertEquals(ex.getMessage(), exceptions.getExceptionMessage(ex));
} else {
Assert.assertFalse(exceptions.hasExceptionMessage(ex));
}
assertStackTrace(ex);
} catch (InteropException ie) {
CompilerDirectives.shouldNotReachHere(ie);
}
}
private void assertStackTrace(Throwable t) throws UnsupportedMessageException, InvalidArrayIndexException {
List<TruffleStackTraceElement> stack = TruffleStackTrace.getStackTrace(t);
Object stackGuestObject = exceptions.getExceptionStackTrace(t);
Assert.assertTrue(exceptions.hasArrayElements(stackGuestObject));
Assert.assertEquals(stack.size(), exceptions.getArraySize(stackGuestObject));
for (int i = 0; i < stack.size(); i++) {
Object stackTraceElementObject = exceptions.readArrayElement(stackGuestObject, i);
verifyStackTraceElementGuestObject(stackTraceElementObject);
Assert.assertTrue(exceptions.hasExecutableName(stackTraceElementObject));
String executableName = exceptions.asString(exceptions.getExecutableName(stackTraceElementObject));
Assert.assertEquals(stack.get(i).getTarget().getRootNode().getName(), executableName);
String qualifiedName;
if (exceptions.hasDeclaringMetaObject(stackTraceElementObject)) {
qualifiedName = exceptions.asString(exceptions.getMetaQualifiedName(exceptions.getDeclaringMetaObject(stackTraceElementObject))) + '.' + executableName;
} else {
qualifiedName = executableName;
}
Assert.assertEquals(stack.get(i).getTarget().getRootNode().getQualifiedName(), qualifiedName);
}
}
}
interface ExceptionFactory {
Object apply(Node t);
}
static final class InternalExceptionFactory implements ExceptionFactory {
@Override
public Object apply(Node t) {
CompilerDirectives.transferToInterpreter();
throw new RuntimeException();
}
}
static class ThrowNode extends StatementNode {
private final ExceptionFactory exceptionObjectFactory;
@Child InteropLibrary interop;
ThrowNode(ExceptionFactory exceptionObjectFactroy) {
this.exceptionObjectFactory = exceptionObjectFactroy;
this.interop = InteropLibrary.getFactory().createDispatched(1);
}
@Override
void executeVoid(VirtualFrame frame) {
try {
throw interop.throwException(exceptionObjectFactory.apply(this));
} catch (UnsupportedMessageException um) {
throw CompilerDirectives.shouldNotReachHere(um);
}
}
}
static class InvokeNode extends StatementNode {
private final DirectCallNode call;
InvokeNode(CallTarget target) {
this.call = Truffle.getRuntime().createDirectCallNode(target);
}
@Override
void executeVoid(VirtualFrame frame) {
this.call.call();
}
}
@SuppressWarnings("serial")
@ExportLibrary(InteropLibrary.class)
static final class TruffleExceptionImpl extends AbstractTruffleException {
enum MessageKind {
IS_EXCEPTION,
THROW_EXCEPTION,
GET_EXCEPTION_TYPE,
GET_EXCEPTION_EXIT_STATUS,
IS_EXCEPTION_INCOMPLETE_SOURCE,
HAS_SOURCE_LOCATION,
GET_SOURCE_LOCATION
}
private final ExceptionType exceptionType;
private final Consumer<MessageKind> exceptionInjection;
TruffleExceptionImpl(String message, Node location) {
this(message, location, ExceptionType.RUNTIME_ERROR, null);
}
TruffleExceptionImpl(
String message,
Node location,
ExceptionType exceptionType,
Consumer<MessageKind> exceptionInjection) {
super(message, location);
this.exceptionType = exceptionType;
this.exceptionInjection = exceptionInjection;
}
@ExportMessage
boolean isException() {
injectException(MessageKind.IS_EXCEPTION);
return true;
}
@ExportMessage
RuntimeException throwException() {
injectException(MessageKind.THROW_EXCEPTION);
throw this;
}
@ExportMessage
ExceptionType getExceptionType() {
injectException(MessageKind.GET_EXCEPTION_TYPE);
return exceptionType;
}
@ExportMessage
int getExceptionExitStatus() throws UnsupportedMessageException {
injectException(MessageKind.GET_EXCEPTION_EXIT_STATUS);
if (exceptionType != ExceptionType.EXIT) {
throw UnsupportedMessageException.create();
} else {
return 0;
}
}
@ExportMessage
boolean isExceptionIncompleteSource() throws UnsupportedMessageException {
injectException(MessageKind.IS_EXCEPTION_INCOMPLETE_SOURCE);
if (exceptionType != ExceptionType.PARSE_ERROR) {
throw UnsupportedMessageException.create();
} else {
return true;
}
}
@ExportMessage
boolean hasSourceLocation() {
injectException(MessageKind.HAS_SOURCE_LOCATION);
Node location = getLocation();
return location != null && location.getEncapsulatingSourceSection() != null;
}
@ExportMessage(name = "getSourceLocation")
SourceSection getSource() throws UnsupportedMessageException {
injectException(MessageKind.GET_SOURCE_LOCATION);
Node location = getLocation();
SourceSection section = location == null ? null : location.getEncapsulatingSourceSection();
if (section == null) {
throw UnsupportedMessageException.create();
} else {
return section;
}
}
@TruffleBoundary
private void injectException(MessageKind messageKind) {
if (exceptionInjection != null) {
exceptionInjection.accept(messageKind);
}
}
}
private static final class InjectException implements Consumer<TruffleExceptionImpl.MessageKind> {
private final Set<TruffleExceptionImpl.MessageKind> messages;
private InjectException(TruffleExceptionImpl.MessageKind... messages) {
this.messages = EnumSet.noneOf(TruffleExceptionImpl.MessageKind.class);
Collections.addAll(this.messages, messages);
}
@Override
public void accept(TruffleExceptionImpl.MessageKind kind) {
if (messages.contains(kind)) {
throw new RuntimeException();
}
}
}
static final class VerifyingHandler extends Handler {
final String loggerName;
private Queue<String> expected = new ArrayDeque<>();
VerifyingHandler(Class<?> testClass) {
loggerName = String.format("%s.%s", ProxyLanguage.ID, testClass.getName());
}
void expect(BlockNode.Kind... kinds) {
Arrays.stream(kinds).map(BlockNode.Kind::name).forEach(expected::add);
}
@Override
public void publish(LogRecord lr) {
if (loggerName.equals(lr.getLoggerName())) {
String head = expected.remove();
Assert.assertEquals(head, lr.getMessage());
}
}
@Override
public void flush() {
}
@Override
public void close() {
Assert.assertTrue("All expected events must be consumed. Remaining events: " + String.join(", ", expected), expected.isEmpty());
}
}
}
| gpl-2.0 |
google/desugar_jdk_libs | jdk11/src/libcore/ojluni/src/main/java/java/security/KeyStore.java | 77059 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.security;
import java.io.*;
import java.net.URI;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.callback.*;
/**
* This class represents a storage facility for cryptographic
* keys and certificates.
*
* <p> A {@code KeyStore} manages different types of entries.
* Each type of entry implements the {@code KeyStore.Entry} interface.
* Three basic {@code KeyStore.Entry} implementations are provided:
*
* <ul>
* <li><b>KeyStore.PrivateKeyEntry</b>
* <p> This type of entry holds a cryptographic {@code PrivateKey},
* which is optionally stored in a protected format to prevent
* unauthorized access. It is also accompanied by a certificate chain
* for the corresponding public key.
*
* <p> Private keys and certificate chains are used by a given entity for
* self-authentication. Applications for this authentication include software
* distribution organizations which sign JAR files as part of releasing
* and/or licensing software.
*
* <li><b>KeyStore.SecretKeyEntry</b>
* <p> This type of entry holds a cryptographic {@code SecretKey},
* which is optionally stored in a protected format to prevent
* unauthorized access.
*
* <li><b>KeyStore.TrustedCertificateEntry</b>
* <p> This type of entry contains a single public key {@code Certificate}
* belonging to another party. It is called a <i>trusted certificate</i>
* because the keystore owner trusts that the public key in the certificate
* indeed belongs to the identity identified by the <i>subject</i> (owner)
* of the certificate.
*
* <p>This type of entry can be used to authenticate other parties.
* </ul>
*
* <p> Each entry in a keystore is identified by an "alias" string. In the
* case of private keys and their associated certificate chains, these strings
* distinguish among the different ways in which the entity may authenticate
* itself. For example, the entity may authenticate itself using different
* certificate authorities, or using different public key algorithms.
*
* <p> Whether aliases are case sensitive is implementation dependent. In order
* to avoid problems, it is recommended not to use aliases in a KeyStore that
* only differ in case.
*
* <p> Whether keystores are persistent, and the mechanisms used by the
* keystore if it is persistent, are not specified here. This allows
* use of a variety of techniques for protecting sensitive (e.g., private or
* secret) keys. Smart cards or other integrated cryptographic engines
* (SafeKeyper) are one option, and simpler mechanisms such as files may also
* be used (in a variety of formats).
*
* <p> Typical ways to request a KeyStore object include
* relying on the default type and providing a specific keystore type.
*
* <ul>
* <li>To rely on the default type:
* <pre>
* KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
* </pre>
* The system will return a keystore implementation for the default type.
*
* <li>To provide a specific keystore type:
* <pre>
* KeyStore ks = KeyStore.getInstance("JKS");
* </pre>
* The system will return the most preferred implementation of the
* specified keystore type available in the environment. <p>
* </ul>
*
* <p> Before a keystore can be accessed, it must be
* {@link #load(java.io.InputStream, char[]) loaded}.
* <pre>
* KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
*
* // get user password and file input stream
* char[] password = getPassword();
*
* try (FileInputStream fis = new FileInputStream("keyStoreName")) {
* ks.load(fis, password);
* }
* </pre>
*
* To create an empty keystore using the above {@code load} method,
* pass {@code null} as the {@code InputStream} argument.
*
* <p> Once the keystore has been loaded, it is possible
* to read existing entries from the keystore, or to write new entries
* into the keystore:
* <pre>
* KeyStore.ProtectionParameter protParam =
* new KeyStore.PasswordProtection(password);
*
* // get my private key
* KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
* ks.getEntry("privateKeyAlias", protParam);
* PrivateKey myPrivateKey = pkEntry.getPrivateKey();
*
* // save my secret key
* javax.crypto.SecretKey mySecretKey;
* KeyStore.SecretKeyEntry skEntry =
* new KeyStore.SecretKeyEntry(mySecretKey);
* ks.setEntry("secretKeyAlias", skEntry, protParam);
*
* // store away the keystore
* try (FileOutputStream fos = new FileOutputStream("newKeyStoreName")) {
* ks.store(fos, password);
* }
* </pre>
*
* Note that although the same password may be used to
* load the keystore, to protect the private key entry,
* to protect the secret key entry, and to store the keystore
* (as is shown in the sample code above),
* different passwords or other protection parameters
* may also be used.
*
* <p> Android provides the following <code>KeyStore</code> types:
* <table>
* <thead>
* <tr>
* <th>Algorithm</th>
* <th>Supported API Levels</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>AndroidCAStore</td>
* <td>14+</td>
* </tr>
* <tr>
* <td>AndroidKeyStore</td>
* <td>18+</td>
* </tr>
* <tr class="deprecated">
* <td>BCPKCS12</td>
* <td>1-8</td>
* </tr>
* <tr>
* <td>BKS</td>
* <td>1+</td>
* </tr>
* <tr>
* <td>BouncyCastle</td>
* <td>1+</td>
* </tr>
* <tr>
* <td>PKCS12</td>
* <td>1+</td>
* </tr>
* <tr class="deprecated">
* <td>PKCS12-DEF</td>
* <td>1-8</td>
* </tr>
* </tbody>
* </table>
*
* These types are described in the <a href=
* "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
* KeyStore section</a> of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
*
* @author Jan Luehe
*
* @see java.security.PrivateKey
* @see javax.crypto.SecretKey
* @see java.security.cert.Certificate
*
* @since 1.2
*/
public class KeyStore {
// BEGIN Android-removed: this debugging mechanism is not supported in Android.
/*
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("keystore");
*/
// END Android-removed: this debugging mechanism is not supported in Android.
/*
* Constant to lookup in the Security properties file to determine
* the default keystore type.
* In the Security properties file, the default keystore type is given as:
* <pre>
* keystore.type=jks
* </pre>
*/
private static final String KEYSTORE_TYPE = "keystore.type";
// The keystore type
private String type;
// The provider
private Provider provider;
// The provider implementation
private KeyStoreSpi keyStoreSpi;
// Has this keystore been initialized (loaded)?
private boolean initialized = false;
/**
* A marker interface for {@code KeyStore}
* {@link #load(KeyStore.LoadStoreParameter) load}
* and
* {@link #store(KeyStore.LoadStoreParameter) store}
* parameters.
*
* @since 1.5
*/
public static interface LoadStoreParameter {
/**
* Gets the parameter used to protect keystore data.
*
* @return the parameter used to protect keystore data, or null
*/
public ProtectionParameter getProtectionParameter();
}
/**
* A marker interface for keystore protection parameters.
*
* <p> The information stored in a {@code ProtectionParameter}
* object protects the contents of a keystore.
* For example, protection parameters may be used to check
* the integrity of keystore data, or to protect the
* confidentiality of sensitive keystore data
* (such as a {@code PrivateKey}).
*
* @since 1.5
*/
public static interface ProtectionParameter { }
/**
* A password-based implementation of {@code ProtectionParameter}.
*
* @since 1.5
*/
public static class PasswordProtection implements
ProtectionParameter, javax.security.auth.Destroyable {
private final char[] password;
private final String protectionAlgorithm;
private final AlgorithmParameterSpec protectionParameters;
private volatile boolean destroyed = false;
/**
* Creates a password parameter.
*
* <p> The specified {@code password} is cloned before it is stored
* in the new {@code PasswordProtection} object.
*
* @param password the password, which may be {@code null}
*/
public PasswordProtection(char[] password) {
this.password = (password == null) ? null : password.clone();
this.protectionAlgorithm = null;
this.protectionParameters = null;
}
/**
* Creates a password parameter and specifies the protection algorithm
* and associated parameters to use when encrypting a keystore entry.
* <p>
* The specified {@code password} is cloned before it is stored in the
* new {@code PasswordProtection} object.
*
* @param password the password, which may be {@code null}
* @param protectionAlgorithm the encryption algorithm name, for
* example, {@code PBEWithHmacSHA256AndAES_256}.
* See the Cipher section in the <a href=
* "{@docRoot}/../technotes/guides/security/StandardNames.html#Cipher">
* Java Cryptography Architecture Standard Algorithm Name
* Documentation</a>
* for information about standard encryption algorithm names.
* @param protectionParameters the encryption algorithm parameter
* specification, which may be {@code null}
* @exception NullPointerException if {@code protectionAlgorithm} is
* {@code null}
*
* @since 1.8
*/
public PasswordProtection(char[] password, String protectionAlgorithm,
AlgorithmParameterSpec protectionParameters) {
if (protectionAlgorithm == null) {
throw new NullPointerException("invalid null input");
}
this.password = (password == null) ? null : password.clone();
this.protectionAlgorithm = protectionAlgorithm;
this.protectionParameters = protectionParameters;
}
/**
* Gets the name of the protection algorithm.
* If none was set then the keystore provider will use its default
* protection algorithm. The name of the default protection algorithm
* for a given keystore type is set using the
* {@code 'keystore.<type>.keyProtectionAlgorithm'} security property.
* For example, the
* {@code keystore.PKCS12.keyProtectionAlgorithm} property stores the
* name of the default key protection algorithm used for PKCS12
* keystores. If the security property is not set, an
* implementation-specific algorithm will be used.
*
* @return the algorithm name, or {@code null} if none was set
*
* @since 1.8
*/
public String getProtectionAlgorithm() {
return protectionAlgorithm;
}
/**
* Gets the parameters supplied for the protection algorithm.
*
* @return the algorithm parameter specification, or {@code null},
* if none was set
*
* @since 1.8
*/
public AlgorithmParameterSpec getProtectionParameters() {
return protectionParameters;
}
/**
* Gets the password.
*
* <p>Note that this method returns a reference to the password.
* If a clone of the array is created it is the caller's
* responsibility to zero out the password information
* after it is no longer needed.
*
* @see #destroy()
* @return the password, which may be {@code null}
* @exception IllegalStateException if the password has
* been cleared (destroyed)
*/
public synchronized char[] getPassword() {
if (destroyed) {
throw new IllegalStateException("password has been cleared");
}
return password;
}
/**
* Clears the password.
*
* @exception DestroyFailedException if this method was unable
* to clear the password
*/
public synchronized void destroy() throws DestroyFailedException {
destroyed = true;
if (password != null) {
Arrays.fill(password, ' ');
}
}
/**
* Determines if password has been cleared.
*
* @return true if the password has been cleared, false otherwise
*/
public synchronized boolean isDestroyed() {
return destroyed;
}
}
/**
* A ProtectionParameter encapsulating a CallbackHandler.
*
* @since 1.5
*/
public static class CallbackHandlerProtection
implements ProtectionParameter {
private final CallbackHandler handler;
/**
* Constructs a new CallbackHandlerProtection from a
* CallbackHandler.
*
* @param handler the CallbackHandler
* @exception NullPointerException if handler is null
*/
public CallbackHandlerProtection(CallbackHandler handler) {
if (handler == null) {
throw new NullPointerException("handler must not be null");
}
this.handler = handler;
}
/**
* Returns the CallbackHandler.
*
* @return the CallbackHandler.
*/
public CallbackHandler getCallbackHandler() {
return handler;
}
}
/**
* A marker interface for {@code KeyStore} entry types.
*
* @since 1.5
*/
public static interface Entry {
/**
* Retrieves the attributes associated with an entry.
* <p>
* The default implementation returns an empty {@code Set}.
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
public default Set<Attribute> getAttributes() {
return Collections.<Attribute>emptySet();
}
/**
* An attribute associated with a keystore entry.
* It comprises a name and one or more values.
*
* @since 1.8
*/
public interface Attribute {
/**
* Returns the attribute's name.
*
* @return the attribute name
*/
public String getName();
/**
* Returns the attribute's value.
* Multi-valued attributes encode their values as a single string.
*
* @return the attribute value
*/
public String getValue();
}
}
/**
* A {@code KeyStore} entry that holds a {@code PrivateKey}
* and corresponding certificate chain.
*
* @since 1.5
*/
public static final class PrivateKeyEntry implements Entry {
private final PrivateKey privKey;
private final Certificate[] chain;
private final Set<Attribute> attributes;
/**
* Constructs a {@code PrivateKeyEntry} with a
* {@code PrivateKey} and corresponding certificate chain.
*
* <p> The specified {@code chain} is cloned before it is stored
* in the new {@code PrivateKeyEntry} object.
*
* @param privateKey the {@code PrivateKey}
* @param chain an array of {@code Certificate}s
* representing the certificate chain.
* The chain must be ordered and contain a
* {@code Certificate} at index 0
* corresponding to the private key.
*
* @exception NullPointerException if
* {@code privateKey} or {@code chain}
* is {@code null}
* @exception IllegalArgumentException if the specified chain has a
* length of 0, if the specified chain does not contain
* {@code Certificate}s of the same type,
* or if the {@code PrivateKey} algorithm
* does not match the algorithm of the {@code PublicKey}
* in the end entity {@code Certificate} (at index 0)
*/
public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain) {
this(privateKey, chain, Collections.<Attribute>emptySet());
}
/**
* Constructs a {@code PrivateKeyEntry} with a {@code PrivateKey} and
* corresponding certificate chain and associated entry attributes.
*
* <p> The specified {@code chain} and {@code attributes} are cloned
* before they are stored in the new {@code PrivateKeyEntry} object.
*
* @param privateKey the {@code PrivateKey}
* @param chain an array of {@code Certificate}s
* representing the certificate chain.
* The chain must be ordered and contain a
* {@code Certificate} at index 0
* corresponding to the private key.
* @param attributes the attributes
*
* @exception NullPointerException if {@code privateKey}, {@code chain}
* or {@code attributes} is {@code null}
* @exception IllegalArgumentException if the specified chain has a
* length of 0, if the specified chain does not contain
* {@code Certificate}s of the same type,
* or if the {@code PrivateKey} algorithm
* does not match the algorithm of the {@code PublicKey}
* in the end entity {@code Certificate} (at index 0)
*
* @since 1.8
*/
public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain,
Set<Attribute> attributes) {
if (privateKey == null || chain == null || attributes == null) {
throw new NullPointerException("invalid null input");
}
if (chain.length == 0) {
throw new IllegalArgumentException
("invalid zero-length input chain");
}
Certificate[] clonedChain = chain.clone();
String certType = clonedChain[0].getType();
for (int i = 1; i < clonedChain.length; i++) {
if (!certType.equals(clonedChain[i].getType())) {
throw new IllegalArgumentException
("chain does not contain certificates " +
"of the same type");
}
}
if (!privateKey.getAlgorithm().equals
(clonedChain[0].getPublicKey().getAlgorithm())) {
throw new IllegalArgumentException
("private key algorithm does not match " +
"algorithm of public key in end entity " +
"certificate (at index 0)");
}
this.privKey = privateKey;
if (clonedChain[0] instanceof X509Certificate &&
!(clonedChain instanceof X509Certificate[])) {
this.chain = new X509Certificate[clonedChain.length];
System.arraycopy(clonedChain, 0,
this.chain, 0, clonedChain.length);
} else {
this.chain = clonedChain;
}
this.attributes =
Collections.unmodifiableSet(new HashSet<>(attributes));
}
/**
* Gets the {@code PrivateKey} from this entry.
*
* @return the {@code PrivateKey} from this entry
*/
public PrivateKey getPrivateKey() {
return privKey;
}
/**
* Gets the {@code Certificate} chain from this entry.
*
* <p> The stored chain is cloned before being returned.
*
* @return an array of {@code Certificate}s corresponding
* to the certificate chain for the public key.
* If the certificates are of type X.509,
* the runtime type of the returned array is
* {@code X509Certificate[]}.
*/
public Certificate[] getCertificateChain() {
return chain.clone();
}
/**
* Gets the end entity {@code Certificate}
* from the certificate chain in this entry.
*
* @return the end entity {@code Certificate} (at index 0)
* from the certificate chain in this entry.
* If the certificate is of type X.509,
* the runtime type of the returned certificate is
* {@code X509Certificate}.
*/
public Certificate getCertificate() {
return chain[0];
}
/**
* Retrieves the attributes associated with an entry.
* <p>
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set<Attribute> getAttributes() {
return attributes;
}
/**
* Returns a string representation of this PrivateKeyEntry.
* @return a string representation of this PrivateKeyEntry.
*/
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Private key entry and certificate chain with "
+ chain.length + " elements:\r\n");
for (Certificate cert : chain) {
sb.append(cert);
sb.append("\r\n");
}
return sb.toString();
}
}
/**
* A {@code KeyStore} entry that holds a {@code SecretKey}.
*
* @since 1.5
*/
public static final class SecretKeyEntry implements Entry {
private final SecretKey sKey;
private final Set<Attribute> attributes;
/**
* Constructs a {@code SecretKeyEntry} with a
* {@code SecretKey}.
*
* @param secretKey the {@code SecretKey}
*
* @exception NullPointerException if {@code secretKey}
* is {@code null}
*/
public SecretKeyEntry(SecretKey secretKey) {
if (secretKey == null) {
throw new NullPointerException("invalid null input");
}
this.sKey = secretKey;
this.attributes = Collections.<Attribute>emptySet();
}
/**
* Constructs a {@code SecretKeyEntry} with a {@code SecretKey} and
* associated entry attributes.
*
* <p> The specified {@code attributes} is cloned before it is stored
* in the new {@code SecretKeyEntry} object.
*
* @param secretKey the {@code SecretKey}
* @param attributes the attributes
*
* @exception NullPointerException if {@code secretKey} or
* {@code attributes} is {@code null}
*
* @since 1.8
*/
public SecretKeyEntry(SecretKey secretKey, Set<Attribute> attributes) {
if (secretKey == null || attributes == null) {
throw new NullPointerException("invalid null input");
}
this.sKey = secretKey;
this.attributes =
Collections.unmodifiableSet(new HashSet<>(attributes));
}
/**
* Gets the {@code SecretKey} from this entry.
*
* @return the {@code SecretKey} from this entry
*/
public SecretKey getSecretKey() {
return sKey;
}
/**
* Retrieves the attributes associated with an entry.
* <p>
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set<Attribute> getAttributes() {
return attributes;
}
/**
* Returns a string representation of this SecretKeyEntry.
* @return a string representation of this SecretKeyEntry.
*/
public String toString() {
return "Secret key entry with algorithm " + sKey.getAlgorithm();
}
}
/**
* A {@code KeyStore} entry that holds a trusted
* {@code Certificate}.
*
* @since 1.5
*/
public static final class TrustedCertificateEntry implements Entry {
private final Certificate cert;
private final Set<Attribute> attributes;
/**
* Constructs a {@code TrustedCertificateEntry} with a
* trusted {@code Certificate}.
*
* @param trustedCert the trusted {@code Certificate}
*
* @exception NullPointerException if
* {@code trustedCert} is {@code null}
*/
public TrustedCertificateEntry(Certificate trustedCert) {
if (trustedCert == null) {
throw new NullPointerException("invalid null input");
}
this.cert = trustedCert;
this.attributes = Collections.<Attribute>emptySet();
}
/**
* Constructs a {@code TrustedCertificateEntry} with a
* trusted {@code Certificate} and associated entry attributes.
*
* <p> The specified {@code attributes} is cloned before it is stored
* in the new {@code TrustedCertificateEntry} object.
*
* @param trustedCert the trusted {@code Certificate}
* @param attributes the attributes
*
* @exception NullPointerException if {@code trustedCert} or
* {@code attributes} is {@code null}
*
* @since 1.8
*/
public TrustedCertificateEntry(Certificate trustedCert,
Set<Attribute> attributes) {
if (trustedCert == null || attributes == null) {
throw new NullPointerException("invalid null input");
}
this.cert = trustedCert;
this.attributes =
Collections.unmodifiableSet(new HashSet<>(attributes));
}
/**
* Gets the trusted {@code Certficate} from this entry.
*
* @return the trusted {@code Certificate} from this entry
*/
public Certificate getTrustedCertificate() {
return cert;
}
/**
* Retrieves the attributes associated with an entry.
* <p>
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set<Attribute> getAttributes() {
return attributes;
}
/**
* Returns a string representation of this TrustedCertificateEntry.
* @return a string representation of this TrustedCertificateEntry.
*/
public String toString() {
return "Trusted certificate entry:\r\n" + cert.toString();
}
}
/**
* Creates a KeyStore object of the given type, and encapsulates the given
* provider implementation (SPI object) in it.
*
* @param keyStoreSpi the provider implementation.
* @param provider the provider.
* @param type the keystore type.
*/
protected KeyStore(KeyStoreSpi keyStoreSpi, Provider provider, String type)
{
this.keyStoreSpi = keyStoreSpi;
this.provider = provider;
this.type = type;
// BEGIN Android-removed: this debugging mechanism is not supported in Android.
/*
if (!skipDebug && pdebug != null) {
pdebug.println("KeyStore." + type.toUpperCase() + " type from: " +
this.provider.getName());
}
*/
// END Android-removed: this debugging mechanism is not supported in Android.
}
/**
* Returns a keystore object of the specified type.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the first
* Provider that supports the specified type is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the type of keystore.
* See the KeyStore section in the <a href=
* "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
* Java Cryptography Architecture Standard Algorithm Name Documentation</a>
* for information about standard keystore types.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if no Provider supports a
* KeyStoreSpi implementation for the
* specified type.
*
* @see Provider
*/
public static KeyStore getInstance(String type)
throws KeyStoreException
{
try {
Object[] objs = Security.getImpl(type, "KeyStore", (String)null);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
} catch (NoSuchProviderException nspe) {
throw new KeyStoreException(type + " not found", nspe);
}
}
/**
* Returns a keystore object of the specified type.
*
* <p> A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the type of keystore.
* See the KeyStore section in the <a href=
* "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
* Java Cryptography Architecture Standard Algorithm Name Documentation</a>
* for information about standard keystore types.
*
* @param provider the name of the provider.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if a KeyStoreSpi
* implementation for the specified type is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static KeyStore getInstance(String type, String provider)
throws KeyStoreException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
}
/**
* Returns a keystore object of the specified type.
*
* <p> A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param type the type of keystore.
* See the KeyStore section in the <a href=
* "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
* Java Cryptography Architecture Standard Algorithm Name Documentation</a>
* for information about standard keystore types.
*
* @param provider the provider.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if KeyStoreSpi
* implementation for the specified type is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static KeyStore getInstance(String type, Provider provider)
throws KeyStoreException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
}
/**
* Returns the default keystore type as specified by the
* {@code keystore.type} security property, or the string
* {@literal "jks"} (acronym for {@literal "Java keystore"})
* if no such property exists.
*
* <p>The default keystore type can be used by applications that do not
* want to use a hard-coded keystore type when calling one of the
* {@code getInstance} methods, and want to provide a default keystore
* type in case a user does not specify its own.
*
* <p>The default keystore type can be changed by setting the value of the
* {@code keystore.type} security property to the desired keystore type.
*
* @return the default keystore type as specified by the
* {@code keystore.type} security property, or the string {@literal "jks"}
* if no such property exists.
* @see java.security.Security security properties
*/
public final static String getDefaultType() {
String kstype;
kstype = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return Security.getProperty(KEYSTORE_TYPE);
}
});
if (kstype == null) {
kstype = "jks";
}
return kstype;
}
/**
* Returns the provider of this keystore.
*
* @return the provider of this keystore.
*/
public final Provider getProvider()
{
return this.provider;
}
/**
* Returns the type of this keystore.
*
* @return the type of this keystore.
*/
public final String getType()
{
return this.type;
}
/**
* Returns the key associated with the given alias, using the given
* password to recover it. The key must have been associated with
* the alias by a call to {@code setKeyEntry},
* or by a call to {@code setEntry} with a
* {@code PrivateKeyEntry} or {@code SecretKeyEntry}.
*
* @param alias the alias name
* @param password the password for recovering the key
*
* @return the requested key, or null if the given alias does not exist
* or does not identify a key-related entry.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* key cannot be found
* @exception UnrecoverableKeyException if the key cannot be recovered
* (e.g., the given password is wrong).
*/
public final Key getKey(String alias, char[] password)
throws KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetKey(alias, password);
}
/**
* Returns the certificate chain associated with the given alias.
* The certificate chain must have been associated with the alias
* by a call to {@code setKeyEntry},
* or by a call to {@code setEntry} with a
* {@code PrivateKeyEntry}.
*
* @param alias the alias name
*
* @return the certificate chain (ordered with the user's certificate first
* followed by zero or more certificate authorities), or null if the given alias
* does not exist or does not contain a certificate chain
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Certificate[] getCertificateChain(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCertificateChain(alias);
}
/**
* Returns the certificate associated with the given alias.
*
* <p> If the given alias name identifies an entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the trusted certificate contained in that entry is returned.
*
* <p> If the given alias name identifies an entry
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the first element of the certificate chain in that entry
* is returned.
*
* @param alias the alias name
*
* @return the certificate, or null if the given alias does not exist or
* does not contain a certificate.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Certificate getCertificate(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCertificate(alias);
}
/**
* Returns the creation date of the entry identified by the given alias.
*
* @param alias the alias name
*
* @return the creation date of this entry, or null if the given alias does
* not exist
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Date getCreationDate(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCreationDate(alias);
}
/**
* Assigns the given key to the given alias, protecting it with the given
* password.
*
* <p>If the given key is of type {@code java.security.PrivateKey},
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
* <p>If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key to be associated with the alias
* @param password the password to protect the key
* @param chain the certificate chain for the corresponding public
* key (only required if the given key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), the given key cannot be protected, or this operation fails
* for some other reason
*/
public final void setKeyEntry(String alias, Key key, char[] password,
Certificate[] chain)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
if ((key instanceof PrivateKey) &&
(chain == null || chain.length == 0)) {
throw new IllegalArgumentException("Private key must be "
+ "accompanied by certificate "
+ "chain");
}
keyStoreSpi.engineSetKeyEntry(alias, key, password, chain);
}
/**
* Assigns the given key (that has already been protected) to the given
* alias.
*
* <p>If the protected key is of type
* {@code java.security.PrivateKey}, it must be accompanied by a
* certificate chain certifying the corresponding public key. If the
* underlying keystore implementation is of type {@code jks},
* {@code key} must be encoded as an
* {@code EncryptedPrivateKeyInfo} as defined in the PKCS #8 standard.
*
* <p>If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key (in protected format) to be associated with the alias
* @param chain the certificate chain for the corresponding public
* key (only useful if the protected key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), or if this operation fails for some other reason.
*/
public final void setKeyEntry(String alias, byte[] key,
Certificate[] chain)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetKeyEntry(alias, key, chain);
}
/**
* Assigns the given trusted certificate to the given alias.
*
* <p> If the given alias identifies an existing entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* the trusted certificate in the existing entry
* is overridden by the given certificate.
*
* @param alias the alias name
* @param cert the certificate
*
* @exception KeyStoreException if the keystore has not been initialized,
* or the given alias already exists and does not identify an
* entry containing a trusted certificate,
* or this operation fails for some other reason.
*/
public final void setCertificateEntry(String alias, Certificate cert)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetCertificateEntry(alias, cert);
}
/**
* Deletes the entry identified by the given alias from this keystore.
*
* @param alias the alias name
*
* @exception KeyStoreException if the keystore has not been initialized,
* or if the entry cannot be removed.
*/
public final void deleteEntry(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineDeleteEntry(alias);
}
/**
* Lists all the alias names of this keystore.
*
* @return enumeration of the alias names
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Enumeration<String> aliases()
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineAliases();
}
/**
* Checks if the given alias exists in this keystore.
*
* @param alias the alias name
*
* @return true if the alias exists, false otherwise
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final boolean containsAlias(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineContainsAlias(alias);
}
/**
* Retrieves the number of entries in this keystore.
*
* @return the number of entries in this keystore
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final int size()
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineSize();
}
/**
* Returns true if the entry identified by the given alias
* was created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry} or a {@code SecretKeyEntry}.
*
* @param alias the alias for the keystore entry to be checked
*
* @return true if the entry identified by the given alias is a
* key-related entry, false otherwise.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final boolean isKeyEntry(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineIsKeyEntry(alias);
}
/**
* Returns true if the entry identified by the given alias
* was created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry}.
*
* @param alias the alias for the keystore entry to be checked
*
* @return true if the entry identified by the given alias contains a
* trusted certificate, false otherwise.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final boolean isCertificateEntry(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineIsCertificateEntry(alias);
}
/**
* Returns the (alias) name of the first keystore entry whose certificate
* matches the given certificate.
*
* <p> This method attempts to match the given certificate with each
* keystore entry. If the entry being considered was
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the given certificate is compared to that entry's certificate.
*
* <p> If the entry being considered was
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the given certificate is compared to the first
* element of that entry's certificate chain.
*
* @param cert the certificate to match with.
*
* @return the alias name of the first entry with a matching certificate,
* or null if no such entry exists in this keystore.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final String getCertificateAlias(Certificate cert)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCertificateAlias(cert);
}
/**
* Stores this keystore to the given output stream, and protects its
* integrity with the given password.
*
* @param stream the output stream to which this keystore is written.
* @param password the password to generate the keystore integrity check
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*/
public final void store(OutputStream stream, char[] password)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineStore(stream, password);
}
/**
* Stores this keystore using the given {@code LoadStoreParameter}.
*
* @param param the {@code LoadStoreParameter}
* that specifies how to store the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code LoadStoreParameter}
* input is not recognized
* @exception KeyStoreException if the keystore has not been initialized
* (loaded)
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*
* @since 1.5
*/
public final void store(LoadStoreParameter param)
throws KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException {
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineStore(param);
}
/**
* Loads this KeyStore from the given input stream.
*
* <p>A password may be given to unlock the keystore
* (e.g. the keystore resides on a hardware token device),
* or to check the integrity of the keystore data.
* If a password is not given for integrity checking,
* then integrity checking is not performed.
*
* <p>In order to create an empty keystore, or if the keystore cannot
* be initialized from a stream, pass {@code null}
* as the {@code stream} argument.
*
* <p> Note that if this keystore has already been loaded, it is
* reinitialized and loaded again from the given input stream.
*
* @param stream the input stream from which the keystore is loaded,
* or {@code null}
* @param password the password used to check the integrity of
* the keystore, the password used to unlock the keystore,
* or {@code null}
*
* @exception IOException if there is an I/O or format problem with the
* keystore data, if a password is required but not given,
* or if the given password was incorrect. If the error is due to a
* wrong password, the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
public final void load(InputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException
{
keyStoreSpi.engineLoad(stream, password);
initialized = true;
}
/**
* Loads this keystore using the given {@code LoadStoreParameter}.
*
* <p> Note that if this KeyStore has already been loaded, it is
* reinitialized and loaded again from the given parameter.
*
* @param param the {@code LoadStoreParameter}
* that specifies how to load the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code LoadStoreParameter}
* input is not recognized
* @exception IOException if there is an I/O or format problem with the
* keystore data. If the error is due to an incorrect
* {@code ProtectionParameter} (e.g. wrong password)
* the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*
* @since 1.5
*/
public final void load(LoadStoreParameter param)
throws IOException, NoSuchAlgorithmException,
CertificateException {
keyStoreSpi.engineLoad(param);
initialized = true;
}
/**
* Gets a keystore {@code Entry} for the specified alias
* with the specified protection parameter.
*
* @param alias get the keystore {@code Entry} for this alias
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @return the keystore {@code Entry} for the specified alias,
* or {@code null} if there is no such entry
*
* @exception NullPointerException if
* {@code alias} is {@code null}
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* entry cannot be found
* @exception UnrecoverableEntryException if the specified
* {@code protParam} were insufficient or invalid
* @exception UnrecoverableKeyException if the entry is a
* {@code PrivateKeyEntry} or {@code SecretKeyEntry}
* and the specified {@code protParam} does not contain
* the information needed to recover the key (e.g. wrong password)
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
* @see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
*
* @since 1.5
*/
public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
}
/**
* Saves a keystore {@code Entry} under the specified alias.
* The protection parameter is used to protect the
* {@code Entry}.
*
* <p> If an entry already exists for the specified alias,
* it is overridden.
*
* @param alias save the keystore {@code Entry} under this alias
* @param entry the {@code Entry} to save
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @exception NullPointerException if
* {@code alias} or {@code entry}
* is {@code null}
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), or if this operation fails for some other reason
*
* @see #getEntry(String, KeyStore.ProtectionParameter)
*
* @since 1.5
*/
public final void setEntry(String alias, Entry entry,
ProtectionParameter protParam)
throws KeyStoreException {
if (alias == null || entry == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetEntry(alias, entry, protParam);
}
/**
* Determines if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the specified
* {@code entryClass}.
*
* @param alias the alias name
* @param entryClass the entry class
*
* @return true if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the
* specified {@code entryClass}, false otherwise
*
* @exception NullPointerException if
* {@code alias} or {@code entryClass}
* is {@code null}
* @exception KeyStoreException if the keystore has not been
* initialized (loaded)
*
* @since 1.5
*/
public final boolean
entryInstanceOf(String alias,
Class<? extends KeyStore.Entry> entryClass)
throws KeyStoreException
{
if (alias == null || entryClass == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineEntryInstanceOf(alias, entryClass);
}
/**
* A description of a to-be-instantiated KeyStore object.
*
* <p>An instance of this class encapsulates the information needed to
* instantiate and initialize a KeyStore object. That process is
* triggered when the {@linkplain #getKeyStore} method is called.
*
* <p>This makes it possible to decouple configuration from KeyStore
* object creation and e.g. delay a password prompt until it is
* needed.
*
* @see KeyStore
* @see javax.net.ssl.KeyStoreBuilderParameters
* @since 1.5
*/
public static abstract class Builder {
// maximum times to try the callbackhandler if the password is wrong
static final int MAX_CALLBACK_TRIES = 3;
/**
* Construct a new Builder.
*/
protected Builder() {
// empty
}
/**
* Returns the KeyStore described by this object.
*
* @return the {@code KeyStore} described by this object
* @exception KeyStoreException if an error occurred during the
* operation, for example if the KeyStore could not be
* instantiated or loaded
*/
public abstract KeyStore getKeyStore() throws KeyStoreException;
/**
* Returns the ProtectionParameters that should be used to obtain
* the {@link KeyStore.Entry Entry} with the given alias.
* The {@code getKeyStore} method must be invoked before this
* method may be called.
*
* @return the ProtectionParameters that should be used to obtain
* the {@link KeyStore.Entry Entry} with the given alias.
* @param alias the alias of the KeyStore entry
* @throws NullPointerException if alias is null
* @throws KeyStoreException if an error occurred during the
* operation
* @throws IllegalStateException if the getKeyStore method has
* not been invoked prior to calling this method
*/
public abstract ProtectionParameter getProtectionParameter(String alias)
throws KeyStoreException;
/**
* Returns a new Builder that encapsulates the given KeyStore.
* The {@linkplain #getKeyStore} method of the returned object
* will return {@code keyStore}, the {@linkplain
* #getProtectionParameter getProtectionParameter()} method will
* return {@code protectionParameters}.
*
* <p> This is useful if an existing KeyStore object needs to be
* used with Builder-based APIs.
*
* @return a new Builder object
* @param keyStore the KeyStore to be encapsulated
* @param protectionParameter the ProtectionParameter used to
* protect the KeyStore entries
* @throws NullPointerException if keyStore or
* protectionParameters is null
* @throws IllegalArgumentException if the keyStore has not been
* initialized
*/
public static Builder newInstance(final KeyStore keyStore,
final ProtectionParameter protectionParameter) {
if ((keyStore == null) || (protectionParameter == null)) {
throw new NullPointerException();
}
if (keyStore.initialized == false) {
throw new IllegalArgumentException("KeyStore not initialized");
}
return new Builder() {
private volatile boolean getCalled;
public KeyStore getKeyStore() {
getCalled = true;
return keyStore;
}
public ProtectionParameter getProtectionParameter(String alias)
{
if (alias == null) {
throw new NullPointerException();
}
if (getCalled == false) {
throw new IllegalStateException
("getKeyStore() must be called first");
}
return protectionParameter;
}
};
}
/**
* Returns a new Builder object.
*
* <p>The first call to the {@link #getKeyStore} method on the returned
* builder will create a KeyStore of type {@code type} and call
* its {@link KeyStore#load load()} method.
* The {@code inputStream} argument is constructed from
* {@code file}.
* If {@code protection} is a
* {@code PasswordProtection}, the password is obtained by
* calling the {@code getPassword} method.
* Otherwise, if {@code protection} is a
* {@code CallbackHandlerProtection}, the password is obtained
* by invoking the CallbackHandler.
*
* <p>Subsequent calls to {@link #getKeyStore} return the same object
* as the initial call. If the initial call to failed with a
* KeyStoreException, subsequent calls also throw a
* KeyStoreException.
*
* <p>The KeyStore is instantiated from {@code provider} if
* non-null. Otherwise, all installed providers are searched.
*
* <p>Calls to {@link #getProtectionParameter getProtectionParameter()}
* will return a {@link KeyStore.PasswordProtection PasswordProtection}
* object encapsulating the password that was used to invoke the
* {@code load} method.
*
* <p><em>Note</em> that the {@link #getKeyStore} method is executed
* within the {@link AccessControlContext} of the code invoking this
* method.
*
* @return a new Builder object
* @param type the type of KeyStore to be constructed
* @param provider the provider from which the KeyStore is to
* be instantiated (or null)
* @param file the File that contains the KeyStore data
* @param protection the ProtectionParameter securing the KeyStore data
* @throws NullPointerException if type, file or protection is null
* @throws IllegalArgumentException if protection is not an instance
* of either PasswordProtection or CallbackHandlerProtection; or
* if file does not exist or does not refer to a normal file
*/
public static Builder newInstance(String type, Provider provider,
File file, ProtectionParameter protection) {
if ((type == null) || (file == null) || (protection == null)) {
throw new NullPointerException();
}
if ((protection instanceof PasswordProtection == false) &&
(protection instanceof CallbackHandlerProtection == false)) {
throw new IllegalArgumentException
("Protection must be PasswordProtection or " +
"CallbackHandlerProtection");
}
if (file.isFile() == false) {
throw new IllegalArgumentException
("File does not exist or it does not refer " +
"to a normal file: " + file);
}
return new FileBuilder(type, provider, file, protection,
AccessController.getContext());
}
private static final class FileBuilder extends Builder {
private final String type;
private final Provider provider;
private final File file;
private ProtectionParameter protection;
private ProtectionParameter keyProtection;
private final AccessControlContext context;
private KeyStore keyStore;
private Throwable oldException;
FileBuilder(String type, Provider provider, File file,
ProtectionParameter protection,
AccessControlContext context) {
this.type = type;
this.provider = provider;
this.file = file;
this.protection = protection;
this.context = context;
}
public synchronized KeyStore getKeyStore() throws KeyStoreException
{
if (keyStore != null) {
return keyStore;
}
if (oldException != null) {
throw new KeyStoreException
("Previous KeyStore instantiation failed",
oldException);
}
PrivilegedExceptionAction<KeyStore> action =
new PrivilegedExceptionAction<KeyStore>() {
public KeyStore run() throws Exception {
if (protection instanceof CallbackHandlerProtection == false) {
return run0();
}
// when using a CallbackHandler,
// reprompt if the password is wrong
int tries = 0;
while (true) {
tries++;
try {
return run0();
} catch (IOException e) {
if ((tries < MAX_CALLBACK_TRIES)
&& (e.getCause() instanceof UnrecoverableKeyException)) {
continue;
}
throw e;
}
}
}
public KeyStore run0() throws Exception {
KeyStore ks;
if (provider == null) {
ks = KeyStore.getInstance(type);
} else {
ks = KeyStore.getInstance(type, provider);
}
InputStream in = null;
char[] password = null;
try {
in = new FileInputStream(file);
if (protection instanceof PasswordProtection) {
password =
((PasswordProtection)protection).getPassword();
keyProtection = protection;
} else {
CallbackHandler handler =
((CallbackHandlerProtection)protection)
.getCallbackHandler();
PasswordCallback callback = new PasswordCallback
("Password for keystore " + file.getName(),
false);
handler.handle(new Callback[] {callback});
password = callback.getPassword();
if (password == null) {
throw new KeyStoreException("No password" +
" provided");
}
callback.clearPassword();
keyProtection = new PasswordProtection(password);
}
ks.load(in, password);
return ks;
} finally {
if (in != null) {
in.close();
}
}
}
};
try {
keyStore = AccessController.doPrivileged(action, context);
return keyStore;
} catch (PrivilegedActionException e) {
oldException = e.getCause();
throw new KeyStoreException
("KeyStore instantiation failed", oldException);
}
}
public synchronized ProtectionParameter
getProtectionParameter(String alias) {
if (alias == null) {
throw new NullPointerException();
}
if (keyStore == null) {
throw new IllegalStateException
("getKeyStore() must be called first");
}
return keyProtection;
}
}
/**
* Returns a new Builder object.
*
* <p>Each call to the {@link #getKeyStore} method on the returned
* builder will return a new KeyStore object of type {@code type}.
* Its {@link KeyStore#load(KeyStore.LoadStoreParameter) load()}
* method is invoked using a
* {@code LoadStoreParameter} that encapsulates
* {@code protection}.
*
* <p>The KeyStore is instantiated from {@code provider} if
* non-null. Otherwise, all installed providers are searched.
*
* <p>Calls to {@link #getProtectionParameter getProtectionParameter()}
* will return {@code protection}.
*
* <p><em>Note</em> that the {@link #getKeyStore} method is executed
* within the {@link AccessControlContext} of the code invoking this
* method.
*
* @return a new Builder object
* @param type the type of KeyStore to be constructed
* @param provider the provider from which the KeyStore is to
* be instantiated (or null)
* @param protection the ProtectionParameter securing the Keystore
* @throws NullPointerException if type or protection is null
*/
public static Builder newInstance(final String type,
final Provider provider, final ProtectionParameter protection) {
if ((type == null) || (protection == null)) {
throw new NullPointerException();
}
final AccessControlContext context = AccessController.getContext();
return new Builder() {
private volatile boolean getCalled;
private IOException oldException;
private final PrivilegedExceptionAction<KeyStore> action
= new PrivilegedExceptionAction<KeyStore>() {
public KeyStore run() throws Exception {
KeyStore ks;
if (provider == null) {
ks = KeyStore.getInstance(type);
} else {
ks = KeyStore.getInstance(type, provider);
}
LoadStoreParameter param = new SimpleLoadStoreParameter(protection);
if (protection instanceof CallbackHandlerProtection == false) {
ks.load(param);
} else {
// when using a CallbackHandler,
// reprompt if the password is wrong
int tries = 0;
while (true) {
tries++;
try {
ks.load(param);
break;
} catch (IOException e) {
if (e.getCause() instanceof UnrecoverableKeyException) {
if (tries < MAX_CALLBACK_TRIES) {
continue;
} else {
oldException = e;
}
}
throw e;
}
}
}
getCalled = true;
return ks;
}
};
public synchronized KeyStore getKeyStore()
throws KeyStoreException {
if (oldException != null) {
throw new KeyStoreException
("Previous KeyStore instantiation failed",
oldException);
}
try {
return AccessController.doPrivileged(action, context);
} catch (PrivilegedActionException e) {
Throwable cause = e.getCause();
throw new KeyStoreException
("KeyStore instantiation failed", cause);
}
}
public ProtectionParameter getProtectionParameter(String alias)
{
if (alias == null) {
throw new NullPointerException();
}
if (getCalled == false) {
throw new IllegalStateException
("getKeyStore() must be called first");
}
return protection;
}
};
}
}
static class SimpleLoadStoreParameter implements LoadStoreParameter {
private final ProtectionParameter protection;
SimpleLoadStoreParameter(ProtectionParameter protection) {
this.protection = protection;
}
public ProtectionParameter getProtectionParameter() {
return protection;
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/lang/management/ThreadMXBean/SynchronizerDeadlock.java | 5419 | /*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @summary SynchronizerDeadlock creates threads that are deadlocked
* waiting for JSR-166 synchronizers.
* @author Mandy Chung
* @build Barrier
*/
import java.lang.management.*;
import java.util.*;
import java.util.concurrent.locks.*;
public class SynchronizerDeadlock {
private Lock a = new ReentrantLock();
private Lock b = new ReentrantLock();
private Lock c = new ReentrantLock();
private final int EXPECTED_THREADS = 3;
private Thread[] dThreads = new Thread[EXPECTED_THREADS];
private Barrier go = new Barrier(1);
private Barrier barr = new Barrier(EXPECTED_THREADS);
public SynchronizerDeadlock() {
dThreads[0] = new DeadlockingThread("Deadlock-Thread-1", a, b);
dThreads[1] = new DeadlockingThread("Deadlock-Thread-2", b, c);
dThreads[2] = new DeadlockingThread("Deadlock-Thread-3", c, a);
// make them daemon threads so that the test will exit
for (int i = 0; i < EXPECTED_THREADS; i++) {
dThreads[i].setDaemon(true);
dThreads[i].start();
}
}
void goDeadlock() {
// Wait until all threads have started
barr.await();
// reset for later signals
barr.set(EXPECTED_THREADS);
while (go.getWaiterCount() != EXPECTED_THREADS) {
synchronized(this) {
try {
wait(100);
} catch (InterruptedException e) {
// ignore
}
}
}
// sleep a little so that all threads are blocked before notified.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
go.signal();
}
void waitUntilDeadlock() {
barr.await();
for (int i=0; i < 100; i++) {
// sleep a little while to wait until threads are blocked.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
boolean retry = false;
for (Thread t: dThreads) {
if (t.getState() == Thread.State.RUNNABLE) {
retry = true;
break;
}
}
if (!retry) {
break;
}
}
}
private class DeadlockingThread extends Thread {
private final Lock lock1;
private final Lock lock2;
DeadlockingThread(String name, Lock lock1, Lock lock2) {
super(name);
this.lock1 = lock1;
this.lock2 = lock2;
}
public void run() {
f();
}
private void f() {
lock1.lock();
try {
barr.signal();
go.await();
g();
} finally {
lock1.unlock();
}
}
private void g() {
barr.signal();
lock2.lock();
throw new RuntimeException("should not reach here.");
}
}
void checkResult(long[] threads) {
if (threads.length != EXPECTED_THREADS) {
ThreadDump.threadDump();
throw new RuntimeException("Expected to have " +
EXPECTED_THREADS + " to be in the deadlock list");
}
boolean[] found = new boolean[EXPECTED_THREADS];
for (int i = 0; i < threads.length; i++) {
for (int j = 0; j < dThreads.length; j++) {
if (dThreads[j].getId() == threads[i]) {
found[j] = true;
}
}
}
boolean ok = true;
for (int j = 0; j < found.length; j++) {
ok = ok && found[j];
}
if (!ok) {
System.out.print("Returned result is [");
for (int j = 0; j < threads.length; j++) {
System.out.print(threads[j] + " ");
}
System.out.println("]");
System.out.print("Expected result is [");
for (int j = 0; j < threads.length; j++) {
System.out.print(dThreads[j] + " ");
}
System.out.println("]");
throw new RuntimeException("Unexpected result returned " +
" by findMonitorDeadlockedThreads method.");
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/sun/swing/table/DefaultTableCellHeaderRenderer.java | 7302 | /*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.swing.table;
import java.awt.Component;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.*;
import javax.swing.plaf.UIResource;
import javax.swing.border.Border;
import javax.swing.table.*;
import sun.swing.DefaultLookup;
public class DefaultTableCellHeaderRenderer extends DefaultTableCellRenderer
implements UIResource {
private boolean horizontalTextPositionSet;
private Icon sortArrow;
private EmptyIcon emptyIcon = new EmptyIcon();
public DefaultTableCellHeaderRenderer() {
setHorizontalAlignment(JLabel.CENTER);
}
public void setHorizontalTextPosition(int textPosition) {
horizontalTextPositionSet = true;
super.setHorizontalTextPosition(textPosition);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Icon sortIcon = null;
boolean isPaintingForPrint = false;
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
Color fgColor = null;
Color bgColor = null;
if (hasFocus) {
fgColor = DefaultLookup.getColor(this, ui, "TableHeader.focusCellForeground");
bgColor = DefaultLookup.getColor(this, ui, "TableHeader.focusCellBackground");
}
if (fgColor == null) {
fgColor = header.getForeground();
}
if (bgColor == null) {
bgColor = header.getBackground();
}
setForeground(fgColor);
setBackground(bgColor);
setFont(header.getFont());
isPaintingForPrint = header.isPaintingForPrint();
}
if (!isPaintingForPrint && table.getRowSorter() != null) {
if (!horizontalTextPositionSet) {
// There is a row sorter, and the developer hasn't
// set a text position, change to leading.
setHorizontalTextPosition(JLabel.LEADING);
}
SortOrder sortOrder = getColumnSortOrder(table, column);
if (sortOrder != null) {
switch(sortOrder) {
case ASCENDING:
sortIcon = DefaultLookup.getIcon(
this, ui, "Table.ascendingSortIcon");
break;
case DESCENDING:
sortIcon = DefaultLookup.getIcon(
this, ui, "Table.descendingSortIcon");
break;
case UNSORTED:
sortIcon = DefaultLookup.getIcon(
this, ui, "Table.naturalSortIcon");
break;
}
}
}
}
setText(value == null ? "" : value.toString());
setIcon(sortIcon);
sortArrow = sortIcon;
Border border = null;
if (hasFocus) {
border = DefaultLookup.getBorder(this, ui, "TableHeader.focusCellBorder");
}
if (border == null) {
border = DefaultLookup.getBorder(this, ui, "TableHeader.cellBorder");
}
setBorder(border);
return this;
}
public static SortOrder getColumnSortOrder(JTable table, int column) {
SortOrder rv = null;
if (table.getRowSorter() == null) {
return rv;
}
java.util.List<? extends RowSorter.SortKey> sortKeys =
table.getRowSorter().getSortKeys();
if (sortKeys.size() > 0 && sortKeys.get(0).getColumn() ==
table.convertColumnIndexToModel(column)) {
rv = sortKeys.get(0).getSortOrder();
}
return rv;
}
@Override
public void paintComponent(Graphics g) {
boolean b = DefaultLookup.getBoolean(this, ui,
"TableHeader.rightAlignSortArrow", false);
if (b && sortArrow != null) {
//emptyIcon is used so that if the text in the header is right
//aligned, or if the column is too narrow, then the text will
//be sized appropriately to make room for the icon that is about
//to be painted manually here.
emptyIcon.width = sortArrow.getIconWidth();
emptyIcon.height = sortArrow.getIconHeight();
setIcon(emptyIcon);
super.paintComponent(g);
Point position = computeIconPosition(g);
sortArrow.paintIcon(this, g, position.x, position.y);
} else {
super.paintComponent(g);
}
}
private Point computeIconPosition(Graphics g) {
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle viewR = new Rectangle();
Rectangle textR = new Rectangle();
Rectangle iconR = new Rectangle();
Insets i = getInsets();
viewR.x = i.left;
viewR.y = i.top;
viewR.width = getWidth() - (i.left + i.right);
viewR.height = getHeight() - (i.top + i.bottom);
SwingUtilities.layoutCompoundLabel(
this,
fontMetrics,
getText(),
sortArrow,
getVerticalAlignment(),
getHorizontalAlignment(),
getVerticalTextPosition(),
getHorizontalTextPosition(),
viewR,
iconR,
textR,
getIconTextGap());
int x = getWidth() - i.right - sortArrow.getIconWidth();
int y = iconR.y;
return new Point(x, y);
}
private class EmptyIcon implements Icon {
int width = 0;
int height = 0;
public void paintIcon(Component c, Graphics g, int x, int y) {}
public int getIconWidth() { return width; }
public int getIconHeight() { return height; }
}
}
| gpl-2.0 |
ivmai/JCGO | sunawt/fix/javax/swing/plaf/basic/BasicSpinnerUI.java | 33804 | /*
* This file is modified by Ivan Maidanski <ivmai@ivmaisoft.com>
* Project name: JCGO-SUNAWT (http://www.ivmaisoft.com/jcgo/)
*/
/*
* @(#)BasicSpinnerUI.java 1.18 06/08/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package javax.swing.plaf.basic;
import java.awt.*;
import java.awt.event.*;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
import java.beans.*;
import java.text.*;
import java.util.*;
/**
* The default Spinner UI delegate.
*
* @version 1.15 01/23/03
* @author Hans Muller
* @since 1.4
*/
public class BasicSpinnerUI extends SpinnerUI
{
/**
* The spinner that we're a UI delegate for. Initialized by
* the <code>installUI</code> method, and reset to null
* by <code>uninstallUI</code>.
*
* @see #installUI
* @see #uninstallUI
*/
protected JSpinner spinner;
/**
* The <code>PropertyChangeListener</code> that's added to the
* <code>JSpinner</code> itself. This listener is created by the
* <code>createPropertyChangeListener</code> method, added by the
* <code>installListeners</code> method, and removed by the
* <code>uninstallListeners</code> method.
* <p>
* One instance of this listener is shared by all JSpinners.
*
* @see #createPropertyChangeListener
* @see #installListeners
* @see #uninstallListeners
*/
private static final PropertyChangeListener propertyChangeListener = new PropertyChangeHandler();
/**
* The mouse/action listeners that are added to the spinner's
* arrow buttons. These listeners are shared by all
* spinner arrow buttons.
*
* @see #createNextButton
* @see #createPreviousButton
*/
private static ArrowButtonHandler nextButtonHandler;
private static ArrowButtonHandler previousButtonHandler;
private static synchronized void initButtonHandlers() {
if (nextButtonHandler == null)
nextButtonHandler = new ArrowButtonHandler("increment", true);
if (previousButtonHandler == null)
previousButtonHandler = new ArrowButtonHandler("decrement", false);
}
/**
* Returns a new instance of BasicSpinnerUI. SpinnerListUI
* delegates are allocated one per JSpinner.
*
* @param c the JSpinner (not used)
* @see ComponentUI#createUI
* @return a new BasicSpinnerUI object
*/
public static ComponentUI createUI(JComponent c) {
return new BasicSpinnerUI();
}
public BasicSpinnerUI() {
initButtonHandlers();
}
private void maybeAdd(Component c, String s) {
if (c != null) {
spinner.add(c, s);
}
}
/**
* Calls <code>installDefaults</code>, <code>installListeners</code>,
* and then adds the components returned by <code>createNextButton</code>,
* <code>createPreviousButton</code>, and <code>createEditor</code>.
*
* @param c the JSpinner
* @see #installDefaults
* @see #installListeners
* @see #createNextButton
* @see #createPreviousButton
* @see #createEditor
*/
public void installUI(JComponent c) {
this.spinner = (JSpinner)c;
installDefaults();
installListeners();
maybeAdd(createNextButton(), "Next");
maybeAdd(createPreviousButton(), "Previous");
maybeAdd(createEditor(), "Editor");
updateEnabledState();
installKeyboardActions();
}
/**
* Calls <code>uninstallDefaults</code>, <code>uninstallListeners</code>,
* and then removes all of the spinners children.
*
* @param c the JSpinner (not used)
*/
public void uninstallUI(JComponent c) {
uninstallDefaults();
uninstallListeners();
this.spinner = null;
c.removeAll();
}
/**
* Initializes <code>propertyChangeListener</code> with
* a shared object that delegates interesting PropertyChangeEvents
* to protected methods.
* <p>
* This method is called by <code>installUI</code>.
*
* @see #replaceEditor
* @see #uninstallListeners
*/
protected void installListeners() {
JComponent editor = spinner.getEditor();
if (editor != null && editor instanceof JSpinner.DefaultEditor) {
JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField();
if (tf != null) {
tf.removeFocusListener(nextButtonHandler);
tf.addFocusListener(nextButtonHandler);
tf.removeFocusListener(previousButtonHandler);
tf.addFocusListener(previousButtonHandler);
}
}
spinner.addPropertyChangeListener(propertyChangeListener);
}
/**
* Removes the <code>propertyChangeListener</code> added
* by installListeners.
* <p>
* This method is called by <code>uninstallUI</code>.
*
* @see #installListeners
*/
protected void uninstallListeners() {
spinner.removePropertyChangeListener(propertyChangeListener);
JComponent editor = spinner.getEditor();
removeEditorBorderListener(editor);
if (editor instanceof JSpinner.DefaultEditor) {
JTextField tf = ((JSpinner.DefaultEditor)editor).getTextField();
if (tf != null) {
tf.removeFocusListener(nextButtonHandler);
tf.removeFocusListener(previousButtonHandler);
}
}
}
/**
* Initialize the <code>JSpinner</code> <code>border</code>,
* <code>foreground</code>, and <code>background</code>, properties
* based on the corresponding "Spinner.*" properties from defaults table.
* The <code>JSpinners</code> layout is set to the value returned by
* <code>createLayout</code>. This method is called by <code>installUI</code>.
*
* @see #uninstallDefaults
* @see #installUI
* @see #createLayout
* @see LookAndFeel#installBorder
* @see LookAndFeel#installColors
*/
protected void installDefaults() {
spinner.setLayout(createLayout());
LookAndFeel.installBorder(spinner, "Spinner.border");
LookAndFeel.installColorsAndFont(spinner, "Spinner.background", "Spinner.foreground", "Spinner.font");
}
/**
* Sets the <code>JSpinner's</code> layout manager to null. This
* method is called by <code>uninstallUI</code>.
*
* @see #installDefaults
* @see #uninstallUI
*/
protected void uninstallDefaults() {
spinner.setLayout(null);
}
/**
* Create a <code>LayoutManager</code> that manages the <code>editor</code>,
* <code>nextButton</code>, and <code>previousButton</code>
* children of the JSpinner. These three children must be
* added with a constraint that identifies their role:
* "Editor", "Next", and "Previous". The default layout manager
* can handle the absence of any of these children.
*
* @return a LayoutManager for the editor, next button, and previous button.
* @see #createNextButton
* @see #createPreviousButton
* @see #createEditor
*/
protected LayoutManager createLayout() {
return new SpinnerLayout();
}
/**
* Create a <code>PropertyChangeListener</code> that can be
* added to the JSpinner itself. Typically, this listener
* will call replaceEditor when the "editor" property changes,
* since it's the <code>SpinnerUI's</code> responsibility to
* add the editor to the JSpinner (and remove the old one).
* This method is called by <code>installListeners</code>.
*
* @return A PropertyChangeListener for the JSpinner itself
* @see #installListeners
*/
protected PropertyChangeListener createPropertyChangeListener() {
return new PropertyChangeHandler();
}
/**
* Create a component that will replace the spinner models value
* with the object returned by <code>spinner.getPreviousValue</code>.
* By default the <code>previousButton</code> is a JButton
* who's <code>ActionListener</code> updates it's <code>JSpinner</code>
* ancestors model. If a previousButton isn't needed (in a subclass)
* then override this method to return null.
*
* @return a component that will replace the spinners model with the
* next value in the sequence, or null
* @see #installUI
* @see #createNextButton
*/
protected Component createPreviousButton() {
return createArrowButton(SwingConstants.SOUTH, previousButtonHandler);
}
/**
* Create a component that will replace the spinner models value
* with the object returned by <code>spinner.getNextValue</code>.
* By default the <code>nextButton</code> is a JButton
* who's <code>ActionListener</code> updates it's <code>JSpinner</code>
* ancestors model. If a nextButton isn't needed (in a subclass)
* then override this method to return null.
*
* @return a component that will replace the spinners model with the
* next value in the sequence, or null
* @see #installUI
* @see #createPreviousButton
*/
protected Component createNextButton() {
return createArrowButton(SwingConstants.NORTH, nextButtonHandler);
}
private Component createArrowButton(int direction, ArrowButtonHandler handler) {
JButton b = new BasicArrowButton(direction);
b.addActionListener(handler);
b.addMouseListener(handler);
Border buttonBorder = UIManager.getBorder("Spinner.arrowButtonBorder");
if (buttonBorder instanceof UIResource) {
// Wrap the border to avoid having the UIResource be replaced by
// the ButtonUI. This is the opposite of using BorderUIResource.
b.setBorder(new CompoundBorder(buttonBorder, null));
} else {
b.setBorder(buttonBorder);
}
return b;
}
/**
* This method is called by installUI to get the editor component
* of the <code>JSpinner</code>. By default it just returns
* <code>JSpinner.getEditor()</code>. Subclasses can override
* <code>createEditor</code> to return a component that contains
* the spinner's editor or null, if they're going to handle adding
* the editor to the <code>JSpinner</code> in an
* <code>installUI</code> override.
* <p>
* Typically this method would be overridden to wrap the editor
* with a container with a custom border, since one can't assume
* that the editors border can be set directly.
* <p>
* The <code>replaceEditor</code> method is called when the spinners
* editor is changed with <code>JSpinner.setEditor</code>. If you've
* overriden this method, then you'll probably want to override
* <code>replaceEditor</code> as well.
*
* @return the JSpinners editor JComponent, spinner.getEditor() by default
* @see #installUI
* @see #replaceEditor
* @see JSpinner#getEditor
*/
protected JComponent createEditor() {
JComponent editor = spinner.getEditor();
maybeRemoveEditorBorder(editor);
installEditorBorderListener(editor);
return editor;
}
/**
* Called by the <code>PropertyChangeListener</code> when the
* <code>JSpinner</code> editor property changes. It's the responsibility
* of this method to remove the old editor and add the new one. By
* default this operation is just:
* <pre>
* spinner.remove(oldEditor);
* spinner.add(newEditor, "Editor");
* </pre>
* The implementation of <code>replaceEditor</code> should be coordinated
* with the <code>createEditor</code> method.
*
* @see #createEditor
* @see #createPropertyChangeListener
*/
protected void replaceEditor(JComponent oldEditor, JComponent newEditor) {
spinner.remove(oldEditor);
maybeRemoveEditorBorder(newEditor);
installEditorBorderListener(newEditor);
spinner.add(newEditor, "Editor");
}
/**
* Remove the border around the inner editor component for LaFs
* that install an outside border around the spinner,
*/
private void maybeRemoveEditorBorder(JComponent editor) {
if (!UIManager.getBoolean("Spinner.editorBorderPainted")) {
if (editor instanceof JPanel &&
editor.getBorder() == null &&
editor.getComponentCount() > 0) {
editor = (JComponent)editor.getComponent(0);
}
if (editor != null && editor.getBorder() instanceof UIResource) {
editor.setBorder(null);
}
}
}
/**
* Remove the border around the inner editor component for LaFs
* that install an outside border around the spinner,
*/
private void installEditorBorderListener(JComponent editor) {
if (!UIManager.getBoolean("Spinner.editorBorderPainted")) {
if (editor instanceof JPanel &&
editor.getBorder() == null &&
editor.getComponentCount() > 0) {
editor = (JComponent)editor.getComponent(0);
}
if (editor != null &&
(editor.getBorder() == null ||
editor.getBorder() instanceof UIResource)) {
editor.addPropertyChangeListener(propertyChangeListener);
}
}
}
private void removeEditorBorderListener(JComponent editor) {
if (!UIManager.getBoolean("Spinner.editorBorderPainted")) {
if (editor instanceof JPanel &&
editor.getComponentCount() > 0) {
editor = (JComponent)editor.getComponent(0);
}
if (editor != null) {
editor.removePropertyChangeListener(propertyChangeListener);
}
}
}
/**
* Updates the enabled state of the children Components based on the
* enabled state of the <code>JSpinner</code>.
*/
private void updateEnabledState() {
updateEnabledState(spinner, spinner.isEnabled());
}
/**
* Recursively updates the enabled state of the child
* <code>Component</code>s of <code>c</code>.
*/
private void updateEnabledState(Container c, boolean enabled) {
for (int counter = c.getComponentCount() - 1; counter >= 0;counter--) {
Component child = c.getComponent(counter);
child.setEnabled(enabled);
if (child instanceof Container) {
updateEnabledState((Container)child, enabled);
}
}
}
/**
* Installs the KeyboardActions onto the JSpinner.
*/
private void installKeyboardActions() {
InputMap iMap = getInputMap(JComponent.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
SwingUtilities.replaceUIInputMap(spinner, JComponent.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
iMap);
SwingUtilities.replaceUIActionMap(spinner, getActionMap());
}
/**
* Returns the InputMap to install for <code>condition</code>.
*/
private InputMap getInputMap(int condition) {
if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) {
return (InputMap)UIManager.get("Spinner.ancestorInputMap");
}
return null;
}
private ActionMap getActionMap() {
ActionMap map = (ActionMap)UIManager.get("Spinner.actionMap");
if (map == null) {
map = createActionMap();
if (map != null) {
UIManager.getLookAndFeelDefaults().put("Spinner.actionMap",
map);
}
}
return map;
}
private ActionMap createActionMap() {
ActionMap map = new ActionMapUIResource();
map.put("increment", nextButtonHandler);
map.put("decrement", previousButtonHandler);
return map;
}
/**
* A handler for spinner arrow button mouse and action events. When
* a left mouse pressed event occurs we look up the (enabled) spinner
* that's the source of the event and start the autorepeat timer. The
* timer fires action events until any button is released at which
* point the timer is stopped and the reference to the spinner cleared.
* The timer doesn't start until after a 300ms delay, so often the
* source of the initial (and final) action event is just the button
* logic for mouse released - which means that we're relying on the fact
* that our mouse listener runs after the buttons mouse listener.
* <p>
* Note that one instance of this handler is shared by all slider previous
* arrow buttons and likewise for all of the next buttons,
* so it doesn't have any state that persists beyond the limits
* of a single button pressed/released gesture.
*/
private static class ArrowButtonHandler extends AbstractAction
implements MouseListener, FocusListener, UIResource {
final javax.swing.Timer autoRepeatTimer;
final boolean isNext;
JSpinner spinner = null;
JButton arrowButton = null;
ArrowButtonHandler(String name, boolean isNext) {
super(name);
this.isNext = isNext;
autoRepeatTimer = new javax.swing.Timer(60, this);
autoRepeatTimer.setInitialDelay(300);
}
private JSpinner eventToSpinner(AWTEvent e) {
Object src = e.getSource();
while ((src instanceof Component) && !(src instanceof JSpinner)) {
src = ((Component)src).getParent();
}
return (src instanceof JSpinner) ? (JSpinner)src : null;
}
public void actionPerformed(ActionEvent e) {
JSpinner spinner = this.spinner;
if (!(e.getSource() instanceof javax.swing.Timer)) {
// Most likely resulting from being in ActionMap.
spinner = eventToSpinner(e);
if (e.getSource() instanceof BasicArrowButton) {
arrowButton = (JButton)e.getSource();
}
} else {
if (arrowButton!=null && !arrowButton.getModel().isPressed()
&& autoRepeatTimer.isRunning()) {
autoRepeatTimer.stop();
spinner = null;
}
}
if (spinner != null) {
try {
int calendarField = getCalendarField(spinner);
spinner.commitEdit();
if (calendarField != -1) {
((SpinnerDateModel)spinner.getModel()).
setCalendarField(calendarField);
}
Object value = (isNext) ? spinner.getNextValue() :
spinner.getPreviousValue();
if (value != null) {
spinner.setValue(value);
select(spinner);
}
} catch (IllegalArgumentException iae) {
UIManager.getLookAndFeel().provideErrorFeedback(spinner);
} catch (ParseException pe) {
UIManager.getLookAndFeel().provideErrorFeedback(spinner);
}
}
}
/**
* If the spinner's editor is a DateEditor, this selects the field
* associated with the value that is being incremented.
*/
private void select(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DateEditor) {
JSpinner.DateEditor dateEditor = (JSpinner.DateEditor)editor;
JFormattedTextField ftf = dateEditor.getTextField();
Format format = dateEditor.getFormat();
Object value;
if (format != null && (value = spinner.getValue()) != null) {
SpinnerDateModel model = dateEditor.getModel();
DateFormat.Field field = DateFormat.Field.ofCalendarField(
model.getCalendarField());
if (field != null) {
try {
AttributedCharacterIterator iterator = format.
formatToCharacterIterator(value);
if (!select(ftf, iterator, field) &&
field == DateFormat.Field.HOUR0) {
select(ftf, iterator, DateFormat.Field.HOUR1);
}
}
catch (IllegalArgumentException iae) {}
}
}
}
}
/**
* Selects the passed in field, returning true if it is found,
* false otherwise.
*/
private boolean select(JFormattedTextField ftf,
AttributedCharacterIterator iterator,
DateFormat.Field field) {
int max = ftf.getDocument().getLength();
iterator.first();
do {
Map attrs = iterator.getAttributes();
if (attrs != null && attrs.containsKey(field)){
int start = iterator.getRunStart(field);
int end = iterator.getRunLimit(field);
if (start != -1 && end != -1 && start <= max &&
end <= max) {
ftf.select(start, end);
}
return true;
}
} while (iterator.next() != CharacterIterator.DONE);
return false;
}
/**
* Returns the calendarField under the start of the selection, or
* -1 if there is no valid calendar field under the selection (or
* the spinner isn't editing dates.
*/
private int getCalendarField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DateEditor) {
JSpinner.DateEditor dateEditor = (JSpinner.DateEditor)editor;
JFormattedTextField ftf = dateEditor.getTextField();
int start = ftf.getSelectionStart();
JFormattedTextField.AbstractFormatter formatter =
ftf.getFormatter();
if (formatter instanceof InternationalFormatter) {
Format.Field[] fields = ((InternationalFormatter)
formatter).getFields(start);
for (int counter = 0; counter < fields.length; counter++) {
if (fields[counter] instanceof DateFormat.Field) {
int calendarField;
if (fields[counter] == DateFormat.Field.HOUR1) {
calendarField = Calendar.HOUR;
}
else {
calendarField = ((DateFormat.Field)
fields[counter]).getCalendarField();
}
if (calendarField != -1) {
return calendarField;
}
}
}
}
}
return -1;
}
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getComponent().isEnabled()) {
spinner = eventToSpinner(e);
autoRepeatTimer.start();
focusSpinnerIfNecessary();
}
}
public void mouseReleased(MouseEvent e) {
autoRepeatTimer.stop();
spinner = null;
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
/**
* Requests focus on a child of the spinner if the spinner doesn't
* have focus.
*/
private void focusSpinnerIfNecessary() {
Component fo = KeyboardFocusManager.
getCurrentKeyboardFocusManager().getFocusOwner();
if (spinner.isRequestFocusEnabled() && (
fo == null ||
!SwingUtilities.isDescendingFrom(fo, spinner))) {
Container root = spinner;
if (!root.isFocusCycleRoot()) {
root = root.getFocusCycleRootAncestor();
}
if (root != null) {
FocusTraversalPolicy ftp = root.getFocusTraversalPolicy();
Component child = ftp.getComponentAfter(root, spinner);
if (child != null && SwingUtilities.isDescendingFrom(
child, spinner)) {
child.requestFocus();
}
}
}
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
if (autoRepeatTimer.isRunning()) {
autoRepeatTimer.stop();
}
spinner = null;
if (arrowButton !=null) {
ButtonModel model = arrowButton.getModel();
model.setPressed(false);
model.setArmed(false);
}
}
}
/**
* A simple layout manager for the editor and the next/previous buttons.
* See the BasicSpinnerUI javadoc for more information about exactly
* how the components are arranged.
*/
private static class SpinnerLayout implements LayoutManager
{
private Component nextButton = null;
private Component previousButton = null;
private Component editor = null;
public void addLayoutComponent(String name, Component c) {
if ("Next".equals(name)) {
nextButton = c;
}
else if ("Previous".equals(name)) {
previousButton = c;
}
else if ("Editor".equals(name)) {
editor = c;
}
}
public void removeLayoutComponent(Component c) {
if (c == nextButton) {
c = null;
}
else if (c == previousButton) {
previousButton = null;
}
else if (c == editor) {
editor = null;
}
}
/**
* Used by the default LayoutManager class - SpinnerLayout for
* missing (null) editor/nextButton/previousButton children.
*/
private static final Dimension zeroSize = new Dimension(0, 0);
private Dimension preferredSize(Component c) {
return (c == null) ? zeroSize : c.getPreferredSize();
}
public Dimension preferredLayoutSize(Container parent) {
Dimension nextD = preferredSize(nextButton);
Dimension previousD = preferredSize(previousButton);
Dimension editorD = preferredSize(editor);
/* Force the editors height to be a multiple of 2
*/
editorD.height = ((editorD.height + 1) / 2) * 2;
Dimension size = new Dimension(editorD.width, editorD.height);
size.width += Math.max(nextD.width, previousD.width);
Insets insets = parent.getInsets();
size.width += insets.left + insets.right;
size.height += insets.top + insets.bottom;
return size;
}
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
private void setBounds(Component c, int x, int y, int width, int height) {
if (c != null) {
c.setBounds(x, y, width, height);
}
}
public void layoutContainer(Container parent) {
int width = parent.getWidth();
int height = parent.getHeight();
Insets insets = parent.getInsets();
Dimension nextD = preferredSize(nextButton);
Dimension previousD = preferredSize(previousButton);
int buttonsWidth = Math.max(nextD.width, previousD.width);
int editorHeight = height - (insets.top + insets.bottom);
// The arrowButtonInsets value is used instead of the JSpinner's
// insets if not null. Defining this to be (0, 0, 0, 0) causes the
// buttons to be aligned with the outer edge of the spinner's
// border, and leaving it as "null" places the buttons completely
// inside the spinner's border.
Insets buttonInsets = UIManager.getInsets("Spinner.arrowButtonInsets");
if (buttonInsets == null) {
buttonInsets = insets;
}
/* Deal with the spinner's componentOrientation property.
*/
int editorX, editorWidth, buttonsX;
if (parent.getComponentOrientation().isLeftToRight()) {
editorX = insets.left;
editorWidth = width - insets.left - buttonsWidth - buttonInsets.right;
buttonsX = width - buttonsWidth - buttonInsets.right;
} else {
buttonsX = buttonInsets.left;
editorX = buttonsX + buttonsWidth;
editorWidth = width - buttonInsets.left - buttonsWidth - insets.right;
}
int nextY = buttonInsets.top;
int nextHeight = (height / 2) + (height % 2) - nextY;
int previousY = buttonInsets.top + nextHeight;
int previousHeight = height - previousY - buttonInsets.bottom;
setBounds(editor, editorX, insets.top, editorWidth, editorHeight);
setBounds(nextButton, buttonsX, nextY, buttonsWidth, nextHeight);
setBounds(previousButton, buttonsX, previousY, buttonsWidth, previousHeight);
}
}
/**
* Detect JSpinner property changes we're interested in and delegate. Subclasses
* shouldn't need to replace the default propertyChangeListener (although they
* can by overriding createPropertyChangeListener) since all of the interesting
* property changes are delegated to protected methods.
*/
private static class PropertyChangeHandler implements PropertyChangeListener
{
public void propertyChange(PropertyChangeEvent e)
{
String propertyName = e.getPropertyName();
if (e.getSource() instanceof JSpinner) {
JSpinner spinner = (JSpinner)(e.getSource());
SpinnerUI spinnerUI = spinner.getUI();
if (spinnerUI instanceof BasicSpinnerUI) {
BasicSpinnerUI ui = (BasicSpinnerUI)spinnerUI;
if ("editor".equals(propertyName)) {
JComponent oldEditor = (JComponent)e.getOldValue();
JComponent newEditor = (JComponent)e.getNewValue();
ui.replaceEditor(oldEditor, newEditor);
ui.updateEnabledState();
if (oldEditor instanceof JSpinner.DefaultEditor) {
JTextField tf =
((JSpinner.DefaultEditor)oldEditor).getTextField();
if (tf != null) {
tf.removeFocusListener(nextButtonHandler);
tf.removeFocusListener(previousButtonHandler);
}
}
if (newEditor instanceof JSpinner.DefaultEditor) {
JTextField tf =
((JSpinner.DefaultEditor)newEditor).getTextField();
if (tf != null) {
if (tf.getFont() instanceof UIResource) {
tf.setFont(spinner.getFont());
}
tf.addFocusListener(nextButtonHandler);
tf.addFocusListener(previousButtonHandler);
}
}
}
else if ("enabled".equals(propertyName)) {
ui.updateEnabledState();
}
}
} else if (e.getSource() instanceof JComponent) {
JComponent c = (JComponent)e.getSource();
if ((c.getParent() instanceof JPanel) &&
(c.getParent().getParent() instanceof JSpinner) &&
"border".equals(propertyName)) {
JSpinner spinner = (JSpinner)c.getParent().getParent();
SpinnerUI spinnerUI = spinner.getUI();
if (spinnerUI instanceof BasicSpinnerUI) {
BasicSpinnerUI ui = (BasicSpinnerUI)spinnerUI;
ui.maybeRemoveEditorBorder(c);
}
}
}
}
}
}
| gpl-2.0 |
vanjo9800/SensortagSAPCloud | src/main/java/com/example/ti/ble/sensortag/SensorTagMovementProfile.java | 9813 | /**************************************************************************************************
Filename: SensorTagMovementProfile.java
Copyright (c) 2013 - 2015 Texas Instruments Incorporated
All rights reserved not granted herein.
Limited License.
Texas Instruments Incorporated grants a world-wide, royalty-free,
non-exclusive license under copyrights and patents it now or hereafter
owns or controls to make, have made, use, import, offer to sell and sell ("Utilize")
this software subject to the terms herein. With respect to the foregoing patent
license, such license is granted solely to the extent that any such patent is necessary
to Utilize the software alone. The patent license shall not apply to any combinations which
include this software, other than combinations with devices manufactured by or for TI ('TI Devices').
No hardware patent is licensed hereunder.
Redistributions must preserve existing copyright notices and reproduce this license (including the
above copyright notice and the disclaimer and (if applicable) source code license limitations below)
in the documentation and/or other materials provided with the distribution
Redistribution and use in binary form, without modification, are permitted provided that the following
conditions are met:
* No reverse engineering, decompilation, or disassembly of this software is permitted with respect to any
software provided in binary form.
* any redistribution and use are licensed by TI for use only with TI Devices.
* Nothing shall obligate TI to provide you with source code for the software licensed and provided to you in object code.
If software source code is provided to you, modification and redistribution of the source code are permitted
provided that the following conditions are met:
* any redistribution and use of the source code, including any resulting derivative works, are licensed by
TI for use only with TI Devices.
* any redistribution and use of any object code compiled from the source code and any resulting derivative
works, are licensed by TI for use only with TI Devices.
Neither the name of Texas Instruments Incorporated nor the names of its suppliers may be used to endorse or
promote products derived from this software without specific prior written permission.
DISCLAIMER.
THIS SOFTWARE IS PROVIDED BY TI AND TI'S LICENSORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL TI AND TI'S LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**************************************************************************************************/
package com.example.ti.ble.sensortag;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.text.Html;
import android.util.Log;
import android.widget.CompoundButton;
import com.example.ti.ble.common.BluetoothLeService;
import com.example.ti.ble.common.GattInfo;
import com.example.ti.ble.common.GenericBluetoothProfile;
import com.example.ti.util.Point3D;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class SensorTagMovementProfile extends GenericBluetoothProfile {
public SensorTagMovementProfile(Context con,BluetoothDevice device,BluetoothGattService service,BluetoothLeService controller) {
super(con,device,service,controller);
this.tRow = new SensorTagMovementTableRow(con);
List<BluetoothGattCharacteristic> characteristics = this.mBTService.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if (c.getUuid().toString().equals(SensorTagGatt.UUID_MOV_DATA.toString())) {
this.dataC = c;
}
if (c.getUuid().toString().equals(SensorTagGatt.UUID_MOV_CONF.toString())) {
this.configC = c;
}
if (c.getUuid().toString().equals(SensorTagGatt.UUID_MOV_PERI.toString())) {
this.periodC = c;
}
}
this.tRow.setIcon(this.getIconPrefix(), this.dataC.getUuid().toString());
this.tRow.title.setText(GattInfo.uuidToName(UUID.fromString(this.dataC.getUuid().toString())));
this.tRow.uuidLabel.setText(this.dataC.getUuid().toString());
this.tRow.value.setText("X:0.00G, Y:0.00G, Z:0.00G");
SensorTagMovementTableRow row = (SensorTagMovementTableRow)this.tRow;
row.gyroValue.setText("X:0.00'/s, Y:0.00'/s, Z:0.00'/s");
row.magValue.setText("X:0.00mT, Y:0.00mT, Z:0.00mT");
row.WOS.setChecked(true);
row.WOS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
byte b[] = new byte[] {0x7F,0x00};
if (isChecked) {
b[0] = (byte)0xFF;
}
int error = mBTLeService.writeCharacteristic(configC, b);
if (error != 0) {
if (configC != null)
Log.d("SensorTagMovementProfile","Sensor config failed: " + configC.getUuid().toString() + " Error: " + error);
}
}
});
this.tRow.periodBar.setProgress(100);
}
public static boolean isCorrectService(BluetoothGattService service) {
if ((service.getUuid().toString().compareTo(SensorTagGatt.UUID_MOV_SERV.toString())) == 0) {
return true;
}
else return false;
}
@Override
public void enableService() {
byte b[] = new byte[] {0x7F,0x00};
SensorTagMovementTableRow row = (SensorTagMovementTableRow)this.tRow;
if (row.WOS.isChecked()) b[0] = (byte)0xFF;
int error = mBTLeService.writeCharacteristic(this.configC, b);
if (error != 0) {
if (this.configC != null)
Log.d("SensorTagMovementProfile","Sensor config failed: " + this.configC.getUuid().toString() + " Error: " + error);
}
error = this.mBTLeService.setCharacteristicNotification(this.dataC, true);
if (error != 0) {
if (this.dataC != null)
Log.d("SensorTagMovementProfile","Sensor notification enable failed: " + this.configC.getUuid().toString() + " Error: " + error);
}
this.periodWasUpdated(700);
this.isEnabled = true;
}
@Override
public void disableService() {
int error = mBTLeService.writeCharacteristic(this.configC, new byte[] {0x00,0x00});
if (error != 0) {
if (this.configC != null)
Log.d("SensorTagMovementProfile","Sensor config failed: " + this.configC.getUuid().toString() + " Error: " + error);
}
error = this.mBTLeService.setCharacteristicNotification(this.dataC, false);
if (error != 0) {
if (this.dataC != null)
Log.d("SensorTagMovementProfile","Sensor notification disable failed: " + this.configC.getUuid().toString() + " Error: " + error);
}
this.isEnabled = false;
}
public void didWriteValueForCharacteristic(BluetoothGattCharacteristic c) {
}
public void didReadValueForCharacteristic(BluetoothGattCharacteristic c) {
}
@Override
public void didUpdateValueForCharacteristic(BluetoothGattCharacteristic c) {
byte[] value = c.getValue();
if (c.equals(this.dataC)){
Point3D v;
v = Sensor.MOVEMENT_ACC.convert(value);
if (this.tRow.config == false) this.tRow.value.setText(Html.fromHtml(String.format("<font color=#FF0000>X:%.2fG</font>, <font color=#00967D>Y:%.2fG</font>, <font color=#00000>Z:%.2fG</font>", v.x, v.y, v.z)));
this.tRow.sl1.addValue((float)v.x);
this.tRow.sl2.addValue((float)v.y);
this.tRow.sl3.addValue((float)v.z);
v = Sensor.MOVEMENT_GYRO.convert(value);
SensorTagMovementTableRow row = (SensorTagMovementTableRow)this.tRow;
row.gyroValue.setText(Html.fromHtml(String.format("<font color=#FF0000>X:%.2f°/s</font>, <font color=#00967D>Y:%.2f°/s</font>, <font color=#00000>Z:%.2f°/s</font>", v.x, v.y, v.z)));
row.sl4.addValue((float)v.x);
row.sl5.addValue((float)v.y);
row.sl6.addValue((float)v.z);
v = Sensor.MOVEMENT_MAG.convert(value);
row.magValue.setText(Html.fromHtml(String.format("<font color=#FF0000>X:%.2fuT</font>, <font color=#00967D>Y:%.2fuT</font>, <font color=#00000>Z:%.2fuT</font>", v.x, v.y, v.z)));
row.sl7.addValue((float)v.x);
row.sl8.addValue((float)v.y);
row.sl9.addValue((float)v.z);
}
}
@Override
public Map<String,String> getMQTTMap() {
Point3D v = Sensor.MOVEMENT_ACC.convert(this.dataC.getValue());
Map<String,String> map = new HashMap<String, String>();
map.put("acc_x",String.format("%.2f",v.x));
map.put("acc_y",String.format("%.2f",v.y));
map.put("acc_z",String.format("%.2f",v.z));
v = Sensor.MOVEMENT_GYRO.convert(this.dataC.getValue());
map.put("gyro_x",String.format("%.2f",v.x));
map.put("gyro_y",String.format("%.2f",v.y));
map.put("gyro_z",String.format("%.2f",v.z));
v = Sensor.MOVEMENT_MAG.convert(this.dataC.getValue());
map.put("compass_x",String.format("%.2f",v.x));
map.put("compass_y",String.format("%.2f",v.y));
map.put("compass_z",String.format("%.2f",v.z));
return map;
}
}
| gpl-2.0 |
teamfx/openjfx-9-dev-rt | modules/javafx.graphics/src/main/java/javafx/stage/PopupWindow.java | 41662 | /*
* Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.stage;
import com.sun.javafx.util.Utils;
import com.sun.javafx.event.DirectEvent;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.BooleanPropertyBase;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.ReadOnlyDoubleWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import com.sun.javafx.event.EventHandlerManager;
import com.sun.javafx.event.EventRedirector;
import com.sun.javafx.event.EventUtil;
import com.sun.javafx.perf.PerformanceTracker;
import com.sun.javafx.scene.SceneHelper;
import com.sun.javafx.stage.FocusUngrabEvent;
import com.sun.javafx.stage.PopupWindowPeerListener;
import com.sun.javafx.stage.WindowCloseRequestHandler;
import com.sun.javafx.stage.WindowEventDispatcher;
import com.sun.javafx.tk.Toolkit;
import static com.sun.javafx.FXPermissions.CREATE_TRANSPARENT_WINDOW_PERMISSION;
import com.sun.javafx.scene.NodeHelper;
import com.sun.javafx.stage.PopupWindowHelper;
import com.sun.javafx.stage.WindowHelper;
import javafx.beans.property.ObjectPropertyBase;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.WeakChangeListener;
import javafx.event.EventTarget;
import javafx.event.EventType;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.Pane;
/**
* PopupWindow is the parent for a variety of different types of popup
* based windows including {@link Popup} and {@link javafx.scene.control.Tooltip}
* and {@link javafx.scene.control.ContextMenu}.
* <p>
* A PopupWindow is a secondary window which has no window decorations or title bar.
* It doesn't show up in the OS as a top-level window. It is typically
* used for tool tip like notification, drop down boxes, menus, and so forth.
* <p>
* The PopupWindow <strong>cannot be shown without an owner</strong>.
* PopupWindows require that an owner window exist in order to be shown. However,
* it is possible to create a PopupWindow ahead of time and simply set the owner
* (or change the owner) before first being made visible. Attempting to change
* the owner while the PopupWindow is visible will result in an IllegalStateException.
* <p>
* The PopupWindow encapsulates much of the behavior and functionality common to popups,
* such as the ability to close when the "esc" key is pressed, or the ability to
* hide all child popup windows whenever this window is hidden. These abilities can
* be enabled or disabled via properties.
* @since JavaFX 2.0
*/
public abstract class PopupWindow extends Window {
static {
PopupWindowHelper.setPopupWindowAccessor(new PopupWindowHelper.PopupWindowAccessor() {
@Override public void doVisibleChanging(Window window, boolean visible) {
((PopupWindow) window).doVisibleChanging(visible);
}
@Override public void doVisibleChanged(Window window, boolean visible) {
((PopupWindow) window).doVisibleChanged(visible);
}
@Override
public ObservableList<Node> getContent(PopupWindow popupWindow) {
return popupWindow.getContent();
}
});
}
/**
* A private list of all child popups.
*/
private final List<PopupWindow> children = new ArrayList<PopupWindow>();
/**
* Keeps track of the bounds of the content, and adjust the position and
* size of the popup window accordingly. This way as the popup content
* changes, the window will be changed to match.
*/
private final InvalidationListener popupWindowUpdater =
new InvalidationListener() {
@Override
public void invalidated(final Observable observable) {
cachedExtendedBounds = null;
cachedAnchorBounds = null;
updateWindow(getAnchorX(), getAnchorY());
}
};
/**
* RT-28454: When a parent node or parent window we are associated with is not
* visible anymore, possibly because the scene was not valid anymore, we should hide.
*/
private ChangeListener<Boolean> changeListener = (observable, oldValue, newValue) -> {
if (oldValue && !newValue) {
hide();
}
};
private WeakChangeListener<Boolean> weakOwnerNodeListener = new WeakChangeListener(changeListener);
public PopupWindow() {
final Pane popupRoot = new Pane();
popupRoot.setBackground(Background.EMPTY);
popupRoot.getStyleClass().add("popup");
final Scene scene = SceneHelper.createPopupScene(popupRoot);
scene.setFill(null);
super.setScene(scene);
popupRoot.layoutBoundsProperty().addListener(popupWindowUpdater);
popupRoot.boundsInLocalProperty().addListener(popupWindowUpdater);
scene.rootProperty().addListener(
new InvalidationListener() {
private Node oldRoot = scene.getRoot();
@Override
public void invalidated(final Observable observable) {
final Node newRoot = scene.getRoot();
if (oldRoot != newRoot) {
if (oldRoot != null) {
oldRoot.layoutBoundsProperty()
.removeListener(popupWindowUpdater);
oldRoot.boundsInLocalProperty()
.removeListener(popupWindowUpdater);
oldRoot.getStyleClass().remove("popup");
}
if (newRoot != null) {
newRoot.layoutBoundsProperty()
.addListener(popupWindowUpdater);
newRoot.boundsInLocalProperty()
.addListener(popupWindowUpdater);
newRoot.getStyleClass().add("popup");
}
oldRoot = newRoot;
cachedExtendedBounds = null;
cachedAnchorBounds = null;
updateWindow(getAnchorX(), getAnchorY());
}
}
});
PopupWindowHelper.initHelper(this);
}
/*
* Gets the observable, modifiable list of children which are placed in this
* PopupWindow.
*
* @return the PopupWindow content
*/
ObservableList<Node> getContent() {
final Parent rootNode = getScene().getRoot();
if (rootNode instanceof Group) {
return ((Group) rootNode).getChildren();
}
if (rootNode instanceof Pane) {
return ((Pane) rootNode).getChildren();
}
throw new IllegalStateException(
"The content of the Popup can't be accessed");
}
/**
* The window which is the parent of this popup. All popups must have an
* owner window.
*/
private ReadOnlyObjectWrapper<Window> ownerWindow =
new ReadOnlyObjectWrapper<Window>(this, "ownerWindow");
public final Window getOwnerWindow() {
return ownerWindow.get();
}
public final ReadOnlyObjectProperty<Window> ownerWindowProperty() {
return ownerWindow.getReadOnlyProperty();
}
/**
* The node which is the owner of this popup. All popups must have an
* owner window but are not required to be associated with an owner node.
* If an autohide Popup has an owner node, mouse press inside the owner node
* doesn't cause the Popup to hide.
*/
private ReadOnlyObjectWrapper<Node> ownerNode =
new ReadOnlyObjectWrapper<Node>(this, "ownerNode");
public final Node getOwnerNode() {
return ownerNode.get();
}
public final ReadOnlyObjectProperty<Node> ownerNodeProperty() {
return ownerNode.getReadOnlyProperty();
}
/**
* Note to subclasses: the scene used by PopupWindow is very specifically
* managed by PopupWindow. This method is overridden to throw
* UnsupportedOperationException. You cannot specify your own scene.
*
* @param scene the scene to be rendered on this window
*/
@Override protected final void setScene(Scene scene) {
throw new UnsupportedOperationException();
}
/**
* This convenience variable indicates whether, when the popup is shown,
* it should automatically correct its position such that it doesn't end
* up positioned off the screen.
* @defaultValue true
*/
private BooleanProperty autoFix =
new BooleanPropertyBase(true) {
@Override
protected void invalidated() {
handleAutofixActivation(isShowing(), get());
}
@Override
public Object getBean() {
return PopupWindow.this;
}
@Override
public String getName() {
return "autoFix";
}
};
public final void setAutoFix(boolean value) { autoFix.set(value); }
public final boolean isAutoFix() { return autoFix.get(); }
public final BooleanProperty autoFixProperty() { return autoFix; }
/**
* Specifies whether Popups should auto hide. If a popup loses focus and
* autoHide is true, then the popup will be hidden automatically.
* <p>
* The only exception is when owner Node is specified using {@link #show(javafx.scene.Node, double, double)}.
* Focusing owner Node will not hide the PopupWindow.
* </p>
* @defaultValue false
*/
private BooleanProperty autoHide =
new BooleanPropertyBase() {
@Override
protected void invalidated() {
handleAutohideActivation(isShowing(), get());
}
@Override
public Object getBean() {
return PopupWindow.this;
}
@Override
public String getName() {
return "autoHide";
}
};
public final void setAutoHide(boolean value) { autoHide.set(value); }
public final boolean isAutoHide() { return autoHide.get(); }
public final BooleanProperty autoHideProperty() { return autoHide; }
/**
* Called after autoHide is run.
*/
private ObjectProperty<EventHandler<Event>> onAutoHide =
new SimpleObjectProperty<EventHandler<Event>>(this, "onAutoHide");
public final void setOnAutoHide(EventHandler<Event> value) { onAutoHide.set(value); }
public final EventHandler<Event> getOnAutoHide() { return onAutoHide.get(); }
public final ObjectProperty<EventHandler<Event>> onAutoHideProperty() { return onAutoHide; }
/**
* Specifies whether the PopupWindow should be hidden when an unhandled escape key
* is pressed while the popup has focus.
* @defaultValue true
*/
private BooleanProperty hideOnEscape =
new SimpleBooleanProperty(this, "hideOnEscape", true);
public final void setHideOnEscape(boolean value) { hideOnEscape.set(value); }
public final boolean isHideOnEscape() { return hideOnEscape.get(); }
public final BooleanProperty hideOnEscapeProperty() { return hideOnEscape; }
/**
* Specifies whether the event, which caused the Popup to hide, should be
* consumed. Having the event consumed prevents it from triggering some
* additional UI response in the Popup's owner window.
* @defaultValue true
* @since JavaFX 2.2
*/
private BooleanProperty consumeAutoHidingEvents =
new SimpleBooleanProperty(this, "consumeAutoHidingEvents",
true);
public final void setConsumeAutoHidingEvents(boolean value) {
consumeAutoHidingEvents.set(value);
}
public final boolean getConsumeAutoHidingEvents() {
return consumeAutoHidingEvents.get();
}
public final BooleanProperty consumeAutoHidingEventsProperty() {
return consumeAutoHidingEvents;
}
/**
* Show the popup.
* @param owner The owner of the popup. This must not be null.
* @throws NullPointerException if owner is null
* @throws IllegalArgumentException if the specified owner window would
* create cycle in the window hierarchy
*/
public void show(Window owner) {
validateOwnerWindow(owner);
showImpl(owner);
}
/**
* Shows the popup at the specified location on the screen. The popup window
* is positioned in such way that its anchor point ({@link #anchorLocation})
* is displayed at the specified {@code anchorX} and {@code anchorY}
* coordinates.
* <p>
* The popup is associated with the specified owner node. The {@code Window}
* which contains the owner node at the time of the call becomes an owner
* window of the displayed popup.
* </p>
* <p>
* Note that when {@link #autoHideProperty()} is set to true, mouse press on the owner Node
* will not hide the PopupWindow.
* </p>
*
* @param ownerNode The owner Node of the popup. It must not be null
* and must be associated with a Window.
* @param anchorX the x position of the popup anchor in screen coordinates
* @param anchorY the y position of the popup anchor in screen coordinates
* @throws NullPointerException if ownerNode is null
* @throws IllegalArgumentException if the specified owner node is not
* associated with a Window or when the window would create cycle
* in the window hierarchy
*/
public void show(Node ownerNode, double anchorX, double anchorY) {
if (ownerNode == null) {
throw new NullPointerException("The owner node must not be null");
}
final Scene ownerNodeScene = ownerNode.getScene();
if ((ownerNodeScene == null)
|| (ownerNodeScene.getWindow() == null)) {
throw new IllegalArgumentException(
"The owner node needs to be associated with a window");
}
final Window newOwnerWindow = ownerNodeScene.getWindow();
validateOwnerWindow(newOwnerWindow);
this.ownerNode.set(ownerNode);
// PopupWindow should disappear when owner node is not visible
if (ownerNode != null) {
NodeHelper.treeShowingProperty(ownerNode).addListener(weakOwnerNodeListener);
}
updateWindow(anchorX, anchorY);
showImpl(newOwnerWindow);
}
/**
* Shows the popup at the specified location on the screen. The popup window
* is positioned in such way that its anchor point ({@link #anchorLocation})
* is displayed at the specified {@code anchorX} and {@code anchorY}
* coordinates.
*
* @param ownerWindow The owner of the popup. This must not be null.
* @param anchorX the x position of the popup anchor in screen coordinates
* @param anchorY the y position of the popup anchor in screen coordinates
* @throws NullPointerException if ownerWindow is null
* @throws IllegalArgumentException if the specified owner window would
* create cycle in the window hierarchy
*/
public void show(Window ownerWindow, double anchorX, double anchorY) {
validateOwnerWindow(ownerWindow);
updateWindow(anchorX, anchorY);
showImpl(ownerWindow);
}
private void showImpl(final Window owner) {
// Update the owner field
this.ownerWindow.set(owner);
if (owner instanceof PopupWindow) {
((PopupWindow)owner).children.add(this);
}
// PopupWindow should disappear when owner node is not visible
if (owner != null) {
owner.showingProperty().addListener(weakOwnerNodeListener);
}
final Scene sceneValue = getScene();
SceneHelper.parentEffectiveOrientationInvalidated(sceneValue);
// RT-28447
final Scene ownerScene = getRootWindow(owner).getScene();
if (ownerScene != null) {
if (ownerScene.getUserAgentStylesheet() != null) {
sceneValue.setUserAgentStylesheet(ownerScene.getUserAgentStylesheet());
}
sceneValue.getStylesheets().setAll(ownerScene.getStylesheets());
if (sceneValue.getCursor() == null) {
sceneValue.setCursor(ownerScene.getCursor());
}
}
// It is required that the root window exist and be visible to show the popup.
if (getRootWindow(owner).isShowing()) {
// We do show() first so that the width and height of the
// popup window are initialized. This way the x,y location of the
// popup calculated below uses the right width and height values for
// its calculation. (fix for part of RT-10675).
show();
}
}
/**
* Hide this Popup and all its children
*/
@Override public void hide() {
for (PopupWindow c : children) {
if (c.isShowing()) {
c.hide();
}
}
children.clear();
super.hide();
// When popup hides, remove listeners; these are added when the popup shows.
if (getOwnerWindow() != null) getOwnerWindow().showingProperty().removeListener(weakOwnerNodeListener);
if (getOwnerNode() != null) NodeHelper.treeShowingProperty(getOwnerNode()).removeListener(weakOwnerNodeListener);
}
/*
* This can be replaced by listening for the onShowing/onHiding events
* Note: This method MUST only be called via its accessor method.
*/
private void doVisibleChanging(boolean visible) {
PerformanceTracker.logEvent("PopupWindow.storeVisible for [PopupWindow]");
Toolkit toolkit = Toolkit.getToolkit();
if (visible && (getPeer() == null)) {
// Setup the peer
StageStyle popupStyle;
try {
final SecurityManager securityManager =
System.getSecurityManager();
if (securityManager != null) {
securityManager.checkPermission(CREATE_TRANSPARENT_WINDOW_PERMISSION);
}
popupStyle = StageStyle.TRANSPARENT;
} catch (final SecurityException e) {
popupStyle = StageStyle.UNDECORATED;
}
setPeer(toolkit.createTKPopupStage(this, popupStyle, getOwnerWindow().getPeer(), acc));
setPeerListener(new PopupWindowPeerListener(PopupWindow.this));
}
}
private Window rootWindow;
/*
* This can be replaced by listening for the onShown/onHidden events
* Note: This method MUST only be called via its accessor method.
*/
private void doVisibleChanged(boolean visible) {
final Window ownerWindowValue = getOwnerWindow();
if (visible) {
rootWindow = getRootWindow(ownerWindowValue);
startMonitorOwnerEvents(ownerWindowValue);
// currently we consider popup window to be focused when it is
// visible and its owner window is focused (we need to track
// that through listener on owner window focused property)
// a better solution would require some focus manager, which can
// track focus state across multiple windows
bindOwnerFocusedProperty(ownerWindowValue);
WindowHelper.setFocused(this, ownerWindowValue.isFocused());
handleAutofixActivation(true, isAutoFix());
handleAutohideActivation(true, isAutoHide());
} else {
stopMonitorOwnerEvents(ownerWindowValue);
unbindOwnerFocusedProperty(ownerWindowValue);
WindowHelper.setFocused(this, false);
handleAutofixActivation(false, isAutoFix());
handleAutohideActivation(false, isAutoHide());
rootWindow = null;
}
PerformanceTracker.logEvent("PopupWindow.storeVisible for [PopupWindow] finished");
}
/**
* Specifies the x coordinate of the popup anchor point on the screen. If
* the {@code anchorLocation} is set to {@code WINDOW_TOP_LEFT} or
* {@code WINDOW_BOTTOM_LEFT} the {@code x} and {@code anchorX} values will
* be identical.
*
* @since JavaFX 8.0
*/
private final ReadOnlyDoubleWrapper anchorX =
new ReadOnlyDoubleWrapper(this, "anchorX", Double.NaN);
public final void setAnchorX(final double value) {
updateWindow(value, getAnchorY());
}
public final double getAnchorX() {
return anchorX.get();
}
public final ReadOnlyDoubleProperty anchorXProperty() {
return anchorX.getReadOnlyProperty();
}
/**
* Specifies the y coordinate of the popup anchor point on the screen. If
* the {@code anchorLocation} is set to {@code WINDOW_TOP_LEFT} or
* {@code WINDOW_TOP_RIGHT} the {@code y} and {@code anchorY} values will
* be identical.
*
* @since JavaFX 8.0
*/
private final ReadOnlyDoubleWrapper anchorY =
new ReadOnlyDoubleWrapper(this, "anchorY", Double.NaN);
public final void setAnchorY(final double value) {
updateWindow(getAnchorX(), value);
}
public final double getAnchorY() {
return anchorY.get();
}
public final ReadOnlyDoubleProperty anchorYProperty() {
return anchorY.getReadOnlyProperty();
}
/**
* Specifies the popup anchor point which is used in popup positioning. The
* point can be set to a corner of the popup window or a corner of its
* content. In this context the content corners are derived from the popup
* root node's layout bounds.
* <p>
* In general changing of the anchor location won't change the current
* window position. Instead of that, the {@code anchorX} and {@code anchorY}
* values are recalculated to correspond to the new anchor point.
* </p>
* @since JavaFX 8.0
*/
private final ObjectProperty<AnchorLocation> anchorLocation =
new ObjectPropertyBase<AnchorLocation>(
AnchorLocation.WINDOW_TOP_LEFT) {
@Override
protected void invalidated() {
cachedAnchorBounds = null;
updateWindow(windowToAnchorX(getX()),
windowToAnchorY(getY()));
}
@Override
public Object getBean() {
return PopupWindow.this;
}
@Override
public String getName() {
return "anchorLocation";
}
};
public final void setAnchorLocation(final AnchorLocation value) {
anchorLocation.set(value);
}
public final AnchorLocation getAnchorLocation() {
return anchorLocation.get();
}
public final ObjectProperty<AnchorLocation> anchorLocationProperty() {
return anchorLocation;
}
/**
* Anchor location constants for popup anchor point selection.
*
* @since JavaFX 8.0
*/
public enum AnchorLocation {
/** Represents top left window corner. */
WINDOW_TOP_LEFT(0, 0, false),
/** Represents top right window corner. */
WINDOW_TOP_RIGHT(1, 0, false),
/** Represents bottom left window corner. */
WINDOW_BOTTOM_LEFT(0, 1, false),
/** Represents bottom right window corner. */
WINDOW_BOTTOM_RIGHT(1, 1, false),
/** Represents top left content corner. */
CONTENT_TOP_LEFT(0, 0, true),
/** Represents top right content corner. */
CONTENT_TOP_RIGHT(1, 0, true),
/** Represents bottom left content corner. */
CONTENT_BOTTOM_LEFT(0, 1, true),
/** Represents bottom right content corner. */
CONTENT_BOTTOM_RIGHT(1, 1, true);
private final double xCoef;
private final double yCoef;
private final boolean contentLocation;
private AnchorLocation(final double xCoef, final double yCoef,
final boolean contentLocation) {
this.xCoef = xCoef;
this.yCoef = yCoef;
this.contentLocation = contentLocation;
}
double getXCoef() {
return xCoef;
}
double getYCoef() {
return yCoef;
}
boolean isContentLocation() {
return contentLocation;
}
};
@Override
void setXInternal(final double value) {
updateWindow(windowToAnchorX(value), getAnchorY());
}
@Override
void setYInternal(final double value) {
updateWindow(getAnchorX(), windowToAnchorY(value));
}
@Override
void notifyLocationChanged(final double newX, final double newY) {
super.notifyLocationChanged(newX, newY);
anchorX.set(windowToAnchorX(newX));
anchorY.set(windowToAnchorY(newY));
}
private Bounds cachedExtendedBounds;
private Bounds cachedAnchorBounds;
private Bounds getExtendedBounds() {
if (cachedExtendedBounds == null) {
final Parent rootNode = getScene().getRoot();
cachedExtendedBounds = union(rootNode.getLayoutBounds(),
rootNode.getBoundsInLocal());
}
return cachedExtendedBounds;
}
private Bounds getAnchorBounds() {
if (cachedAnchorBounds == null) {
cachedAnchorBounds = getAnchorLocation().isContentLocation()
? getScene().getRoot()
.getLayoutBounds()
: getExtendedBounds();
}
return cachedAnchorBounds;
}
private void updateWindow(final double newAnchorX,
final double newAnchorY) {
final AnchorLocation anchorLocationValue = getAnchorLocation();
final Parent rootNode = getScene().getRoot();
final Bounds extendedBounds = getExtendedBounds();
final Bounds anchorBounds = getAnchorBounds();
final double anchorXCoef = anchorLocationValue.getXCoef();
final double anchorYCoef = anchorLocationValue.getYCoef();
final double anchorDeltaX = anchorXCoef * anchorBounds.getWidth();
final double anchorDeltaY = anchorYCoef * anchorBounds.getHeight();
double anchorScrMinX = newAnchorX - anchorDeltaX;
double anchorScrMinY = newAnchorY - anchorDeltaY;
if (autofixActive) {
final Screen currentScreen =
Utils.getScreenForPoint(newAnchorX, newAnchorY);
final Rectangle2D screenBounds =
Utils.hasFullScreenStage(currentScreen)
? currentScreen.getBounds()
: currentScreen.getVisualBounds();
if (anchorXCoef <= 0.5) {
// left side of the popup is more important, try to keep it
// visible if the popup width is larger than screen width
anchorScrMinX = Math.min(anchorScrMinX,
screenBounds.getMaxX()
- anchorBounds.getWidth());
anchorScrMinX = Math.max(anchorScrMinX, screenBounds.getMinX());
} else {
// right side of the popup is more important
anchorScrMinX = Math.max(anchorScrMinX, screenBounds.getMinX());
anchorScrMinX = Math.min(anchorScrMinX,
screenBounds.getMaxX()
- anchorBounds.getWidth());
}
if (anchorYCoef <= 0.5) {
// top side of the popup is more important
anchorScrMinY = Math.min(anchorScrMinY,
screenBounds.getMaxY()
- anchorBounds.getHeight());
anchorScrMinY = Math.max(anchorScrMinY, screenBounds.getMinY());
} else {
// bottom side of the popup is more important
anchorScrMinY = Math.max(anchorScrMinY, screenBounds.getMinY());
anchorScrMinY = Math.min(anchorScrMinY,
screenBounds.getMaxY()
- anchorBounds.getHeight());
}
}
final double windowScrMinX =
anchorScrMinX - anchorBounds.getMinX()
+ extendedBounds.getMinX();
final double windowScrMinY =
anchorScrMinY - anchorBounds.getMinY()
+ extendedBounds.getMinY();
// update popup dimensions
setWidth(extendedBounds.getWidth());
setHeight(extendedBounds.getHeight());
// update transform
rootNode.setTranslateX(-extendedBounds.getMinX());
rootNode.setTranslateY(-extendedBounds.getMinY());
// update popup position
// don't set Window.xExplicit unnecessarily
if (!Double.isNaN(windowScrMinX)) {
super.setXInternal(windowScrMinX);
}
// don't set Window.yExplicit unnecessarily
if (!Double.isNaN(windowScrMinY)) {
super.setYInternal(windowScrMinY);
}
// set anchor x, anchor y
anchorX.set(anchorScrMinX + anchorDeltaX);
anchorY.set(anchorScrMinY + anchorDeltaY);
}
private Bounds union(final Bounds bounds1, final Bounds bounds2) {
final double minX = Math.min(bounds1.getMinX(), bounds2.getMinX());
final double minY = Math.min(bounds1.getMinY(), bounds2.getMinY());
final double maxX = Math.max(bounds1.getMaxX(), bounds2.getMaxX());
final double maxY = Math.max(bounds1.getMaxY(), bounds2.getMaxY());
return new BoundingBox(minX, minY, maxX - minX, maxY - minY);
}
private double windowToAnchorX(final double windowX) {
final Bounds anchorBounds = getAnchorBounds();
return windowX - getExtendedBounds().getMinX()
+ anchorBounds.getMinX()
+ getAnchorLocation().getXCoef()
* anchorBounds.getWidth();
}
private double windowToAnchorY(final double windowY) {
final Bounds anchorBounds = getAnchorBounds();
return windowY - getExtendedBounds().getMinY()
+ anchorBounds.getMinY()
+ getAnchorLocation().getYCoef()
* anchorBounds.getHeight();
}
/**
*
* Gets the root (non PopupWindow) Window for the provided window.
*
* @param win the Window for which to get the root window
*/
private static Window getRootWindow(Window win) {
// should be enough to traverse PopupWindow hierarchy here to get to the
// first non-popup focusable window
while (win instanceof PopupWindow) {
win = ((PopupWindow) win).getOwnerWindow();
}
return win;
}
void doAutoHide() {
// There is a timing problem here. I would like to have this isVisible
// check, such that we don't send an onAutoHide event if it was already
// invisible. However, visible is already false by the time this method
// gets called, when done by certain code paths.
// if (isVisible()) {
// hide this popup
hide();
if (getOnAutoHide() != null) {
getOnAutoHide().handle(new Event(this, this, Event.ANY));
}
// }
}
@Override
WindowEventDispatcher createInternalEventDispatcher() {
return new WindowEventDispatcher(new PopupEventRedirector(this),
new WindowCloseRequestHandler(this),
new EventHandlerManager(this));
}
@Override
Window getWindowOwner() {
return getOwnerWindow();
}
private void startMonitorOwnerEvents(final Window ownerWindowValue) {
final EventRedirector parentEventRedirector =
ownerWindowValue.getInternalEventDispatcher()
.getEventRedirector();
parentEventRedirector.addEventDispatcher(getEventDispatcher());
}
private void stopMonitorOwnerEvents(final Window ownerWindowValue) {
final EventRedirector parentEventRedirector =
ownerWindowValue.getInternalEventDispatcher()
.getEventRedirector();
parentEventRedirector.removeEventDispatcher(getEventDispatcher());
}
private ChangeListener<Boolean> ownerFocusedListener;
private void bindOwnerFocusedProperty(final Window ownerWindowValue) {
ownerFocusedListener =
(observable, oldValue, newValue) -> WindowHelper.setFocused(this, newValue);
ownerWindowValue.focusedProperty().addListener(ownerFocusedListener);
}
private void unbindOwnerFocusedProperty(final Window ownerWindowValue) {
ownerWindowValue.focusedProperty().removeListener(ownerFocusedListener);
ownerFocusedListener = null;
}
private boolean autofixActive;
private void handleAutofixActivation(final boolean visible,
final boolean autofix) {
final boolean newAutofixActive = visible && autofix;
if (autofixActive != newAutofixActive) {
autofixActive = newAutofixActive;
if (newAutofixActive) {
Screen.getScreens().addListener(popupWindowUpdater);
updateWindow(getAnchorX(), getAnchorY());
} else {
Screen.getScreens().removeListener(popupWindowUpdater);
}
}
}
private boolean autohideActive;
private void handleAutohideActivation(final boolean visible,
final boolean autohide) {
final boolean newAutohideActive = visible && autohide;
if (autohideActive != newAutohideActive) {
// assert rootWindow != null;
autohideActive = newAutohideActive;
if (newAutohideActive) {
rootWindow.increaseFocusGrabCounter();
} else {
rootWindow.decreaseFocusGrabCounter();
}
}
}
private void validateOwnerWindow(final Window owner) {
if (owner == null) {
throw new NullPointerException("Owner window must not be null");
}
if (wouldCreateCycle(owner, this)) {
throw new IllegalArgumentException(
"Specified owner window would create cycle"
+ " in the window hierarchy");
}
if (isShowing() && (getOwnerWindow() != owner)) {
throw new IllegalStateException(
"Popup is already shown with different owner window");
}
}
private static boolean wouldCreateCycle(Window parent, final Window child) {
while (parent != null) {
if (parent == child) {
return true;
}
parent = parent.getWindowOwner();
}
return false;
}
static class PopupEventRedirector extends EventRedirector {
private static final KeyCombination ESCAPE_KEY_COMBINATION =
KeyCombination.keyCombination("Esc");
private final PopupWindow popupWindow;
public PopupEventRedirector(final PopupWindow popupWindow) {
super(popupWindow);
this.popupWindow = popupWindow;
}
@Override
protected void handleRedirectedEvent(final Object eventSource,
final Event event) {
if (event instanceof KeyEvent) {
handleKeyEvent((KeyEvent) event);
return;
}
final EventType<?> eventType = event.getEventType();
if (eventType == MouseEvent.MOUSE_PRESSED
|| eventType == ScrollEvent.SCROLL) {
handleAutoHidingEvents(eventSource, event);
return;
}
if (eventType == FocusUngrabEvent.FOCUS_UNGRAB) {
handleFocusUngrabEvent();
return;
}
}
private void handleKeyEvent(final KeyEvent event) {
if (event.isConsumed()) {
return;
}
final Scene scene = popupWindow.getScene();
if (scene != null) {
final Node sceneFocusOwner = scene.getFocusOwner();
final EventTarget eventTarget =
(sceneFocusOwner != null) ? sceneFocusOwner : scene;
if (EventUtil.fireEvent(eventTarget, new DirectEvent(event.copyFor(popupWindow, eventTarget)))
== null) {
event.consume();
return;
}
}
if ((event.getEventType() == KeyEvent.KEY_PRESSED)
&& ESCAPE_KEY_COMBINATION.match(event)) {
handleEscapeKeyPressedEvent(event);
}
}
private void handleEscapeKeyPressedEvent(final Event event) {
if (popupWindow.isHideOnEscape()) {
popupWindow.doAutoHide();
if (popupWindow.getConsumeAutoHidingEvents()) {
event.consume();
}
}
}
private void handleAutoHidingEvents(final Object eventSource,
final Event event) {
// we handle mouse pressed only for the immediate parent window,
// where we can check whether the mouse press is inside of the owner
// control or not, we will force possible child popups to close
// by sending the FOCUS_UNGRAB event
if (popupWindow.getOwnerWindow() != eventSource) {
return;
}
if (popupWindow.isAutoHide() && !isOwnerNodeEvent(event)) {
// the mouse press is outside of the owner control,
// fire FOCUS_UNGRAB to child popups
Event.fireEvent(popupWindow, new FocusUngrabEvent());
popupWindow.doAutoHide();
if (popupWindow.getConsumeAutoHidingEvents()) {
event.consume();
}
}
}
private void handleFocusUngrabEvent() {
if (popupWindow.isAutoHide()) {
popupWindow.doAutoHide();
}
}
private boolean isOwnerNodeEvent(final Event event) {
final Node ownerNode = popupWindow.getOwnerNode();
if (ownerNode == null) {
return false;
}
final EventTarget eventTarget = event.getTarget();
if (!(eventTarget instanceof Node)) {
return false;
}
Node node = (Node) eventTarget;
do {
if (node == ownerNode) {
return true;
}
node = node.getParent();
} while (node != null);
return false;
}
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest11696.java | 2757 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest11696")
public class BenchmarkTest11696 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("foo");
String bar = new Test().doSomething(param);
// FILE URIs are tricky because they are different between Mac and Windows because of lack of standardization.
// Mac requires an extra slash for some reason.
String startURIslashes = "";
if (System.getProperty("os.name").indexOf("Windows") != -1)
if (System.getProperty("os.name").indexOf("Windows") != -1)
startURIslashes = "/";
else startURIslashes = "//";
try {
java.net.URI fileURI = new java.net.URI("file:" + startURIslashes
+ org.owasp.benchmark.helpers.Utils.testfileDir.replace('\\', '/').replace(' ', '_') + bar);
new java.io.File(fileURI);
} catch (java.net.URISyntaxException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
StringBuilder sbxyz59007 = new StringBuilder(param);
String bar = sbxyz59007.append("_SafeStuff").toString();
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
andi-git/boatpos | regkas-server/regkas-server-service/regkas-server-service-rest/src/test/java/org/regkas/service/rest/RestTestHelper.java | 1042 | package org.regkas.service.rest;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Specializes;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import java.net.URL;
import java.util.function.Function;
@Specializes
@Dependent
public class RestTestHelper extends org.boatpos.common.test.rest.RestTestHelper {
public Invocation.Builder createRestCallWithHeaderCredentialsForTestUser(URL url, Function<WebTarget, WebTarget> addPath) throws Exception {
return createRestCallWithHeaderCredentialsForTestUser(url, addPath, MediaType.APPLICATION_JSON_TYPE);
}
public Invocation.Builder createRestCallWithHeaderCredentialsForTestUser(URL url, Function<WebTarget, WebTarget> addPath, MediaType mediaType) throws Exception {
return super.createRestCall(url, addPath, mediaType)
.header("username", "Maria Musterfrau")
.header("password", "abc123")
.header("cashbox", "RegKas1");
}
}
| gpl-2.0 |
nidzo732/FileTransfer | Android/FileTransfer/app/src/main/java/com/nidzo/filetransfer/MainActivity.java | 5281 | package com.nidzo.filetransfer;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private Communicator communicator;
private PeerListAdapter peersAdapter;
private ListView peerList;
private EditText deviceName;
private ProgressBar progressIndicator;
private FileHandling fileHandling;
private String selectedPeerGuid;
private Intent fileToSendIntent;
private CheckBox enableEncryption;
private TextWatcher deviceNameChangedWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Identification.setName(deviceName.getText().toString(), getApplicationContext());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.getAction().equals(Intent.ACTION_SEND)) {
fileToSendIntent = intent;
}
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
peersAdapter = new PeerListAdapter(this);
peerList = (ListView) findViewById(R.id.peerList);
peerList.setAdapter(peersAdapter);
deviceName = (EditText) findViewById(R.id.deviceName);
progressIndicator = (ProgressBar) findViewById(R.id.progressIndicator);
enableEncryption = (CheckBox)findViewById(R.id.enableEncryptionCheckbox);
progressStop();
deviceName.setText(Identification.getName(this));
deviceName.addTextChangedListener(deviceNameChangedWatcher);
try {
communicator = new Communicator(this);
communicator.discoverPeers();
fileHandling = new FileHandling(this);
updatePeerList();
} catch (FileTransferException e) {
DialogBoxes.showMessageBox("Error", "Failed to start " + e.getMessage(), this);
}
}
@Override
protected void onPause() {
super.onPause();
communicator.halt();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.refreshPeers) {
communicator.discoverPeers();
}
return true;
}
public void updatePeerList() {
runOnUiThread(new Runnable() {
@Override
public void run() {
peersAdapter.reset(communicator.getPeers());
}
});
}
public void progressIndeterminate() {
progressIndicator.setVisibility(View.VISIBLE);
progressIndicator.setIndeterminate(true);
}
public void progressReport(double progress) {
progressIndicator.setIndeterminate(false);
progressIndicator.setVisibility(View.VISIBLE);
int progressValue = (int) (progress * 100);
progressIndicator.setProgress(progressValue);
}
public void progressStop() {
progressIndicator.setIndeterminate(false);
progressIndicator.setVisibility(View.INVISIBLE);
progressIndicator.setProgress(0);
}
public void deletePeer(String guid) {
try {
communicator.deletePeer(guid);
} catch (FileTransferException e) {
DialogBoxes.showMessageBox("Error", e.getMessage(), this);
}
}
public void unpairPeer(String guid) {
try {
communicator.unpairPeer(guid);
} catch (FileTransferException e) {
DialogBoxes.showMessageBox("Error", e.getMessage(), this);
}
}
public void pair(String guid) {
communicator.pair(guid);
}
public void sendFile(String guid) {
selectedPeerGuid = guid;
if (fileToSendIntent != null) {
communicator.sendFile(guid, fileToSendIntent, enableEncryption.isChecked());
fileToSendIntent = null;
} else fileHandling.selectFileToSend();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == FileHandling.FILE_SELECT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
communicator.sendFile(selectedPeerGuid, result, enableEncryption.isChecked());
}
}
}
public void fileReceived(final java.io.File file) {
runOnUiThread(new Runnable() {
@Override
public void run() {
fileHandling.offerToOpenFile(file);
}
});
}
}
| gpl-2.0 |
rojarsmith/Lab | lab-springboot/lab-springboot-security-oauth2-authorization-expansion/src/main/java/lab/springboot/authorization/controller/OauthController.java | 734 | package lab.springboot.authorization.controller;
import lab.springboot.authorization.config.SecurityProperties;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/oauth")
@RequiredArgsConstructor
public class OauthController {
private final @NonNull SecurityProperties securityProperties;
@GetMapping("login")
public String loginView(Model model) {
model.addAttribute("action", securityProperties.getLoginProcessingUrl());
return "form-login";
}
} | gpl-2.0 |
FauxFaux/jdk9-jdk | test/java/util/concurrent/locks/Lock/Mutex.java | 3212 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* A sample user extension of AbstractQueuedSynchronizer.
*/
public class Mutex implements Lock, java.io.Serializable {
private static class Sync extends AbstractQueuedSynchronizer {
public boolean isHeldExclusively() { return getState() == 1; }
public boolean tryAcquire(int acquires) {
assert acquires == 1; // Does not use multiple acquires
return compareAndSetState(0, 1);
}
public boolean tryRelease(int releases) {
setState(0);
return true;
}
Condition newCondition() { return new ConditionObject(); }
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
private final Sync sync = new Sync();
public void lock() {
sync.acquire(1);
}
public boolean tryLock() {
return sync.tryAcquire(1);
}
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
public void unlock() { sync.release(1); }
public Condition newCondition() { return sync.newCondition(); }
public boolean isLocked() { return sync.isHeldExclusively(); }
public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest16926.java | 2641 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest16926")
public class BenchmarkTest16926 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("foo");
String bar = doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
ProcessBuilder pb = new ProcessBuilder();
pb.command(args);
try {
Process p = pb.start();
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case");
throw new ServletException(e);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(1); // get the last 'safe' value
return bar;
}
}
| gpl-2.0 |
gengjian1203/PlayFace | app/src/main/java/com/mbpr/gengjian/playface/ViewPagerAdapter.java | 1100 | package com.mbpr.gengjian.playface;
import java.util.List;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
/**
* Created by gengjian on 15/12/23.
*/
public class ViewPagerAdapter extends PagerAdapter {
private List<View> views;
private Context context;
public ViewPagerAdapter(List<View> views, Context context) {
this.views = views;
this.context = context;
}
@Override
public void destroyItem(View container, int position, Object object) {
//super.destroyItem(container, position, object);
((ViewPager)container).removeView(views.get(position));
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(views.get(position));
return views.get(position);
}
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
| gpl-2.0 |
HexagonalDiamond/PlayerTraits | src/main/java/playertraits/traits/StrengthTrait.java | 430 | package playertraits.traits;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class StrengthTrait extends Trait {
public StrengthTrait() {
super("Strength");
}
@Override
public void tick(EntityPlayerMP player) {
player.addPotionEffect(new PotionEffect(Potion.damageBoost.id, 200, 1));
}
@Override
public void init() {
}
}
| gpl-2.0 |
tenlee2012/AllCode | JAVA/CodingkeStudy/src/com/day21/Proxy.java | 549 | package com.day21;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* 代理类
* @author tenlee
*
*/
public class Proxy implements InvocationHandler{
private Subject target;
public Proxy(Subject target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("做大量的评估");
method.invoke(target, args);
//代购之后要做的事
System.out.println("代购之后满意度调查");
return null;
}
}
| gpl-2.0 |
MikeLydeamore/LevellingTools | src/main/java/com/insane/levellingtools/Config.java | 877 | package com.insane.levellingtools;
import net.minecraftforge.common.config.Configuration;
import java.io.File;
/**
* Created by Michael on 11/08/2014.
*/
public class Config {
public static int baseXP;
public static int increasePerLevel;
public static int maxLevel;
public static void doConfig(File configFile) {
Configuration config = new Configuration(configFile);
config.load();
config.addCustomCategoryComment("XP Requirements","XP to level calculated as: RequiredXP = BaseXP + (Level-1)*increasePerLevel");
baseXP = config.get("XP Requirements", "BaseXP", 10, "[Default: 50]").getInt(10);
increasePerLevel = config.get("XP Requirements", "increasePerLevel", 10, "[Default: 20]").getInt(10);
maxLevel = config.get("Limits", "Maximum Level", 2, "[Default: 10]").getInt(2);
config.save();
}
}
| gpl-2.0 |
6306120058/Delay-Plane-Display-App | src/delay/model/Pesawat.java | 1027 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package delay.model;
/**
*
* @author M3 New
*/
public class Pesawat {
private String namaPesawat;
private String idPesawat;
private String idMaskapai;
public Pesawat(){
}
public Pesawat(String namaPesawat, String idPesawat, String idMaskapai) {
this.namaPesawat = namaPesawat;
this.idPesawat = idPesawat;
this.idMaskapai = idMaskapai;
}
public String getNamaPesawat() {
return namaPesawat;
}
public String getIdMaskapai() {
return idMaskapai;
}
public void setIdMaskapai(String idMaskapai) {
this.idMaskapai = idMaskapai;
}
public void setNamaPesawat(String namaPesawat) {
this.namaPesawat = namaPesawat;
}
public String getIdPesawat() {
return idPesawat;
}
public void setIdPesawat(String idPesawat) {
this.idPesawat = idPesawat;
}
}
| gpl-2.0 |
JohnDickerson/KidneyExchange | src/edu/cmu/cs/dickerson/kpd/solver/exception/SolverException.java | 219 | package edu.cmu.cs.dickerson.kpd.solver.exception;
public class SolverException extends Exception {
private static final long serialVersionUID = 1L;
public SolverException(String message) {
super(message);
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Gallery2/ext/src/com/mediatek/gallery3d/ext/ActivityHookerGroup.java | 3654 | package com.mediatek.gallery3d.ext;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
/**
* The composite pattern class.
* It will deliver every action to its leaf hookers.
*/
public class ActivityHookerGroup extends ActivityHooker {
private ArrayList<IActivityHooker> mHooks = new ArrayList<IActivityHooker>();
/**
* Add hooker to current group.
* @param hooker
* @return
*/
public boolean addHooker(IActivityHooker hooker) {
return mHooks.add(hooker);
}
/**
* Remove hooker from current group.
* @param hooker
* @return
*/
public boolean removeHooker(IActivityHooker hooker) {
return mHooks.remove(hooker);
}
/**
* Hooker size of current group.
* @return
*/
public int size() {
return mHooks.size();
}
/**
* Get hooker of requested location.
* @param index
* @return
*/
public IActivityHooker getHooker(int index) {
return mHooks.get(index);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (IActivityHooker hook : mHooks) {
hook.onCreate(savedInstanceState);
}
}
@Override
public void onStart() {
super.onStart();
for (IActivityHooker hook : mHooks) {
hook.onStart();
}
}
@Override
public void onResume() {
super.onResume();
for (IActivityHooker hook : mHooks) {
hook.onResume();
}
}
@Override
public void onPause() {
super.onPause();
for (IActivityHooker hook : mHooks) {
hook.onPause();
}
}
@Override
public void onStop() {
super.onStop();
for (IActivityHooker hook : mHooks) {
hook.onStop();
}
}
@Override
public void onDestroy() {
super.onDestroy();
for (IActivityHooker hook : mHooks) {
hook.onDestroy();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
boolean handle = false;
for (IActivityHooker hook : mHooks) {
boolean one = hook.onCreateOptionsMenu(menu);
if (!handle) {
handle = one;
}
}
return handle;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
boolean handle = false;
for (IActivityHooker hook : mHooks) {
boolean one = hook.onPrepareOptionsMenu(menu);
if (!handle) {
handle = one;
}
}
return handle;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
boolean handle = false;
for (IActivityHooker hook : mHooks) {
boolean one = hook.onOptionsItemSelected(item);
if (!handle) {
handle = one;
}
}
return handle;
}
@Override
public void setParameter(String key, Object value) {
super.setParameter(key, value);
for (IActivityHooker hook : mHooks) {
hook.setParameter(key, value);
}
}
@Override
public void init(Activity context, Intent intent) {
super.init(context, intent);
for (IActivityHooker hook : mHooks) {
hook.init(context, intent);
}
}
}
| gpl-2.0 |
jpschewe/fll-sw | src/main/java/fll/web/report/PromptSummarizeScores.java | 4759 | /*
* Copyright (c) 2015 High Tech Kids. All rights reserved
* HighTechKids is on the web at: http://www.hightechkids.org
* This code is released under GPL; see LICENSE.txt for details.
*/
package fll.web.report;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Set;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import javax.sql.DataSource;
import fll.Tournament;
import fll.db.Queries;
import fll.web.ApplicationAttributes;
import fll.web.AuthenticationContext;
import fll.web.BaseFLLServlet;
import fll.web.SessionAttributes;
import fll.web.UserRole;
import fll.web.WebUtils;
/**
* Support for and handle the result from promptSummarizeScores.jsp.
*/
@WebServlet("/report/PromptSummarizeScores")
public class PromptSummarizeScores extends BaseFLLServlet {
private static final org.apache.logging.log4j.Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger();
/**
* Session variable key for the URL to redirect to after score summarization.
*/
public static final String SUMMARY_REDIRECT_KEY = "summary_redirect";
@Override
protected void processRequest(final HttpServletRequest request,
final HttpServletResponse response,
final ServletContext application,
final HttpSession session)
throws IOException, ServletException {
final AuthenticationContext auth = SessionAttributes.getAuthentication(session);
if (!auth.requireRoles(request, response, session, Set.of(UserRole.HEAD_JUDGE), false)) {
return;
}
if (null != request.getParameter("recompute")) {
WebUtils.sendRedirect(application, response, "summarizePhase1.jsp");
} else {
final String url = SessionAttributes.getAttribute(session, SUMMARY_REDIRECT_KEY, String.class);
LOGGER.debug("redirect is {}", url);
if (null == url) {
WebUtils.sendRedirect(application, response, "index.jsp");
} else {
WebUtils.sendRedirect(application, response, url);
}
}
}
/**
* Check if summary scores need to be updated. If they do, redirect and set
* the session variable SUMMARY_REDIRECT to point to
* redirect.
*
* @param response used to send a redirect
* @param application the application context
* @param session the session context
* @param redirect the page to visit once the scores have been summarized
* @return if the summary scores need to be updated, the calling method should
* return immediately if this is true as a redirect has been executed.
*/
public static boolean checkIfSummaryUpdated(final HttpServletResponse response,
final ServletContext application,
final HttpSession session,
final String redirect) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("top check if summary updated");
}
final AuthenticationContext auth = SessionAttributes.getAuthentication(session);
if (!auth.isHeadJudge()) {
// only the head judge can summarize scores, so don't prompt others to summarize
// the scores
return false;
}
final DataSource datasource = ApplicationAttributes.getDataSource(application);
try (Connection connection = datasource.getConnection()) {
final int tournamentId = Queries.getCurrentTournament(connection);
final Tournament tournament = Tournament.findTournamentByID(connection, tournamentId);
if (tournament.checkTournamentNeedsSummaryUpdate(connection)) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Needs summary update");
}
if (null != session.getAttribute(SUMMARY_REDIRECT_KEY)) {
LOGGER.debug("redirect has already been set, it must be the case that the user is skipping summarization, allow it");
return false;
} else {
session.setAttribute(SUMMARY_REDIRECT_KEY, redirect);
WebUtils.sendRedirect(application, response, "/report/promptSummarizeScores.jsp");
return true;
}
} else {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("No updated needed");
}
return false;
}
} catch (final SQLException e) {
LOGGER.error(e, e);
throw new RuntimeException(e);
} catch (final IOException e) {
LOGGER.error(e, e);
throw new RuntimeException(e);
}
}
}
| gpl-2.0 |
phantamanta44/BotAgainstHumanity | src/main/java/io/github/phantamanta44/botah/core/context/GenericEventContext.java | 2047 | package io.github.phantamanta44.botah.core.context;
import io.github.phantamanta44.botah.core.rate.RateLimitedChannel;
import io.github.phantamanta44.botah.util.MessageUtils;
import sx.blah.discord.api.Event;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IMessage;
import sx.blah.discord.handle.obj.IUser;
import java.lang.reflect.Method;
public class GenericEventContext implements IEventContext {
private Class<? extends Event> clazz;
private long timestamp;
private IGuild guild;
private IChannel channel;
private IUser user;
private IMessage msg;
public GenericEventContext(Event event) {
timestamp = System.currentTimeMillis();
clazz = event.getClass();
Method[] methods = clazz.getMethods();
for (Method m : methods) {
try {
if (m.getName().equalsIgnoreCase("getUser"))
user = (IUser)m.invoke(event);
else if (m.getName().equalsIgnoreCase("getChannel")) {
channel = new RateLimitedChannel((IChannel)m.invoke(event));
guild = channel.getGuild();
}
else if (m.getName().equalsIgnoreCase("getMessage")) {
msg = (IMessage)m.invoke(event);
user = msg.getAuthor();
channel = new RateLimitedChannel(msg.getChannel());
guild = channel.getGuild();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Override
public void sendMessage(String msg) {
if (channel != null)
MessageUtils.sendMessage(channel, msg);
else
throw new UnsupportedOperationException();
}
@Override
public void sendMessage(String format, Object... args) {
sendMessage(String.format(format, args));
}
@Override
public long getTimestamp() {
return timestamp;
}
@Override
public Class<? extends Event> getType() {
return clazz;
}
@Override
public IGuild getGuild() {
return guild;
}
@Override
public IChannel getChannel() {
return channel;
}
@Override
public IUser getUser() {
return user;
}
@Override
public IMessage getMessage() {
return msg;
}
}
| gpl-2.0 |
biddyweb/checker-framework | checker/tests/regex/MatcherGroupCount.java | 944 | // Test case for Issue 291
// https://code.google.com/p/checker-framework/issues/detail?id=291
// @skip-test
import java.util.regex.*;
import org.checkerframework.checker.regex.RegexUtil;
public class MatcherGroupCount {
public static void main(String[] args) {
String regex = args[0];
String content = args[1];
if (!RegexUtil.isRegex(regex)) {
System.out.println("Error parsing regex \"" + regex + "\": " +
RegexUtil.regexException(regex).getMessage());
System.exit(1);
}
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(content);
if (mat.matches()) {
if (mat.groupCount() > 0) {
System.out.println("Group: " + mat.group(1));
} else {
System.out.println("No group found!");
}
} else {
System.out.println("No match!");
}
}
}
| gpl-2.0 |
UnboundID/ldapsdk | src/com/unboundid/ldap/sdk/unboundidds/tools/SplitLDIFFilterTranslator.java | 11362 | /*
* Copyright 2016-2020 Ping Identity Corporation
* All Rights Reserved.
*/
/*
* Copyright 2016-2020 Ping Identity Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2016-2020 Ping Identity Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPLv2 only)
* or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
* 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 General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*/
package com.unboundid.ldap.sdk.unboundidds.tools;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.unboundid.ldap.sdk.DN;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.RDN;
import com.unboundid.ldap.sdk.schema.Schema;
import com.unboundid.ldif.LDIFException;
import com.unboundid.util.Debug;
import com.unboundid.util.NotNull;
import com.unboundid.util.Nullable;
import com.unboundid.util.StaticUtils;
import com.unboundid.util.ThreadSafety;
import com.unboundid.util.ThreadSafetyLevel;
import static com.unboundid.ldap.sdk.unboundidds.tools.ToolMessages.*;
/**
* This class provides an implementation of an LDIF reader entry translator that
* can be used to determine the set into which an entry should be placed by
* selecting the first set for which the associated filter matches the entry.
* <BR>
* <BLOCKQUOTE>
* <B>NOTE:</B> This class, and other classes within the
* {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
* supported for use against Ping Identity, UnboundID, and
* Nokia/Alcatel-Lucent 8661 server products. These classes provide support
* for proprietary functionality or for external specifications that are not
* considered stable or mature enough to be guaranteed to work in an
* interoperable way with other types of LDAP servers.
* </BLOCKQUOTE>
*/
@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
final class SplitLDIFFilterTranslator
extends SplitLDIFTranslator
{
// The map used to cache decisions made by this translator.
@Nullable private final ConcurrentHashMap<String,Set<String>> rdnCache;
// A map used to associate the search filter for each set with the name of
// that set.
@NotNull private final Map<Filter,Set<String>> setFilters;
// A map of the names that will be used for each of the sets.
@NotNull private final Map<Integer,Set<String>> setNames;
// The schema to use for filter evaluation.
@Nullable private final Schema schema;
// The sets in which entries outside the split base should be placed.
@NotNull private final Set<String> outsideSplitBaseSetNames;
// The sets in which the split base entry should be placed.
@NotNull private final Set<String> splitBaseEntrySetNames;
/**
* Creates a new instance of this translator with the provided information.
*
* @param splitBaseDN The base DN below which to
* split entries.
* @param schema The schema to use for filter
* evaluation.
* @param filters The filters to use to select
* the appropriate backend set.
* This must not be
* {@code null} or empty.
* @param assumeFlatDIT Indicates whether to assume
* that the DIT is flat, and
* there aren't any entries more
* than one level below the
* split base DN. If this is
* {@code true}, then any
* entries more than one level
* below the split base DN will
* be considered an error.
* @param addEntriesOutsideSplitToAllSets Indicates whether entries
* outside the split should be
* added to all sets.
* @param addEntriesOutsideSplitToDedicatedSet Indicates whether entries
* outside the split should be
* added to all sets.
*/
SplitLDIFFilterTranslator(@NotNull final DN splitBaseDN,
@Nullable final Schema schema,
@NotNull final LinkedHashSet<Filter> filters,
final boolean assumeFlatDIT,
final boolean addEntriesOutsideSplitToAllSets,
final boolean addEntriesOutsideSplitToDedicatedSet)
{
super(splitBaseDN);
this.schema = schema;
if (assumeFlatDIT)
{
rdnCache = null;
}
else
{
rdnCache = new ConcurrentHashMap<>(StaticUtils.computeMapCapacity(100));
}
final int numSets = filters.size();
outsideSplitBaseSetNames =
new LinkedHashSet<>(StaticUtils.computeMapCapacity(numSets+1));
splitBaseEntrySetNames =
new LinkedHashSet<>(StaticUtils.computeMapCapacity(numSets));
if (addEntriesOutsideSplitToDedicatedSet)
{
outsideSplitBaseSetNames.add(SplitLDIFEntry.SET_NAME_OUTSIDE_SPLIT);
}
setFilters = new LinkedHashMap<>(StaticUtils.computeMapCapacity(numSets));
setNames = new LinkedHashMap<>(StaticUtils.computeMapCapacity(numSets));
int i=0;
for (final Filter f : filters)
{
final String setName = ".set" + (i+1);
final Set<String> sets = Collections.singleton(setName);
splitBaseEntrySetNames.add(setName);
if (addEntriesOutsideSplitToAllSets)
{
outsideSplitBaseSetNames.add(setName);
}
setFilters.put(f, sets);
setNames.put(i, sets);
i++;
}
}
/**
* {@inheritDoc}
*/
@Override()
@NotNull()
public SplitLDIFEntry translate(@NotNull final Entry original,
final long firstLineNumber)
throws LDIFException
{
// Get the parsed DN for the entry. If we can't, that's an error and we
// should only include it in the error set.
final DN dn;
try
{
dn = original.getParsedDN();
}
catch (final LDAPException le)
{
Debug.debugException(le);
return createEntry(original,
ERR_SPLIT_LDIF_FILTER_TRANSLATOR_CANNOT_PARSE_DN.get(
le.getMessage()),
getErrorSetNames());
}
// If the parsed DN is outside the split base DN, then return the
// appropriate sets for that.
if (! dn.isDescendantOf(getSplitBaseDN(), true))
{
return createEntry(original, outsideSplitBaseSetNames);
}
// If the parsed DN matches the split base DN, then it will always go into
// all of the split sets.
if (dn.equals(getSplitBaseDN()))
{
return createEntry(original, splitBaseEntrySetNames);
}
// Determine which RDN component is immediately below the split base DN.
final RDN[] rdns = dn.getRDNs();
final int targetRDNIndex = rdns.length - getSplitBaseRDNs().length - 1;
final String normalizedRDNString =
rdns[targetRDNIndex].toNormalizedString();
// If the target RDN component is not the first component of the DN, then
// we'll use the cache to send this entry to the same set as its parent.
if (targetRDNIndex > 0)
{
// If we aren't maintaining an RDN cache (which should only happen if
// the --assumeFlatDIT argument was provided), then this is an error.
if (rdnCache == null)
{
return createEntry(original,
ERR_SPLIT_LDIF_FILTER_TRANSLATOR_NON_FLAT_DIT.get(
getSplitBaseDN().toString()),
getErrorSetNames());
}
// Note that even if we are maintaining an RDN cache, it may not contain
// the information that we need to determine which set should hold this
// entry. There are two reasons for this:
//
// - The LDIF file contains an entry below the split base DN without
// including the parent for that entry, (or includes a child entry
// before its parent).
//
// - We are processing multiple entries in parallel, and the parent entry
// is currently being processed in another thread and that thread hasn't
// yet made the determination as to which set should be used for that
// parent entry.
//
// In either case, use null for the target set names. If we are in the
// parallel processing phase, then we will re-invoke this method later
// at a point in which we can be confident that the caching should have
// been performed If we still get null the second time through, then
// the caller will consider that an error and handle it appropriately.
return createEntry(original, rdnCache.get(normalizedRDNString));
}
// At this point, we know that the entry is exactly one level below the
// split base DN. Iterate through the filters and see if any of them
// matches the entry.
for (final Map.Entry<Filter,Set<String>> e : setFilters.entrySet())
{
final Filter f = e.getKey();
try
{
if (f.matchesEntry(original, schema))
{
final Set<String> sets = e.getValue();
if (rdnCache != null)
{
rdnCache.put(normalizedRDNString, sets);
}
return createEntry(original, sets);
}
}
catch (final Exception ex)
{
Debug.debugException(ex);
}
}
// If we've gotten here, then none of the filters matched so pick a set
// based on a hash of the RDN.
final SplitLDIFEntry e = createFromRDNHash(original, dn, setNames);
if (rdnCache != null)
{
rdnCache.put(normalizedRDNString, e.getSets());
}
return e;
}
}
| gpl-2.0 |
unktomi/form-follows-function | mjavac/langtools/src/share/classes/javax/lang/model/type/UnknownTypeException.java | 2970 | /*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.lang.model.type;
/**
* Indicates that an unknown kind of type was encountered. This can
* occur if the language evolves and new kinds of types are added to
* the {@code TypeMirror} hierarchy. May be thrown by a {@linkplain
* TypeVisitor type visitor} to indicate that the visitor was created
* for a prior version of the language.
*
* @author Joseph D. Darcy
* @author Scott Seligman
* @author Peter von der Ahé
* @see TypeVisitor#visitUnknown
* @since 1.6
*/
public class UnknownTypeException extends RuntimeException {
private static final long serialVersionUID = 269L;
private transient TypeMirror type;
private transient Object parameter;
/**
* Creates a new {@code UnknownTypeException}.The {@code p}
* parameter may be used to pass in an additional argument with
* information about the context in which the unknown type was
* encountered; for example, the visit methods of {@link
* TypeVisitor} may pass in their additional parameter.
*
* @param t the unknown type, may be {@code null}
* @param p an additional parameter, may be {@code null}
*/
public UnknownTypeException(TypeMirror t, Object p) {
super("Unknown type: " + t);
type = t;
this.parameter = p;
}
/**
* Returns the unknown type.
* The value may be unavailable if this exception has been
* serialized and then read back in.
*
* @return the unknown type, or {@code null} if unavailable
*/
public TypeMirror getUnknownType() {
return type;
}
/**
* Returns the additional argument.
*
* @return the additional argument
*/
public Object getArgument() {
return parameter;
}
}
| gpl-2.0 |
unktomi/form-follows-function | mjavac/langtools/test/tools/javac/generics/ArrayTypearg.java | 1406 | /*
* Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4881205
* @summary generics: array as generic argument type fails
* @author gafter
*
* @compile -source 1.5 ArrayTypearg.java
*/
import java.util.List;
import java.util.ArrayList;
class ArrayTypearg {
private void foo() {
List<Object[]> list = new ArrayList<Object[]>();
Object o1 = list.get(0)[0];
}
}
| gpl-2.0 |
MISO4203-201520/mp-books | MarketPlace.web/src/main/java/co/edu/uniandes/csw/marketplace/providers/StatusCreated.java | 253 | package co.edu.uniandes.csw.marketplace.providers;
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface StatusCreated {}
| gpl-2.0 |
vs49688/RAFTools | src/main/java/net/vs49688/rafview/wwise/objects/EventActionObject.java | 1110 | /*
* RAFTools - Copyright (C) 2016 Zane van Iperen.
* Contact: zane@zanevaniperen.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, and only
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Any and all GPL restrictions may be circumvented with permission from the
* the original author.
*/
package net.vs49688.rafview.wwise.objects;
import java.nio.*;
public class EventActionObject extends WwiseObject {
public EventActionObject(int id, long length, ByteBuffer bb) {
super(id, length);
}
}
| gpl-2.0 |
Apacio/react-native-google-vr-panorama | android/src/main/java/com/xebia/googlevrpanorama/RNGoogleVRPanoramaView.java | 9255 | package com.xebia.googlevrpanorama;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.UiThread;
import android.util.Log;
import android.util.Pair;
import android.util.LruCache;
import android.widget.RelativeLayout;
import android.content.res.AssetManager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
import com.google.vr.sdk.widgets.pano.VrPanoramaView.Options;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.lang.Runtime;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
public class RNGoogleVRPanoramaView extends RelativeLayout {
private static final String TAG = RNGoogleVRPanoramaView.class.getSimpleName();
// public static Bitmap bitmap = null;
// public Bitmap bitmap = null;
private android.os.Handler _handler;
private RNGoogleVRPanoramaViewManager _manager;
private Activity _activity;
private VrPanoramaView panoWidgetView;
private ImageLoaderTask imageLoaderTask;
private Options panoOptions = new Options();
private LruCache<String, Bitmap> mMemoryCache;
private URL imageUrl = null;
private String url;
private int imageWidth;
private int imageHeight;
private boolean showFullScreen = false;
private boolean showStereo = false;
private boolean showInfo = false;
private boolean isLocalUrl = false;
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
@UiThread
public RNGoogleVRPanoramaView(Context context, RNGoogleVRPanoramaViewManager manager, Activity activity) {
super(context);
_handler = new android.os.Handler();
_manager = manager;
_activity = activity;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
public void setStereo(boolean showStereo) {
this.showStereo = showStereo;
}
public void setInfo(boolean showInfo) {
this.showInfo = showInfo;
}
public void setFullScreen(boolean showFullScreen) {
this.showFullScreen = showFullScreen;
}
public void clear() {
/*
Log.d("Surya", "Clearing bitmap");
this.bitmap.recycle();
*/
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
public void onAfterUpdateTransaction(Context context) {
panoWidgetView = new VrPanoramaView(_activity);
panoWidgetView.setEventListener(new ActivityEventListener());
panoWidgetView.setStereoModeButtonEnabled(showStereo);
panoWidgetView.setInfoButtonEnabled(showInfo);
panoWidgetView.setFullscreenButtonEnabled(showFullScreen);
this.addView(panoWidgetView);
if (imageLoaderTask != null) {
imageLoaderTask.cancel(true);
}
imageLoaderTask = new ImageLoaderTask(context);
imageLoaderTask.execute(Pair.create(imageUrl, panoOptions));
}
public void setImageUrl(String value) {
if (imageUrl != null && imageUrl.toString().equals(value)) { return; }
url = value;
isLocalUrl = true;
}
public void setDimensions(int width, int height) {
this.imageWidth = width;
this.imageHeight = height;
}
public void setInputType(int value) {
if (panoOptions.inputType == value) { return; }
panoOptions.inputType = value;
}
class ImageLoaderTask extends AsyncTask<Pair<URL, Options>, Void, Boolean> {
private Context mContext;
public ImageLoaderTask (Context context){
mContext = context;
}
protected Boolean doInBackground(Pair<URL, Options>... fileInformation) {
/*
if (RNGoogleVRPanoramaView.bitmap != null) {
RNGoogleVRPanoramaView.bitmap.recycle();
RNGoogleVRPanoramaView.bitmap = null;
}
*/
final URL imageUrl = fileInformation[0].first;
Options panoOptions = fileInformation[0].second;
InputStream istr = null;
Log.d(TAG, "Image loader task is called: " + url);
Bitmap image = getBitmapFromMemCache(url);
if (image == null) {
if (!isLocalUrl) {
try {
HttpURLConnection connection = (HttpURLConnection) fileInformation[0].first.openConnection();
connection.connect();
istr = connection.getInputStream();
image = decodeSampledBitmap(istr);
} catch (IOException e) {
Log.e(TAG, "Could not load file: " + e);
return false;
} finally {
try {
if (istr!=null) {
istr.close();
}
} catch (IOException e) {
Log.e(TAG, "Could not close input stream: " + e);
}
}
} else {
AssetManager assetManager = mContext.getAssets();
try {
istr = assetManager.open(url);
image = BitmapFactory.decodeStream(istr);
} catch (IOException e) {
Log.e(TAG, "Could not decode default bitmap: " + e);
return false;
}
}
}
if (image != null) {
//bitmap = image;
Log.d(TAG, "Image does exist, so we're adding it to the pano: " + url);
//Bitmap temp = getBitmapFromMemCache(url);
//RNGoogleVRPanoramaView.bitmap = temp;
panoWidgetView.loadImageFromBitmap(image, panoOptions);
try {
istr.close();
} catch (IOException e) {
Log.e(TAG, "Could not close input stream: " + e);
}
}
return true;
}
private Bitmap decodeSampledBitmap(InputStream inputStream) throws IOException {
final byte[] bytes = getBytesFromInputStream(inputStream);
BitmapFactory.Options options = new BitmapFactory.Options();
if(imageWidth != 0 && imageHeight != 0) {
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
options.inSampleSize = calculateInSampleSize(options, imageWidth, imageHeight);
options.inJustDecodeBounds = false;
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
private byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStream, baos);
return baos.toByteArray();
}
private int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
private class ActivityEventListener extends VrPanoramaEventListener {
@Override
public void onLoadSuccess() {
emitEvent("onImageLoaded", null);
}
@Override
public void onLoadError(String errorMessage) {
Log.e(TAG, "Error loading pano: " + errorMessage);
emitEvent("onImageLoadingFailed", null);
}
}
void emitEvent(String name, @Nullable WritableMap event) {
if (event == null) {
event = Arguments.createMap();
}
((ReactContext)getContext())
.getJSModule(RCTEventEmitter.class)
.receiveEvent(getId(), name, event);
}
}
| gpl-2.0 |
stereokrauts/stereoscope | stereoscope/src/main/java/model/protocol/osc/touchosc/SnappingFader.java | 671 | package model.protocol.osc.touchosc;
public class SnappingFader {
static final float SNAP_DELTA = 0.1f;
private double currentRealValue;
public SnappingFader(final double currentRealValue) {
this.currentRealValue = currentRealValue;
}
public void tryUpdate(final double value, final ISnappingFaderEventHandler handler) {
if (isInBoundary(value)) {
currentRealValue = value;
handler.snapSucceeded();
} else {
handler.snapFailed();
}
}
public void forceUpdate(final double value) {
currentRealValue = value;
}
public boolean isInBoundary(final double receivedValue) {
return Math.abs(receivedValue - currentRealValue) <= SNAP_DELTA;
}
}
| gpl-2.0 |
GreenGas48/Feed-The-Max | RobotsActivity.java | 3148 | package com.holdit.feedthemax;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import static com.holdit.feedthemax.MainActivity.rbt1qu;
import static com.holdit.feedthemax.R.id.rbt1price;
import static com.holdit.feedthemax.R.id.rbt2price;
import static com.holdit.feedthemax.R.id.rbt3price;
/**
* Created by Antek on 2017-05-10.
* Activity started after robot button pressed
*/
public class RobotsActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.robots_layout);
//final MainActivity mact = new MainActivity();
RelativeLayout rbt1rl = (RelativeLayout) findViewById(R.id.rbt1rl);
RelativeLayout rbt2rl = (RelativeLayout) findViewById(R.id.rbt2rl);
RelativeLayout rbt3rl = (RelativeLayout) findViewById(R.id.rbt3rl);
final TextView rbt1prc = (TextView) findViewById(rbt1price);
rbt1prc.setText(MainActivity.rbt1price + "C");
final TextView rbt2prc = (TextView) findViewById(rbt2price);
rbt2prc.setText(MainActivity.rbt2price + "C");
final TextView rbt3prc = (TextView) findViewById(rbt3price);
rbt3prc.setText(MainActivity.rbt3price + "C");
rbt1rl.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (MainActivity.cookies >= MainActivity.rbt1price) {
MainActivity.cookies -= MainActivity.rbt1price;
MainActivity.cps ++;
MainActivity.rbt1qu++;
MainActivity.rbt1price = (int) (100 * Math.pow(1.15, MainActivity.rbt1qu));
rbt1prc.setText(MainActivity.rbt1price + "C");
}
}
});
rbt2rl.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (MainActivity.cookies >= MainActivity.rbt2price) {
MainActivity.cookies -= MainActivity.rbt2price;
MainActivity.cps += 8;
MainActivity.rbt2qu++;
MainActivity.rbt2price = (int) (1100 * Math.pow(1.15, MainActivity.rbt2qu));
rbt2prc.setText(MainActivity.rbt2price + "C");
}
}
});
rbt3rl.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (MainActivity.cookies >= MainActivity.rbt3price) {
MainActivity.cookies -= MainActivity.rbt3price;
MainActivity.cps += 47;
MainActivity.rbt3qu++;
MainActivity.rbt3price = (int) (12000 * Math.pow(1.15, MainActivity.rbt3qu));
rbt3prc.setText(MainActivity.rbt3price + "C");
}
}
});
}
}
| gpl-2.0 |
RanHuang/AndroidProject | WiFi P2p/WifiP2pApp/src/hrylab/xjtu/wifip2papp/wifidirect/WifiPeerListListener.java | 1609 | package hrylab.xjtu.wifip2papp.wifidirect;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
/*
* @author NickHuang
*/
public class WifiPeerListListener implements PeerListListener{
private static final String TAG = "WifiPeerListListener";
private static final boolean D = true;
private WifiConnector mConnector;
private ExecutorService mExecutor;
public WifiPeerListListener(WifiConnector mConnector){
this.mConnector = mConnector;
mExecutor = Executors.newCachedThreadPool();
}
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
// TODO Auto-generated method stub
mExecutor.submit(new UpdateAvailableWifiDevices(peers));
}
private class UpdateAvailableWifiDevices implements Runnable{
private WifiP2pDeviceList wifiP2pDeviceList;
public UpdateAvailableWifiDevices(WifiP2pDeviceList wifiP2pDeviceList){
this.wifiP2pDeviceList = wifiP2pDeviceList;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(D) Log.d(TAG, "Peers available. Count = " + wifiP2pDeviceList.getDeviceList().size());
mConnector.clearPeersWifiP2pDevices();
/*
for(WifiP2pDevice device : wifiP2pDeviceList.getDeviceList()){
Log.d(TAG, "Available device: " + device.deviceName);
mConnector.addWifiP2pDevice(device);
}
*/
mConnector.addAllPeersWifiP2pDevices(wifiP2pDeviceList.getDeviceList());
mConnector.sendPeersAvaliableBroadcast();
}
}
}
| gpl-2.0 |
ricardobaumann/android | libs/android_application_2d_adventure_game-master/andenginetmxtiledmapartifactfixer-6410e89ad5e3/test/org/anddev/andengine/entity/layer/tiled/tmx/TMXTiledMapArtifactFixerTest.java | 1740 | package org.anddev.andengine.entity.layer.tiled.tmx;
import static junit.framework.Assert.assertEquals;
import java.io.File;
import org.junit.Test;
/**
* @author Nicolas Gramlich
* @since 21:21:51 - 28.07.2010
*/
public class TMXTiledMapArtifactFixerTest {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
@Test
public void testDetermineTileColumnCount() throws Exception {
assertEquals(8, TMXTiledMapArtifactFixer.determineCount(265, 32, 1, 1));
assertEquals(6, TMXTiledMapArtifactFixer.determineCount(199, 32, 1, 1));
}
@Test
public void testGenerateOutputFile() throws Exception {
assertEquals("C:\\Test\\fixed_bla.png", TMXTiledMapArtifactFixer.generateOutputFile(new File("C:\\Test\\bla.png")).toString());
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| gpl-2.0 |
cristian0193/EstructuraDatos | ProyectoFinalBaresUCC/src/Vistas/Productos.java | 9862 | package Vistas;
import Conexion.ConexioSQLite;
import static Vistas.Cuenta.modeloCuenta;
import static Vistas.Cuenta.sumaProductos;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class Productos extends javax.swing.JDialog {
public static DefaultTableModel modelo;
public static ConexioSQLite conexion;
public Cuenta cuenta;
public static String valor;
public Productos(java.awt.Frame parent, boolean modal, String idMesa) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
cargar_tabla_productos();
valor = idMesa;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tabla_productos = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txt_cantidad = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("PRODUCTOS");
tabla_productos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabla_productos.setRowHeight(23);
jScrollPane1.setViewportView(tabla_productos);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Agregar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Cantidad :");
txt_cantidad.setFont(new java.awt.Font("Tahoma", 1, 22)); // NOI18N
txt_cantidad.setForeground(new java.awt.Color(255, 0, 0));
txt_cantidad.setHorizontalAlignment(javax.swing.JTextField.CENTER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 541, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_cantidad, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
String id = "", producto = "";
int subtotal = 0, precio = 0, cantidad = 0;
int select = tabla_productos.getSelectedRow();
if (select == -1) {
JOptionPane.showMessageDialog(null, "Seleccione una Fila");
} else {
if (txt_cantidad.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Ingrese la Cantidad");
} else {
cantidad = Integer.parseInt(txt_cantidad.getText());
if (cantidad <= 0) {
JOptionPane.showMessageDialog(null, "La cantidad debe ser mayor a (0) ");
} else {
id = tabla_productos.getValueAt(select, 0).toString();
producto = tabla_productos.getValueAt(select, 1).toString();
precio = Integer.parseInt(tabla_productos.getValueAt(select, 2).toString());
subtotal = (precio * cantidad);
Object datos[] = {id, producto, precio, cantidad, subtotal};
modeloCuenta.addRow(datos);
}
}
}
}//GEN-LAST:event_jButton1ActionPerformed
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(Productos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the dialog */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// Productos dialog = new Productos(new javax.swing.JFrame(), true, valor);
// dialog.addWindowListener(new java.awt.event.WindowAdapter() {
// @Override
// public void windowClosing(java.awt.event.WindowEvent e) {
// System.exit(0);
// }
// });
// dialog.setVisible(true);
// }
// });
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tabla_productos;
private javax.swing.JTextField txt_cantidad;
// End of variables declaration//GEN-END:variables
// METODO PARA CARGAR TABLA PROYECTOS
public void cargar_tabla_productos() {
try {
conexion = new ConexioSQLite();
conexion.coneccionbase();
String[] titulos = {"ID", "PRODUCTO", "PRECIO"};
String[] registro = new String[3];
modelo = new DefaultTableModel(null, titulos);
try {
ResultSet rs = conexion.consultaProductos();
while (rs.next()) {
registro[0] = rs.getString("ID");
registro[1] = rs.getString("DESCRIPCION");
registro[2] = rs.getString("PRECIO");
modelo.addRow(registro);
}
tabla_productos.setModel(modelo);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
} catch (Exception ex) {
Logger.getLogger(Productos.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| gpl-2.0 |
pja35/ThePyBotWarPro | src/main/java/helper/GhostGlassPane.java | 1128 | package helper;
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class GhostGlassPane extends JPanel
{
private AlphaComposite composite;
private BufferedImage dragged = null;
private Point location = new Point(0, 0);
public GhostGlassPane()
{
setOpaque(false);
composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
}
public void setImage(BufferedImage dragged)
{
this.dragged = dragged;
}
public void setPoint(Point location)
{
this.location = location;
}
public void paintComponent(Graphics g)
{
if (dragged == null)
return;
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(composite);
g2.drawImage(dragged,
(int) (location.getX() - (dragged.getWidth(this) / 2)),
(int) (location.getY() - (dragged.getHeight(this) / 2)),
null);
}
} | gpl-2.0 |
h3xstream/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00544.java | 2453 | /**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark 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, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/xss-01/BenchmarkTest00544")
public class BenchmarkTest00544 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = "";
boolean flag = true;
java.util.Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements() && flag) {
String name = (String) names.nextElement();
String[] values = request.getParameterValues(name);
if (values != null) {
for(int i=0;i<values.length && flag; i++){
String value = values[i];
if (value.equals("BenchmarkTest00544")) {
param = name;
flag = false;
}
}
}
}
String bar = "alsosafe";
if (param != null) {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
bar = valuesList.get(1); // get the last 'safe' value
}
response.setHeader("X-XSS-Protection", "0");
response.getWriter().print(bar.toCharArray());
}
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | src/java.base/share/classes/java/util/concurrent/atomic/AtomicLongArray.java | 18582 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.function.LongBinaryOperator;
import java.util.function.LongUnaryOperator;
/**
* A {@code long} array in which elements may be updated atomically.
* See the {@link VarHandle} specification for descriptions of the
* properties of atomic accesses.
* @since 1.5
* @author Doug Lea
*/
public class AtomicLongArray implements java.io.Serializable {
private static final long serialVersionUID = -2308431214976778248L;
private static final VarHandle AA
= MethodHandles.arrayElementVarHandle(long[].class);
private final long[] array;
/**
* Creates a new AtomicLongArray of the given length, with all
* elements initially zero.
*
* @param length the length of the array
*/
public AtomicLongArray(int length) {
array = new long[length];
}
/**
* Creates a new AtomicLongArray with the same length as, and
* all elements copied from, the given array.
*
* @param array the array to copy elements from
* @throws NullPointerException if array is null
*/
public AtomicLongArray(long[] array) {
// Visibility guaranteed by final field guarantees
this.array = array.clone();
}
/**
* Returns the length of the array.
*
* @return the length of the array
*/
public final int length() {
return array.length;
}
/**
* Returns the current value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getVolatile}.
*
* @param i the index
* @return the current value
*/
public final long get(int i) {
return (long)AA.getVolatile(array, i);
}
/**
* Sets the element at index {@code i} to {@code newValue},
* with memory effects as specified by {@link VarHandle#setVolatile}.
*
* @param i the index
* @param newValue the new value
*/
public final void set(int i, long newValue) {
AA.setVolatile(array, i, newValue);
}
/**
* Sets the element at index {@code i} to {@code newValue},
* with memory effects as specified by {@link VarHandle#setRelease}.
*
* @param i the index
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int i, long newValue) {
AA.setRelease(array, i, newValue);
}
/**
* Atomically sets the element at index {@code i} to {@code
* newValue} and returns the old value,
* with memory effects as specified by {@link VarHandle#getAndSet}.
*
* @param i the index
* @param newValue the new value
* @return the previous value
*/
public final long getAndSet(int i, long newValue) {
return (long)AA.getAndSet(array, i, newValue);
}
/**
* Atomically sets the element at index {@code i} to {@code newValue}
* if the element's current value {@code == expectedValue},
* with memory effects as specified by {@link VarHandle#compareAndSet}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int i, long expectedValue, long newValue) {
return AA.compareAndSet(array, i, expectedValue, newValue);
}
/**
* Possibly atomically sets the element at index {@code i} to
* {@code newValue} if the element's current value {@code == expectedValue},
* with memory effects as specified by {@link VarHandle#weakCompareAndSet}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(int i, long expectedValue, long newValue) {
return AA.weakCompareAndSet(array, i, expectedValue, newValue);
}
/**
* Atomically increments the value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getAndAdd}.
*
* <p>Equivalent to {@code getAndAdd(i, 1)}.
*
* @param i the index
* @return the previous value
*/
public final long getAndIncrement(int i) {
return (long)AA.getAndAdd(array, i, 1L);
}
/**
* Atomically decrements the value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getAndAdd}.
*
* <p>Equivalent to {@code getAndAdd(i, -1)}.
*
* @param i the index
* @return the previous value
*/
public final long getAndDecrement(int i) {
return (long)AA.getAndAdd(array, i, -1L);
}
/**
* Atomically adds the given value to the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getAndAdd}.
*
* @param i the index
* @param delta the value to add
* @return the previous value
*/
public final long getAndAdd(int i, long delta) {
return (long)AA.getAndAdd(array, i, delta);
}
/**
* Atomically increments the value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#addAndGet}.
*
* <p>Equivalent to {@code addAndGet(i, 1)}.
*
* @param i the index
* @return the updated value
*/
public final long incrementAndGet(int i) {
return (long)AA.addAndGet(array, i, 1L);
}
/**
* Atomically decrements the value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#addAndGet}.
*
* <p>Equivalent to {@code addAndGet(i, -1)}.
*
* @param i the index
* @return the updated value
*/
public final long decrementAndGet(int i) {
return (long)AA.addAndGet(array, i, -1L);
}
/**
* Atomically adds the given value to the element at index {@code i},
* with memory effects as specified by {@link VarHandle#addAndGet}.
*
* @param i the index
* @param delta the value to add
* @return the updated value
*/
public long addAndGet(int i, long delta) {
return (long)AA.addAndGet(array, i, delta);
}
/**
* Atomically updates the element at index {@code i} with the results
* of applying the given function, returning the previous value. The
* function should be side-effect-free, since it may be re-applied
* when attempted updates fail due to contention among threads.
*
* @param i the index
* @param updateFunction a side-effect-free function
* @return the previous value
* @since 1.8
*/
public final long getAndUpdate(int i, LongUnaryOperator updateFunction) {
long prev = get(i), next = 0L;
for (boolean haveNext = false;;) {
if (!haveNext)
next = updateFunction.applyAsLong(prev);
if (weakCompareAndSetVolatile(i, prev, next))
return prev;
haveNext = (prev == (prev = get(i)));
}
}
/**
* Atomically updates the element at index {@code i} with the results
* of applying the given function, returning the updated value. The
* function should be side-effect-free, since it may be re-applied
* when attempted updates fail due to contention among threads.
*
* @param i the index
* @param updateFunction a side-effect-free function
* @return the updated value
* @since 1.8
*/
public final long updateAndGet(int i, LongUnaryOperator updateFunction) {
long prev = get(i), next = 0L;
for (boolean haveNext = false;;) {
if (!haveNext)
next = updateFunction.applyAsLong(prev);
if (weakCompareAndSetVolatile(i, prev, next))
return next;
haveNext = (prev == (prev = get(i)));
}
}
/**
* Atomically updates the element at index {@code i} with the
* results of applying the given function to the current and given
* values, returning the previous value. The function should be
* side-effect-free, since it may be re-applied when attempted
* updates fail due to contention among threads. The function is
* applied with the current value of the element at index {@code i}
* as its first argument, and the given update as the second
* argument.
*
* @param i the index
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the previous value
* @since 1.8
*/
public final long getAndAccumulate(int i, long x,
LongBinaryOperator accumulatorFunction) {
long prev = get(i), next = 0L;
for (boolean haveNext = false;;) {
if (!haveNext)
next = accumulatorFunction.applyAsLong(prev, x);
if (weakCompareAndSetVolatile(i, prev, next))
return prev;
haveNext = (prev == (prev = get(i)));
}
}
/**
* Atomically updates the element at index {@code i} with the
* results of applying the given function to the current and given
* values, returning the updated value. The function should be
* side-effect-free, since it may be re-applied when attempted
* updates fail due to contention among threads. The function is
* applied with the current value of the element at index {@code i}
* as its first argument, and the given update as the second
* argument.
*
* @param i the index
* @param x the update value
* @param accumulatorFunction a side-effect-free function of two arguments
* @return the updated value
* @since 1.8
*/
public final long accumulateAndGet(int i, long x,
LongBinaryOperator accumulatorFunction) {
long prev = get(i), next = 0L;
for (boolean haveNext = false;;) {
if (!haveNext)
next = accumulatorFunction.applyAsLong(prev, x);
if (weakCompareAndSetVolatile(i, prev, next))
return next;
haveNext = (prev == (prev = get(i)));
}
}
/**
* Returns the String representation of the current values of array.
* @return the String representation of the current values of array
*/
public String toString() {
int iMax = array.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(get(i));
if (i == iMax)
return b.append(']').toString();
b.append(',').append(' ');
}
}
// jdk9
/**
* Returns the current value of the element at index {@code i},
* with memory semantics of reading as if the variable was declared
* non-{@code volatile}.
*
* @param i the index
* @return the value
* @since 9
*/
public final long getPlain(int i) {
return (long)AA.get(array, i);
}
/**
* Sets the element at index {@code i} to {@code newValue},
* with memory semantics of setting as if the variable was
* declared non-{@code volatile} and non-{@code final}.
*
* @param i the index
* @param newValue the new value
* @since 9
*/
public final void setPlain(int i, long newValue) {
AA.set(array, i, newValue);
}
/**
* Returns the current value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getOpaque}.
*
* @param i the index
* @return the value
* @since 9
*/
public final long getOpaque(int i) {
return (long)AA.getOpaque(array, i);
}
/**
* Sets the element at index {@code i} to {@code newValue},
* with memory effects as specified by {@link VarHandle#setOpaque}.
*
* @param i the index
* @param newValue the new value
* @since 9
*/
public final void setOpaque(int i, long newValue) {
AA.setOpaque(array, i, newValue);
}
/**
* Returns the current value of the element at index {@code i},
* with memory effects as specified by {@link VarHandle#getAcquire}.
*
* @param i the index
* @return the value
* @since 9
*/
public final long getAcquire(int i) {
return (long)AA.getAcquire(array, i);
}
/**
* Sets the element at index {@code i} to {@code newValue},
* with memory effects as specified by {@link VarHandle#setRelease}.
*
* @param i the index
* @param newValue the new value
* @since 9
*/
public final void setRelease(int i, long newValue) {
AA.setRelease(array, i, newValue);
}
/**
* Atomically sets the element at index {@code i} to {@code newValue}
* if the element's current value, referred to as the <em>witness
* value</em>, {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#compareAndExchange}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return the witness value, which will be the same as the
* expected value if successful
* @since 9
*/
public final long compareAndExchange(int i, long expectedValue, long newValue) {
return (long)AA.compareAndExchange(array, i, expectedValue, newValue);
}
/**
* Atomically sets the element at index {@code i} to {@code newValue}
* if the element's current value, referred to as the <em>witness
* value</em>, {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#compareAndExchangeAcquire}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return the witness value, which will be the same as the
* expected value if successful
* @since 9
*/
public final long compareAndExchangeAcquire(int i, long expectedValue, long newValue) {
return (long)AA.compareAndExchangeAcquire(array, i, expectedValue, newValue);
}
/**
* Atomically sets the element at index {@code i} to {@code newValue}
* if the element's current value, referred to as the <em>witness
* value</em>, {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#compareAndExchangeRelease}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return the witness value, which will be the same as the
* expected value if successful
* @since 9
*/
public final long compareAndExchangeRelease(int i, long expectedValue, long newValue) {
return (long)AA.compareAndExchangeRelease(array, i, expectedValue, newValue);
}
/**
* Possibly atomically sets the element at index {@code i} to
* {@code newValue} if the element's current value {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#weakCompareAndSetVolatile}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful
* @since 9
*/
public final boolean weakCompareAndSetVolatile(int i, long expectedValue, long newValue) {
return AA.weakCompareAndSetVolatile(array, i, expectedValue, newValue);
}
/**
* Possibly atomically sets the element at index {@code i} to
* {@code newValue} if the element's current value {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#weakCompareAndSetAcquire}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful
* @since 9
*/
public final boolean weakCompareAndSetAcquire(int i, long expectedValue, long newValue) {
return AA.weakCompareAndSetAcquire(array, i, expectedValue, newValue);
}
/**
* Possibly atomically sets the element at index {@code i} to
* {@code newValue} if the element's current value {@code == expectedValue},
* with memory effects as specified by
* {@link VarHandle#weakCompareAndSetRelease}.
*
* @param i the index
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful
* @since 9
*/
public final boolean weakCompareAndSetRelease(int i, long expectedValue, long newValue) {
return AA.weakCompareAndSetRelease(array, i, expectedValue, newValue);
}
}
| gpl-2.0 |
teamfx/openjfx-10-dev-rt | modules/jdk.packager/src/main/java/com/oracle/tools/packager/jnlp/JNLPBundler.java | 56509 | /*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.tools.packager.jnlp;
import com.oracle.tools.packager.AbstractBundler;
import com.oracle.tools.packager.BundlerParamInfo;
import com.oracle.tools.packager.ConfigException;
import com.oracle.tools.packager.Log;
import com.oracle.tools.packager.RelativeFileSet;
import com.oracle.tools.packager.StandardBundlerParam;
import com.oracle.tools.packager.UnsupportedPlatformException;
import com.sun.javafx.tools.packager.PackagerException;
import com.sun.javafx.tools.resource.PackagerResource;
import com.sun.javafx.tools.packager.TemplatePlaceholders;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.cert.CertificateEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.oracle.tools.packager.StandardBundlerParam.*;
import jdk.packager.internal.legacy.JLinkBundlerHelper;
public class JNLPBundler extends AbstractBundler {
private static final ResourceBundle I18N =
ResourceBundle.getBundle(JNLPBundler.class.getName());
private static final String dtFX = "dtjava.js";
private static final String webfilesDir = "web-files";
//Note: leading "." is important for IE8
private static final String EMBEDDED_DT = "./"+webfilesDir+"/"+dtFX;
private static final String PUBLIC_DT = "https://java.com/js/dtjava.js";
private static final String JFX_NS_URI = "http://javafx.com";
public static final StandardBundlerParam<String> OUT_FILE = new StandardBundlerParam<>(
I18N.getString("param.out-file.name"),
I18N.getString("param.out-file.description"),
"jnlp.outfile",
String.class,
null,
null);
public static final StandardBundlerParam<Boolean> SWING_APP = new StandardBundlerParam<>(
I18N.getString("param.swing-app.name"),
I18N.getString("param.swing-app.description"),
"jnlp.swingApp",
Boolean.class,
p -> Boolean.FALSE,
(s, p) -> Boolean.parseBoolean(s));
public static final StandardBundlerParam<Boolean> INCLUDE_DT = new StandardBundlerParam<>(
I18N.getString("param.include-deployment-toolkit.name"),
I18N.getString("param.include-deployment-toolkit.description"),
"jnlp.includeDT",
Boolean.class,
p -> Boolean.FALSE,
(s, p) -> Boolean.parseBoolean(s));
public static final StandardBundlerParam<Boolean> EMBED_JNLP = new StandardBundlerParam<>(
I18N.getString("param.embed-jnlp.name"),
I18N.getString("param.embed-jnlp.description"),
"jnlp.embedJnlp",
Boolean.class,
p -> Boolean.FALSE,
(s, p) -> Boolean.parseBoolean(s));
public static final StandardBundlerParam<Boolean> EXTENSION = new StandardBundlerParam<>(
I18N.getString("param.extension.name"),
I18N.getString("param.extension.description"),
"jnlp.extension",
Boolean.class,
p -> Boolean.FALSE,
(s, p) -> Boolean.parseBoolean(s));
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<Map<File, File>> TEMPLATES = new StandardBundlerParam<>(
I18N.getString("param.templates.name"),
I18N.getString("param.templates.description"),
"jnlp.templates",
(Class<Map<File, File>>) (Object) Map.class,
p -> new LinkedHashMap<>(),
null);
public static final StandardBundlerParam<String> CODEBASE = new StandardBundlerParam<>(
I18N.getString("param.codebase.name"),
I18N.getString("param.codebase.description"),
"jnlp.codebase",
String.class,
p -> null,
null);
public static final StandardBundlerParam<String> PLACEHOLDER = new StandardBundlerParam<>(
I18N.getString("param.placeholder.name"),
I18N.getString("param.placeholder.description"),
"jnlp.placeholder",
String.class,
p -> "javafx-app-placeholder",
(s, p) -> {
if (!s.startsWith("'")) {
s = "'" + s;
}
if (!s.endsWith("'")) {
s = s + "'";
}
return s;
});
public static final StandardBundlerParam<Boolean> OFFLINE_ALLOWED = new StandardBundlerParam<>(
I18N.getString("param.offline-allowed.name"),
I18N.getString("param.offline-allowed.description"),
"jnlp.offlineAllowed",
Boolean.class,
p -> true,
(s, p) -> Boolean.valueOf(s));
public static final StandardBundlerParam<Boolean> ALL_PERMISSIONS = new StandardBundlerParam<>(
I18N.getString("param.all-permissions.name"),
I18N.getString("param.all-permissions.description"),
"jnlp.allPermisions",
Boolean.class,
p -> false,
(s, p) -> Boolean.valueOf(s));
public static final StandardBundlerParam<Integer> WIDTH = new StandardBundlerParam<>(
I18N.getString("param.width.name"),
I18N.getString("param.width.description"),
"jnlp.width",
Integer.class,
p -> 0,
(s, p) -> Integer.parseInt(s));
public static final StandardBundlerParam<Integer> HEIGHT = new StandardBundlerParam<>(
I18N.getString("param.height.name"),
I18N.getString("param.height.description"),
"jnlp.height",
Integer.class,
p -> 0,
(s, p) -> Integer.parseInt(s));
public static final StandardBundlerParam<String> EMBEDDED_WIDTH = new StandardBundlerParam<>(
I18N.getString("param.embedded-width.name"),
I18N.getString("param.embedded-width.description"),
"jnlp.embeddedWidth",
String.class,
p -> Integer.toString(WIDTH.fetchFrom(p)),
(s, p) -> s);
public static final StandardBundlerParam<String> EMBEDDED_HEIGHT = new StandardBundlerParam<>(
I18N.getString("param.embedded-height.name"),
I18N.getString("param.embedded-height.description"),
"jnlp.embeddedHeight",
String.class,
p -> Integer.toString(HEIGHT.fetchFrom(p)),
(s, p) -> s);
public static final StandardBundlerParam<String> FALLBACK_APP = new StandardBundlerParam<>(
I18N.getString("param.fallback-app.name"),
I18N.getString("param.fallback-app.description"),
"jnlp.fallbackApp",
String.class,
p -> null,
(s, p) -> s);
public static final StandardBundlerParam<String> UPDATE_MODE = new StandardBundlerParam<>(
I18N.getString("param.update-mode.name"),
I18N.getString("param.update-mode.description"),
"jnlp.updateMode",
String.class,
p -> "background",
(s, p) -> s);
public static final StandardBundlerParam<String> FX_PLATFORM = new StandardBundlerParam<>(
I18N.getString("param.fx-platform.name"),
I18N.getString("param.fx-platform.description"),
"jnlp.fxPlatform",
String.class,
p -> "1.8+",
(s, p) -> s);
public static final StandardBundlerParam<String> JRE_PLATFORM = new StandardBundlerParam<>(
I18N.getString("param.jre-platform.name"),
I18N.getString("param.jre-platform.description"),
"jnlp.jrePlatform",
String.class,
p -> "1.8+",
(s, p) -> s);
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<List<Map<String, ? super Object>>> ICONS = new StandardBundlerParam<>(
I18N.getString("param.icons.name"),
I18N.getString("param.icons.description"),
"jnlp.icons",
(Class<List<Map<String, ? super Object>>>) (Object) List.class,
params -> new ArrayList<>(1),
null
);
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<Map<String, String>> APP_PARAMS = new StandardBundlerParam<>(
I18N.getString("param.params.name"),
I18N.getString("param.params.description"),
"jnlp.params",
(Class<Map<String, String>>) (Object) Map.class,
params -> new HashMap<>(),
null
);
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<Map<String, String>> ESCAPED_APPLET_PARAMS = new StandardBundlerParam<>(
I18N.getString("param.escaped-applet-params.name"),
I18N.getString("param.escaped-applet-params.description"),
"jnlp.escapedAppletParams",
(Class<Map<String, String>>) (Object) Map.class,
params -> new HashMap<>(),
null
);
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<Map<String, String>> APPLET_PARAMS = new StandardBundlerParam<>(
I18N.getString("param.applet-params.name"),
I18N.getString("param.applet-params.description"),
"jnlp.appletParams",
(Class<Map<String, String>>) (Object) Map.class,
params -> new HashMap<>(),
null
);
@SuppressWarnings("unchecked")
public static final StandardBundlerParam<Map<String, String>> JS_CALLBACKS = new StandardBundlerParam<>(
I18N.getString("param.js-callbacks.name"),
I18N.getString("param.js-callbacks.description"),
"jnlp.jsCallbacks",
(Class<Map<String, String>>) (Object) Map.class,
params -> new HashMap<>(),
null
);
public static final StandardBundlerParam<Boolean> INSTALL_HINT =
new StandardBundlerParam<>(
I18N.getString("param.menu-install-hint.name"),
I18N.getString("param.menu-install-hint.description"),
"jnlp.install",
Boolean.class,
params -> null,
// valueOf(null) is false, and we actually do want null in some cases
(s, p) -> (s == null || "null".equalsIgnoreCase(s))? null : Boolean.valueOf(s)
);
public static final StandardBundlerParam<String> ICONS_HREF =
new StandardBundlerParam<>(
I18N.getString("param.icons-href.name"),
I18N.getString("param.icons-href.description"),
"jnlp.icons.href",
String.class,
null,
null
);
public static final StandardBundlerParam<String> ICONS_KIND =
new StandardBundlerParam<>(
I18N.getString("param.icons-kind.name"),
I18N.getString("param.icons-kind.description"),
"jnlp.icons.kind",
String.class,
params -> null,
null
);
public static final StandardBundlerParam<String> ICONS_WIDTH =
new StandardBundlerParam<>(
I18N.getString("param.icons-width.name"),
I18N.getString("param.icons-width.description"),
"jnlp.icons.width",
String.class,
params -> null,
null
);
public static final StandardBundlerParam<String> ICONS_HEIGHT =
new StandardBundlerParam<>(
I18N.getString("param.icons-height.name"),
I18N.getString("param.icons-height.description"),
"jnlp.icons.height",
String.class,
params -> null,
null
);
public static final StandardBundlerParam<String> ICONS_DEPTH =
new StandardBundlerParam<>(
I18N.getString("param.icons-depth.name"),
I18N.getString("param.icons-depth.description"),
"jnlp.icons.depth",
String.class,
params -> null,
null
);
private enum Mode {FX, APPLET, SwingAPP}
@Override
public String getName() {
return I18N.getString("bundler.name");
}
@Override
public String getDescription() {
return I18N.getString("bundler.description");
}
@Override
public String getID() {
return "jnlp";
}
@Override
public String getBundleType() {
return "JNLP";
}
@Override
public Collection<BundlerParamInfo<?>> getBundleParameters() {
return Arrays.asList(
ALL_PERMISSIONS,
APPLET_PARAMS,
APP_NAME,
APP_PARAMS,
APP_RESOURCES_LIST,
ARGUMENTS,
CODEBASE,
DESCRIPTION,
EMBED_JNLP,
EMBEDDED_HEIGHT,
EMBEDDED_WIDTH,
ESCAPED_APPLET_PARAMS,
EXTENSION,
// FALLBACK_APP,
// FX_PLATFORM,
HEIGHT,
ICONS,
IDENTIFIER,
INCLUDE_DT,
INSTALL_HINT,
JRE_PLATFORM,
JS_CALLBACKS,
JVM_OPTIONS,
JVM_PROPERTIES,
MAIN_CLASS,
MENU_HINT,
OFFLINE_ALLOWED,
OUT_FILE,
PRELOADER_CLASS,
PLACEHOLDER,
SHORTCUT_HINT,
SWING_APP,
TEMPLATES,
TITLE,
UPDATE_MODE,
VENDOR,
WIDTH
);
}
@Override
public boolean validate(Map<String, ? super Object> params) throws UnsupportedPlatformException, ConfigException {
if (OUT_FILE.fetchFrom(params) == null) {
throw new ConfigException(
I18N.getString("error.no-outfile"),
I18N.getString("error.no-outfile.advice"));
}
if (APP_RESOURCES_LIST.fetchFrom(params) == null) {
throw new ConfigException(
I18N.getString("error.no-app-resources"),
I18N.getString("error.no-app-resources.advice"));
}
if (!EXTENSION.fetchFrom(params)) {
StandardBundlerParam.validateMainClassInfoFromAppResources(params);
}
return true;
}
private String readTextFile(File in) throws PackagerException {
StringBuilder sb = new StringBuilder();
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(in))) {
char[] buf = new char[16384];
int len;
while ((len = isr.read(buf)) > 0) {
sb.append(buf, sb.length(), len);
}
} catch (IOException ex) {
throw new PackagerException(ex, "ERR_FileReadFailed",
in.getAbsolutePath());
}
return sb.toString();
}
private String processTemplate(Map<String, ? super Object> params, String inpText,
Map<TemplatePlaceholders, String> templateStrings) {
//Core pattern matches
// #DT.SCRIPT#
// #DT.EMBED.CODE.ONLOAD#
// #DT.EMBED.CODE.ONLOAD(App2)#
String corePattern = "(#[\\w\\.\\(\\)]+#)";
//This will match
// "/*", "//" or "<!--" with arbitrary number of spaces
String prefixGeneric = "[/\\*-<!]*[ \\t]*";
//This will match
// "/*", "//" or "<!--" with arbitrary number of spaces
String suffixGeneric = "[ \\t]*[\\*/>-]*";
//NB: result core match is group number 1
Pattern mainPattern = Pattern.compile(
prefixGeneric + corePattern + suffixGeneric);
Matcher m = mainPattern.matcher(inpText);
StringBuffer result = new StringBuffer();
while (m.find()) {
String match = m.group();
String coreMatch = m.group(1);
//have match, not validate it is not false positive ...
// e.g. if we matched just some spaces in prefix/suffix ...
boolean inComment =
(match.startsWith("<!--") && match.endsWith("-->")) ||
(match.startsWith("//")) ||
(match.startsWith("/*") && match.endsWith(" */"));
//try to find if we have match
String coreReplacement = null;
//map with rules have no template ids
//int p = coreMatch.indexOf("\\(");
//strip leading/trailing #, then split of id part
String parts[] = coreMatch.substring(1, coreMatch.length()-1).split("[\\(\\)]");
String rulePart = parts[0];
String idPart = (parts.length == 1) ?
//strip trailing ')'
null : parts[1];
if (templateStrings.containsKey(
TemplatePlaceholders.fromString(rulePart))
&& (idPart == null /* it is ok for templateId to be not null, e.g. DT.SCRIPT.CODE */
|| idPart.equals(IDENTIFIER.fetchFrom(params)))) {
coreReplacement = templateStrings.get(
TemplatePlaceholders.fromString(rulePart));
}
if (coreReplacement != null) {
if (inComment || coreMatch.length() == match.length()) {
m.appendReplacement(result, coreReplacement);
} else { // pattern matched something that is not comment
// Very unlikely but lets play it safe
int pp = match.indexOf(coreMatch);
String v = match.substring(0, pp) +
coreReplacement +
match.substring(pp + coreMatch.length());
m.appendReplacement(result, v);
}
}
}
m.appendTail(result);
return result.toString();
}
@Override
public File execute(Map<String, ? super Object> params, File outputParentDir) {
Map<File, File> templates = TEMPLATES.fetchFrom(params);
boolean templateOn = !templates.isEmpty();
Map<TemplatePlaceholders, String> templateStrings = null;
if (templateOn) {
templateStrings =
new EnumMap<>(TemplatePlaceholders.class);
}
try {
//In case of FX app we will have one JNLP and one HTML
//In case of Swing with FX we will have 2 JNLP files and one HTML
String outfile = OUT_FILE.fetchFrom(params);
boolean isSwingApp = SWING_APP.fetchFrom(params);
String jnlp_filename_webstart = outfile + ".jnlp";
String jnlp_filename_browser
= isSwingApp ?
(outfile + "_browser.jnlp") : jnlp_filename_webstart;
String html_filename = outfile + ".html";
//create out dir
outputParentDir.mkdirs();
boolean includeDT = INCLUDE_DT.fetchFrom(params);
if (includeDT && !extractWebFiles(outputParentDir)) {
throw new PackagerException("ERR_NoEmbeddedDT");
}
ByteArrayOutputStream jnlp_bos_webstart = new ByteArrayOutputStream();
ByteArrayOutputStream jnlp_bos_browser = new ByteArrayOutputStream();
//for swing case we need to generate 2 JNLP files
if (isSwingApp) {
PrintStream jnlp_ps = new PrintStream(jnlp_bos_webstart);
generateJNLP(params, jnlp_ps, jnlp_filename_webstart, Mode.SwingAPP);
jnlp_ps.close();
//save JNLP
save(outputParentDir, jnlp_filename_webstart, jnlp_bos_webstart.toByteArray());
jnlp_ps = new PrintStream(jnlp_bos_browser);
generateJNLP(params, jnlp_ps, jnlp_filename_browser, Mode.APPLET);
jnlp_ps.close();
//save JNLP
save(outputParentDir, jnlp_filename_browser, jnlp_bos_browser.toByteArray());
} else {
PrintStream jnlp_ps = new PrintStream(jnlp_bos_browser);
generateJNLP(params, jnlp_ps, jnlp_filename_browser, Mode.FX);
jnlp_ps.close();
//save JNLP
save(outputParentDir, jnlp_filename_browser, jnlp_bos_browser.toByteArray());
jnlp_bos_webstart = jnlp_bos_browser;
}
//we do not need html if this is component and not main app
boolean isExtension = EXTENSION.fetchFrom(params);
if (!isExtension) {
// even though the html is unused if templateOn,
// the templateStrings is updated as a side effect.
ByteArrayOutputStream html_bos =
new ByteArrayOutputStream();
PrintStream html_ps = new PrintStream(html_bos);
generateHTML(params, html_ps,
jnlp_bos_browser.toByteArray(), jnlp_filename_browser,
jnlp_bos_webstart.toByteArray(), jnlp_filename_webstart,
templateStrings, isSwingApp);
html_ps.close();
//process template file
if (templateOn) {
for (Map.Entry<File, File> t: TEMPLATES.fetchFrom(params).entrySet()) {
File out = t.getValue();
if (out == null) {
System.out.println(
"Perform inplace substitution for " +
t.getKey().getAbsolutePath());
out = t.getKey();
}
save(out, processTemplate(params,
readTextFile(t.getKey()), templateStrings).getBytes());
}
} else {
//save HTML
save(outputParentDir, html_filename, html_bos.toByteArray());
}
}
//copy jar files
for (RelativeFileSet rfs : APP_RESOURCES_LIST.fetchFrom(params)) {
copyFiles(rfs, outputParentDir);
}
return outputParentDir;
} catch (Exception ex) {
Log.info("JNLP failed : " + ex.getMessage());
ex.printStackTrace();
Log.debug(ex);
return null;
}
}
private static void copyFiles(RelativeFileSet resources, File outdir) throws IOException, PackagerException {
File rootDir = resources.getBaseDirectory();
for (String s : resources.getIncludedFiles()) {
final File srcFile = new File(rootDir, s);
if (srcFile.exists() && srcFile.isFile()) {
//skip file copying if jar is in the same location
final File destFile = new File(outdir, s);
if (!srcFile.getCanonicalFile().equals(destFile.getCanonicalFile())) {
copyFileToOutDir(new FileInputStream(srcFile), destFile);
} else {
Log.verbose(MessageFormat.format(I18N.getString("error.jar-no-self-copy"), s));
}
}
}
}
//return null if args are default
private String getJvmArguments(Map<String, ? super Object> params, boolean includeProperties) {
List<String> jvmargs = JVM_OPTIONS.fetchFrom(params);
Map<String, String> properties = JVM_PROPERTIES.fetchFrom(params);
StringBuilder sb = new StringBuilder();
for (String v : jvmargs) {
sb.append(v); //may need to escape if parameter has spaces
sb.append(" ");
}
if (includeProperties) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
sb.append("-D");
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue()); //may need to escape if value has spaces
sb.append(" ");
}
}
if (sb.length() > 0) {
return sb.toString();
}
return null;
}
private void generateJNLP(Map<String, ? super Object> params, PrintStream out, String jnlp_filename, Mode m)
throws IOException, CertificateEncodingException
{
String codebase = CODEBASE.fetchFrom(params);
String title = TITLE.fetchFrom(params);
String vendor = VENDOR.fetchFrom(params);
String description = DESCRIPTION.fetchFrom(params);
try {
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLStreamWriter xout = xmlOutputFactory.createXMLStreamWriter(baos, "utf-8");
xout.writeStartDocument("utf-8", "1.0");
xout.writeCharacters("\n");
xout.writeStartElement("jnlp");
xout.writeAttribute("spec", "1.0");
xout.writeNamespace("jfx", "http://javafx.com");
if (codebase != null) {
xout.writeAttribute("codebase", codebase);
}
xout.writeAttribute("href", jnlp_filename);
xout.writeStartElement("information");
xout.writeStartElement("title");
if (title != null) {
xout.writeCharacters(title);
} else {
xout.writeCData("Sample JavaFX Application");
}
xout.writeEndElement();
xout.writeStartElement("vendor");
if (vendor != null) {
xout.writeCharacters(vendor);
} else {
xout.writeCharacters("Unknown vendor");
}
xout.writeEndElement();
xout.writeStartElement("description");
if (description != null) {
xout.writeCharacters(description);
} else {
xout.writeCharacters("Sample JavaFX 2.0 application.");
}
xout.writeEndElement();
for (Map<String, ? super Object> iconInfo : ICONS.fetchFrom(params)) {
String href = ICONS_HREF.fetchFrom(iconInfo);
String kind = ICONS_KIND.fetchFrom(iconInfo);
String width = ICONS_WIDTH.fetchFrom(iconInfo);
String height = ICONS_HEIGHT.fetchFrom(iconInfo);
String depth = ICONS_DEPTH.fetchFrom(iconInfo);
xout.writeStartElement("icon");
xout.writeAttribute("href", href);
if (kind != null) xout.writeAttribute("kind", kind);
if (width != null) xout.writeAttribute("width", width);
if (height != null) xout.writeAttribute("height", height);
if (depth != null) xout.writeAttribute("depth", depth);
xout.writeEndElement();
}
boolean offlineAllowed = OFFLINE_ALLOWED.fetchFrom(params);
boolean isExtension = EXTENSION.fetchFrom(params);
if (offlineAllowed && !isExtension) {
xout.writeEmptyElement("offline-allowed");
}
Boolean needShortcut = SHORTCUT_HINT.fetchFrom(params);
Boolean needMenu = MENU_HINT.fetchFrom(params);
Boolean needInstall = INSTALL_HINT.fetchFrom(params);
if ((needShortcut != null && Boolean.TRUE.equals(needShortcut)) ||
(needMenu != null && Boolean.TRUE.equals(needMenu)) ||
(needInstall != null && Boolean.TRUE.equals(needInstall))) {
xout.writeStartElement("shortcut");
if (Boolean.TRUE.equals(needInstall)) {
xout.writeAttribute("installed", needInstall.toString());
}
if (Boolean.TRUE.equals(needShortcut)) {
xout.writeEmptyElement("desktop");
}
if (Boolean.TRUE.equals(needMenu)) {
xout.writeEmptyElement("menu");
}
xout.writeEndElement();
}
xout.writeEndElement(); // information
boolean allPermissions = ALL_PERMISSIONS.fetchFrom(params);
if (allPermissions) {
xout.writeStartElement("security");
xout.writeEmptyElement("all-permissions");
xout.writeEndElement();
}
String updateMode = UPDATE_MODE.fetchFrom(params);
if (updateMode != null) {
xout.writeStartElement("update");
xout.writeAttribute("check", UPDATE_MODE.fetchFrom(params));
xout.writeEndElement(); // update
}
boolean needToCloseResourceTag = false;
//jre is available for all platforms
if (!isExtension) {
xout.writeStartElement("resources");
needToCloseResourceTag = true;
xout.writeStartElement("j2se");
xout.writeAttribute("version", JRE_PLATFORM.fetchFrom(params));
String vmargs = getJvmArguments(params, false);
if (vmargs != null) {
xout.writeAttribute("java-vm-args", vmargs);
}
xout.writeAttribute("href", "http://java.sun.com/products/autodl/j2se");
xout.writeEndElement(); //j2se
for (Map.Entry<String, String> entry : JVM_PROPERTIES.fetchFrom(params).entrySet()) {
xout.writeStartElement("property");
xout.writeAttribute("name", entry.getKey());
xout.writeAttribute("value", entry.getValue());
xout.writeEndElement(); //property
}
}
String currentOS = null, currentArch = null;
// //NOTE: This should sort the list by os+arch; it will reduce the number of resource tags
// String pendingPrint = null;
//for (DeployResource resource: deployParams.resources) {
for (RelativeFileSet rfs : APP_RESOURCES_LIST.fetchFrom(params)) {
//if not same OS or arch then open new resources element
if (!needToCloseResourceTag ||
((currentOS == null && rfs.getOs() != null) ||
currentOS != null && !currentOS.equals(rfs.getOs())) ||
((currentArch == null && rfs.getArch() != null) ||
currentArch != null && !currentArch.equals(rfs.getArch())))
{
//we do not print right a way as it may be empty block
// Not all resources make sense for JNLP (e.g. data or license)
if (needToCloseResourceTag) {
xout.writeEndElement();
}
needToCloseResourceTag = true;
currentOS = rfs.getOs();
currentArch = rfs.getArch();
xout.writeStartElement("resources");
if (currentOS != null) xout.writeAttribute("os", currentOS);
if (currentArch != null) xout.writeAttribute("arch", currentArch);
}
for (String relativePath : rfs.getIncludedFiles()) {
final File srcFile = new File(rfs.getBaseDirectory(), relativePath);
if (srcFile.exists() && srcFile.isFile()) {
RelativeFileSet.Type type = rfs.getType();
if (type == RelativeFileSet.Type.UNKNOWN) {
if (relativePath.endsWith(".jar")) {
type = RelativeFileSet.Type.jar;
} else if (relativePath.endsWith(".jnlp")) {
type = RelativeFileSet.Type.jnlp;
} else if (relativePath.endsWith(".dll")) {
type = RelativeFileSet.Type.nativelib;
} else if (relativePath.endsWith(".so")) {
type = RelativeFileSet.Type.nativelib;
} else if (relativePath.endsWith(".dylib")) {
type = RelativeFileSet.Type.nativelib;
}
}
switch (type) {
case jar:
xout.writeStartElement("jar");
xout.writeAttribute("href", relativePath);
xout.writeAttribute("size", Long.toString(srcFile.length()));
if (rfs.getMode() != null) {
xout.writeAttribute("download", rfs.getMode());
}
xout.writeEndElement(); //jar
break;
case jnlp:
xout.writeStartElement("extension");
xout.writeAttribute("href", relativePath);
xout.writeEndElement(); //extension
break;
case nativelib:
xout.writeStartElement("nativelib");
xout.writeAttribute("href", relativePath);
xout.writeEndElement(); //nativelib
break;
}
}
}
}
if (needToCloseResourceTag) {
xout.writeEndElement();
}
if (!isExtension) {
Integer width = WIDTH.fetchFrom(params);
Integer height = HEIGHT.fetchFrom(params);
if (width == null) {
width = 0;
}
if (height == null) {
height = 0;
}
String applicationClass = MAIN_CLASS.fetchFrom(params);
String preloader = PRELOADER_CLASS.fetchFrom(params);
Map<String, String> appParams = APP_PARAMS.fetchFrom(params);
List<String> arguments = ARGUMENTS.fetchFrom(params);
String appName = APP_NAME.fetchFrom(params);
if (m == Mode.APPLET) {
xout.writeStartElement("applet-desc");
xout.writeAttribute("width", Integer.toString(width));
xout.writeAttribute("height", Integer.toString(height));
xout.writeAttribute("main-class", applicationClass);
xout.writeAttribute("name", appName);
xout.writeStartElement("param");
xout.writeAttribute("name", "requiredFXVersion");
xout.writeAttribute("value", FX_PLATFORM.fetchFrom(params));
xout.writeEndElement(); // param
for (Map.Entry<String, String> appParamEntry : appParams.entrySet()) {
xout.writeStartElement("param");
xout.writeAttribute("name", appParamEntry.getKey());
if (appParamEntry.getValue() != null) {
xout.writeAttribute("value", appParamEntry.getValue());
}
xout.writeEndElement(); // param
}
xout.writeEndElement(); // applet-desc
} else if (m == Mode.SwingAPP) {
xout.writeStartElement("application-desc");
xout.writeAttribute("main-class", applicationClass);
xout.writeAttribute("name", appName);
for (String a : arguments) {
xout.writeStartElement("argument");
xout.writeCharacters(a);
xout.writeEndElement(); // argument
}
xout.writeEndElement();
} else { //JavaFX application
//embed fallback application
String fallbackApp = FALLBACK_APP.fetchFrom(params);
if (fallbackApp != null) {
xout.writeStartElement("applet-desc");
xout.writeAttribute("width", Integer.toString(width));
xout.writeAttribute("height", Integer.toString(height));
xout.writeAttribute("main-class", fallbackApp);
xout.writeAttribute("name", appName);
xout.writeStartElement("param");
xout.writeAttribute("name", "requiredFXVersion");
xout.writeAttribute("value", FX_PLATFORM.fetchFrom(params));
xout.writeEndElement(); // param
xout.writeEndElement(); // applet-desc
}
xout.writeStartElement("jfx", "javafx-desc", JFX_NS_URI);
xout.writeAttribute("width", Integer.toString(width));
xout.writeAttribute("height", Integer.toString(height));
xout.writeAttribute("main-class", applicationClass);
xout.writeAttribute("name", appName);
if (preloader != null) {
xout.writeAttribute("preloader-class", preloader);
}
if (appParams != null) {
for (Map.Entry<String, String> appParamEntry : appParams.entrySet()) {
xout.writeStartElement("param");
xout.writeAttribute("name", appParamEntry.getKey());
if (appParamEntry.getValue() != null) {
xout.writeAttribute("value", appParamEntry.getValue());
}
xout.writeEndElement(); // param
}
}
if (arguments != null) {
for (String a : arguments) {
xout.writeStartElement("argument");
xout.writeCharacters(a);
xout.writeEndElement(); // argument
}
}
xout.writeEndElement(); //javafx-desc
}
}
xout.writeEndElement(); // jnlp
// now pretty print
String s = baos.toString();
out.println(xmlPrettyPrint(s));
} catch (XMLStreamException | TransformerException e) {
e.printStackTrace();
}
}
private String xmlPrettyPrint(String s) throws TransformerException {
// System.out.println(s);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
StringWriter formattedStringWriter = new StringWriter();
transformer.transform(new StreamSource(new StringReader(s)), new StreamResult(formattedStringWriter));
return formattedStringWriter.toString();
}
private void addToList(List<String> l, String name, String value, boolean isString) {
if (isString) {
l.add(name + " : '" + value.replaceAll("(['\"\\\\])", "\\\\$1") + "'");
} else {
l.add(name + " : " + value);
}
}
private String listToString(List<String> lst, String offset) {
StringBuilder b = new StringBuilder();
if (lst == null || lst.isEmpty()) {
return offset + "{}";
}
b.append(offset).append("{\n");
boolean first = true;
for (String s : lst) {
if (!first) {
b.append(",\n");
}
first = false;
b.append(offset).append(" ");
b.append(s);
}
b.append("\n");
b.append(offset).append("}");
return b.toString();
}
private String encodeAsBase64(byte inp[]) {
return Base64.getEncoder().encodeToString(inp);
}
private void generateHTML(Map<String, ? super Object> params,
PrintStream theOut,
byte[] jnlp_bytes_browser, String jnlpfile_browser,
byte[] jnlp_bytes_webstart, String jnlpfile_webstart,
Map<TemplatePlaceholders, String> templateStrings,
boolean swingMode) {
String poff = " ";
String poff2 = poff + poff;
String poff3 = poff2 + poff;
try {
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLStreamWriter xout = xmlOutputFactory.createXMLStreamWriter(baos, "utf-8");
String appletParams = getAppletParameters(params);
String jnlp_content_browser = null;
String jnlp_content_webstart = null;
boolean embedJNLP = EMBED_JNLP.fetchFrom(params);
boolean includeDT = INCLUDE_DT.fetchFrom(params);
if (embedJNLP) {
jnlp_content_browser = encodeAsBase64(jnlp_bytes_browser);
jnlp_content_webstart = encodeAsBase64(jnlp_bytes_webstart);
}
xout.writeStartElement("html");
xout.writeStartElement("head");
String dtURL = includeDT ? EMBEDDED_DT : PUBLIC_DT;
if (templateStrings != null) {
templateStrings.put(TemplatePlaceholders.SCRIPT_URL, dtURL);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
XMLStreamWriter xo2 = xmlOutputFactory.createXMLStreamWriter(baos2, "utf-8");
xo2.writeStartElement("SCRIPT");
xo2.writeAttribute("src", dtURL);
xo2.writeEndElement();
xo2.close();
templateStrings.put(TemplatePlaceholders.SCRIPT_CODE, baos2.toString());
}
xout.writeStartElement("SCRIPT");
xout.writeAttribute("src", dtURL);
xout.writeEndElement();
List<String> w_app = new ArrayList<>();
List<String> w_platform = new ArrayList<>();
List<String> w_callback = new ArrayList<>();
addToList(w_app, "url", jnlpfile_webstart, true);
if (jnlp_content_webstart != null) {
addToList(w_app, "jnlp_content", jnlp_content_webstart, true);
}
addToList(w_platform, "javafx", FX_PLATFORM.fetchFrom(params), true);
String vmargs = getJvmArguments(params, true);
if (vmargs != null) {
addToList(w_platform, "jvmargs", vmargs, true);
}
if (!"".equals(appletParams)) {
addToList(w_app, "params", "{" + appletParams + "}", false);
}
for (Map.Entry<String, String> callbackEntry : JS_CALLBACKS.fetchFrom(params).entrySet()) {
addToList(w_callback, callbackEntry.getKey(), callbackEntry.getValue(), false);
}
//prepare content of launchApp function
StringBuilder out_launch_code = new StringBuilder();
out_launch_code.append(poff2).append("dtjava.launch(");
out_launch_code.append(listToString(w_app, poff3)).append(",\n");
out_launch_code.append(listToString(w_platform, poff3)).append(",\n");
out_launch_code.append(listToString(w_callback, poff3)).append("\n");
out_launch_code.append(poff2).append(");\n");
xout.writeStartElement("script");
xout.writeCharacters("\n" + poff + "function launchApplication(jnlpfile) {\n");
xout.writeCharacters(out_launch_code.toString());
xout.writeCharacters(poff2 + "return false;\n");
xout.writeCharacters(poff + "}\n");
xout.writeEndElement();
if (templateStrings != null) {
templateStrings.put(TemplatePlaceholders.LAUNCH_CODE,
out_launch_code.toString());
}
//applet deployment
String appId = IDENTIFIER.fetchFrom(params);
String placeholder = PLACEHOLDER.fetchFrom(params);
//prepare content of embedApp()
List<String> p_app = new ArrayList<>();
List<String> p_platform = new ArrayList<>();
List<String> p_callback = new ArrayList<>();
if (appId != null) {
addToList(p_app, "id", appId, true);
}
boolean isSwingApp = SWING_APP.fetchFrom(params);
if (isSwingApp) {
addToList(p_app, "toolkit", "swing", true);
}
addToList(p_app, "url", jnlpfile_browser, true);
addToList(p_app, "placeholder", placeholder, true);
addToList(p_app, "width", EMBEDDED_WIDTH.fetchFrom(params), true);
addToList(p_app, "height", EMBEDDED_HEIGHT.fetchFrom(params), true);
if (jnlp_content_browser != null) {
addToList(p_app, "jnlp_content", jnlp_content_browser, true);
}
addToList(p_platform, "javafx", FX_PLATFORM.fetchFrom(params), true);
if (vmargs != null) {
addToList(p_platform, "jvmargs", vmargs, true);
}
for (Map.Entry<String, String> callbackEntry : JS_CALLBACKS.fetchFrom(params).entrySet()) {
addToList(w_callback, callbackEntry.getKey(), callbackEntry.getValue(), false);
}
if (!"".equals(appletParams)) {
addToList(p_app, "params", "{" + appletParams + "}", false);
}
if (swingMode) {
//Splash will not work in SwingMode
//Unless user overwrites onGetSplash handler (and that means he handles splash on his own)
// we will reset splash function to be "none"
boolean needOnGetSplashImpl = true;
for (String callback : JS_CALLBACKS.fetchFrom(params).keySet()) {
if ("onGetSplash".equals(callback)) {
needOnGetSplashImpl = false;
}
}
if (needOnGetSplashImpl) {
addToList(p_callback, "onGetSplash", "function() {}", false);
}
}
StringBuilder out_embed_dynamic = new StringBuilder();
out_embed_dynamic.append("dtjava.embed(\n");
out_embed_dynamic.append(listToString(p_app, poff3)).append(",\n");
out_embed_dynamic.append(listToString(p_platform, poff3)).append(",\n");
out_embed_dynamic.append(listToString(p_callback, poff3)).append("\n");
out_embed_dynamic.append(poff2).append(");\n");
//now wrap content with function
String embedFuncName = "javafxEmbed" + IDENTIFIER.fetchFrom(params);
ByteArrayOutputStream baos_embed_onload = new ByteArrayOutputStream();
XMLStreamWriter xo_embed_onload = xmlOutputFactory.createXMLStreamWriter(baos_embed_onload, "utf-8");
writeEmbeddedDynamic(out_embed_dynamic, embedFuncName, xo_embed_onload);
xo_embed_onload.close();
String out_embed_onload = xmlPrettyPrint(baos_embed_onload.toString());
if (templateStrings != null) {
templateStrings.put(
TemplatePlaceholders.EMBED_CODE_ONLOAD,
out_embed_onload);
templateStrings.put(
TemplatePlaceholders.EMBED_CODE_DYNAMIC,
out_embed_dynamic.toString());
}
writeEmbeddedDynamic(out_embed_dynamic, embedFuncName, xout);
xout.writeEndElement(); //head
xout.writeStartElement("body");
xout.writeStartElement("h2");
xout.writeCharacters("Test page for ");
xout.writeStartElement("b");
xout.writeCharacters(APP_NAME.fetchFrom(params));
xout.writeEndElement(); // b
xout.writeEndElement(); // h2
xout.writeStartElement("b");
xout.writeCharacters("Webstart:");
xout.writeEndElement();
xout.writeStartElement("a");
xout.writeAttribute("href", jnlpfile_webstart);
xout.writeAttribute("onclick", "return launchApplication('" + jnlpfile_webstart + "');");
xout.writeCharacters("click to launch this app as webstart");
xout.writeEndElement(); // a
xout.writeEmptyElement("br");
xout.writeEmptyElement("hr");
xout.writeEmptyElement("br");
xout.writeCharacters("\n");
xout.writeComment(" Applet will be inserted here ");
xout.writeStartElement("div");
xout.writeAttribute("id", placeholder);
xout.writeEndElement(); //div
xout.writeEndElement(); // body
xout.writeEndElement(); // html
xout.close();
theOut.print(xmlPrettyPrint(baos.toString()));
} catch (XMLStreamException | TransformerException e) {
e.printStackTrace();
}
}
private void writeEmbeddedDynamic(StringBuilder out_embed_dynamic, String embedFuncName, XMLStreamWriter xo_embed_onload) throws XMLStreamException {
xo_embed_onload.writeStartElement("script");
xo_embed_onload.writeCharacters("\n function ");
xo_embed_onload.writeCharacters(embedFuncName);
xo_embed_onload.writeCharacters("() {\n ");
xo_embed_onload.writeCharacters(out_embed_dynamic.toString());
xo_embed_onload.writeCharacters(" }\n ");
xo_embed_onload.writeComment(
" Embed FX application into web page once page is loaded ");
xo_embed_onload.writeCharacters("\n dtjava.addOnloadCallback(");
xo_embed_onload.writeCharacters(embedFuncName);
xo_embed_onload.writeCharacters(");\n");
xo_embed_onload.writeEndElement();
}
private void save(File outdir, String fname, byte[] content) throws IOException {
save(new File(outdir, fname), content);
}
private void save(File f, byte[] content) throws IOException {
if (f.exists()) {
f.delete();
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(content);
fos.close();
}
private static void copyFileToOutDir(
InputStream isa, File fout) throws PackagerException {
final File outDir = fout.getParentFile();
if (!outDir.exists() && !outDir.mkdirs()) {
throw new PackagerException("ERR_CreatingDirFailed", outDir.getPath());
}
try (InputStream is = isa; OutputStream out = new FileOutputStream(fout)) {
byte[] buf = new byte[16384];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException ex) {
throw new PackagerException(ex, "ERR_FileCopyFailed", outDir.getPath());
}
}
private String getAppletParameters(Map<String, ? super Object> params) {
StringBuilder result = new StringBuilder();
boolean addComma = false;
for (Map.Entry<String, String> entry : ESCAPED_APPLET_PARAMS.fetchFrom(params).entrySet()) {
if (addComma) {
result.append(", ");
}
addComma = true;
result.append("'")
.append(quoteEscape(entry.getKey()))
.append("' : '")
.append(quoteEscape(entry.getValue()))
.append("'");
}
for (Map.Entry<String, String> entry : APPLET_PARAMS.fetchFrom(params).entrySet()) {
if (addComma) {
result.append(", ");
}
addComma = true;
result.append("'")
.append(quoteEscape(entry.getKey()))
.append("' : ")
.append(entry.getValue());
}
return result.toString();
}
String quoteEscape(String s) {
return s.replaceAll("(['\"\\\\])", "\\\\$1");
}
private static String[] webFiles = {
"javafx-loading-100x100.gif",
dtFX,
"javafx-loading-25x25.gif",
"error.png",
"upgrade_java.png",
"javafx-chrome.png",
"get_java.png",
"upgrade_javafx.png",
"get_javafx.png"
};
private static String prefixWebFiles = "dtoolkit/resources/web-files/";
private boolean extractWebFiles(File outDir) throws PackagerException {
return doExtractWebFiles(webFiles, outDir, webfilesDir);
}
private boolean doExtractWebFiles(String lst[], File outDir, String webFilesDir) throws PackagerException {
File f = new File(outDir, webFilesDir);
f.mkdirs();
for (String s: lst) {
InputStream is = PackagerResource.class.getResourceAsStream(prefixWebFiles+s);
if (is == null) {
System.err.println("Internal error. Missing resources [" +
(prefixWebFiles+s) + "]");
return false;
} else {
copyFileToOutDir(is, new File(f, s));
}
}
return true;
}
}
| gpl-2.0 |
bdaum/zoraPD | org.eclipse.nebula.widgets.gallery/src/org/eclipse/nebula/widgets/gallery/AbstractGalleryItemRenderer.java | 9697 | /*******************************************************************************
* Copyright (c) 2006-2007 Nicolas Richeton.
* 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 :
* Nicolas Richeton (nicolas.richeton@gmail.com) - initial API and implementation
*******************************************************************************/
package org.eclipse.nebula.widgets.gallery;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
/**
* <p>
* Base class used to implement a custom gallery item renderer.
* </p>
* <p>
* NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT.
* </p>
*
* @author Nicolas Richeton (nicolas.richeton@gmail.com)
*/
public abstract class AbstractGalleryItemRenderer {
/**
* Id for decorators located at the bottom right of the item image
*
* Example : item.setData( AbstractGalleryItemRenderer.OVERLAY_BOTTOM_RIGHT
* , <Image or Image[]> );
*/
public final static String OVERLAY_BOTTOM_RIGHT = "org.eclipse.nebula.widget.gallery.bottomRightOverlay"; //$NON-NLS-1$
/**
* Id for decorators located at the bottom left of the item image
*
* Example : item.setData( AbstractGalleryItemRenderer.OVERLAY_BOTTOM_RIGHT
* , <Image or Image[]> );
*/
public final static String OVERLAY_BOTTOM_LEFT = "org.eclipse.nebula.widget.gallery.bottomLeftOverlay"; //$NON-NLS-1$
/**
* Id for decorators located at the top right of the item image
*
* Example : item.setData( AbstractGalleryItemRenderer.OVERLAY_BOTTOM_RIGHT
* , <Image or Image[]> );
*/
public final static String OVERLAY_TOP_RIGHT = "org.eclipse.nebula.widget.gallery.topRightOverlay"; //$NON-NLS-1$
/**
* Id for decorators located at the top left of the item image
*
* Example : item.setData( AbstractGalleryItemRenderer.OVERLAY_BOTTOM_RIGHT
* , <Image or Image[]> );
*/
public final static String OVERLAY_TOP_LEFT = "org.eclipse.nebula.widget.gallery.topLeftOverlay"; //$NON-NLS-1$
protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
protected Gallery gallery;
Color galleryBackgroundColor, galleryForegroundColor;
protected boolean selected;
/**
* true is the current item is selected
*
* @return
*/
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* Draws an item.
*
* @param gc
* @param item
* @param index
* @param x
* @param y
* @param width
* @param height
*/
public abstract void draw(GC gc, GalleryItem item, int index, int x, int y,
int width, int height);
public abstract void dispose();
/**
* This method is called before drawing the first item. It may be used to
* calculate some values (like font metrics) that will be used for each
* item.
*
* @param gc
*/
public void preDraw(GC gc) {
// Cache gallery color since this method is resource intensive.
galleryForegroundColor = gallery.getForeground();
galleryBackgroundColor = gallery.getBackground();
}
/**
* This method is called after drawing the last item. It may be used to
* cleanup and release resources created in preDraw().
*
* @param gc
*/
public void postDraw(GC gc) {
galleryForegroundColor = null;
galleryBackgroundColor = null;
}
/**
* Get current gallery.
*
* @return
*/
public Gallery getGallery() {
return gallery;
}
/**
* Set the current gallery. This method is automatically called by
* {@link Gallery#setItemRenderer(AbstractGalleryItemRenderer)}. There is
* not need to call it from user code.
*
* @param gallery
*/
public void setGallery(Gallery gallery) {
this.gallery = gallery;
}
/**
* Returns the best size ratio for overlay images. This ensure that all
* images can fit without being drawn on top of others.
*
* @param imageSize
* @param overlaySizeTopLeft
* @param overlaySizeTopRight
* @param overlaySizeBottomLeft
* @param overlaySizeBottomRight
* @return
*/
protected double getOverlayRatio(Point imageSize, Point overlaySizeTopLeft,
Point overlaySizeTopRight, Point overlaySizeBottomLeft,
Point overlaySizeBottomRight) {
double ratio = 1;
if (overlaySizeTopLeft.x + overlaySizeTopRight.x > imageSize.x) {
ratio = Math.min(ratio, (double) imageSize.x
/ (overlaySizeTopLeft.x + overlaySizeTopRight.x));
}
if (overlaySizeBottomLeft.x + overlaySizeBottomRight.x > imageSize.x) {
ratio = Math.min(ratio, (double) imageSize.x
/ (overlaySizeBottomLeft.x + overlaySizeBottomRight.x));
}
if (overlaySizeTopLeft.y + overlaySizeBottomLeft.y > imageSize.y) {
ratio = Math.min(ratio, (double) imageSize.y
/ (overlaySizeTopLeft.y + overlaySizeBottomLeft.y));
}
if (overlaySizeTopRight.y + overlaySizeBottomRight.y > imageSize.y) {
ratio = Math.min(ratio, (double) imageSize.y
/ (overlaySizeTopRight.y + overlaySizeBottomRight.y));
}
return ratio;
}
/**
* Draw image overlays. Overlays are defined with image.setData using the
* following keys :
* <ul>
* <li>org.eclipse.nebula.widget.gallery.bottomLeftOverlay</li>
* <li>org.eclipse.nebula.widget.gallery.bottomRightOverlay</li>
* <li>org.eclipse.nebula.widget.gallery.topLeftOverlay</li>
* <li>org.eclipse.nebula.widget.gallery.topRightOverlay</li>
*</ul>
*
*/
protected void drawAllOverlays(GC gc, GalleryItem item, int x, int y,
Point imageSize, int xShift, int yShift) {
Image[] imagesBottomLeft = getImageOverlay(item, OVERLAY_BOTTOM_LEFT);
Image[] imagesBottomRight = getImageOverlay(item, OVERLAY_BOTTOM_RIGHT);
Image[] imagesTopLeft = getImageOverlay(item, OVERLAY_TOP_LEFT);
Image[] imagesTopRight = getImageOverlay(item, OVERLAY_TOP_RIGHT);
Point overlaySizeBottomLeft = getOverlaySize(imagesBottomLeft);
Point overlaySizeBottomRight = getOverlaySize(imagesBottomRight);
Point overlaySizeTopLeft = getOverlaySize(imagesTopLeft);
Point overlaySizeTopRight = getOverlaySize(imagesTopRight);
double ratio = getOverlayRatio(imageSize, overlaySizeTopLeft,
overlaySizeTopRight, overlaySizeBottomLeft,
overlaySizeBottomRight);
drawOverlayImages(gc, x + xShift, y + yShift, ratio, imagesTopLeft);
drawOverlayImages(
gc,
(int) (x + xShift + imageSize.x - overlaySizeTopRight.x * ratio),
y + yShift, ratio, imagesTopRight);
drawOverlayImages(gc, x + xShift,
(int) (y + yShift + imageSize.y - overlaySizeBottomLeft.y
* ratio), ratio, imagesBottomLeft);
drawOverlayImages(gc,
(int) (x + xShift + imageSize.x - overlaySizeBottomRight.x
* ratio),
(int) (y + yShift + imageSize.y - overlaySizeBottomRight.y
* ratio), ratio, imagesBottomRight);
}
/**
* Draw overlay images for one corner.
*
* @param gc
* @param x
* @param y
* @param ratio
* @param images
*/
protected void drawOverlayImages(GC gc, int x, int y, double ratio,
Image[] images) {
if (images == null)
return;
int position = 0;
for (int i = 0; i < images.length; i++) {
Image img = images[i];
gc.drawImage(img, 0, 0, img.getBounds().width,
img.getBounds().height, x + position, y, (int) (img
.getBounds().width * ratio),
(int) (img.getBounds().height * ratio));
position += img.getBounds().width * ratio;
}
}
/**
* Return overlay size, summing all images sizes
*
* @param images
* @return
*/
protected Point getOverlaySize(Image[] images) {
if (images == null)
return new Point(0, 0);
Point result = new Point(0, 0);
for (int i = 0; i < images.length; i++) {
result.x += images[i].getBounds().width;
result.y = Math.max(result.y, images[i].getBounds().height);
}
return result;
}
/**
* Returns an array of images or null of no overlay was defined for this
* image.
*
* @param item
* @param id
* @return Image[] or null
*/
protected Image[] getImageOverlay(GalleryItem item, String id) {
Object data = item.getData(id);
if (data == null) {
return null;
}
Image[] result = null;
if (data instanceof Image) {
result = new Image[1];
result[0] = (Image) data;
}
if (data instanceof Image[]) {
result = (Image[]) data;
}
return result;
}
/**
* Check the GalleryItem, Gallery, and Display in order for the active
* background color for the given GalleryItem.
*
* @param item
* @return the background Color to use for this item
*/
protected Color getBackground(GalleryItem item) {
Color backgroundColor = item.background;
if (backgroundColor == null) {
backgroundColor = item.getParent().getBackground();
}
return backgroundColor;
}
/**
* Check the GalleryItem, Gallery, and Display in order for the active
* foreground color for the given GalleryItem.
*
* @param item
* @return the foreground Color to use for this item
*/
protected Color getForeground(GalleryItem item) {
Color foregroundColor = item.getForeground(true);
if (foregroundColor == null) {
foregroundColor = item.getParent().getForeground();
}
return foregroundColor;
}
/**
* Check the GalleryItem, Gallery, and Display in order for the active font
* for the given GalleryItem.
*
* @param item
* @return the Font to use for this item
*/
protected Font getFont(GalleryItem item) {
Font font = item.getFont(true);
if (font == null) {
font = item.getParent().getFont();
}
return font;
}
}
| gpl-2.0 |
XuezheMax/cmucoref | src/cmucoref/mention/extractor/MentionExtractor.java | 27355 | package cmucoref.mention.extractor;
import cmucoref.document.Document;
import cmucoref.document.Lexicon;
import cmucoref.document.Sentence;
import cmucoref.exception.MentionException;
import cmucoref.mention.Mention;
import cmucoref.mention.eventextractor.EventExtractor;
import cmucoref.mention.extractor.relationextractor.*;
import cmucoref.model.Options;
import cmucoref.util.Pair;
import cmucoref.mention.SpeakerInfo;
import cmucoref.mention.WordNet;
import cmucoref.mention.Dictionaries;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Properties;
public abstract class MentionExtractor {
protected Dictionaries dict;
protected WordNet wordNet;
protected EventExtractor eventExtractor;
public MentionExtractor(){}
public void createDict(String propfile) throws FileNotFoundException, IOException {
Properties props = new Properties();
InputStream in = MentionExtractor.class.getClassLoader().getResourceAsStream(propfile);
props.load(new InputStreamReader(in));
this.dict = new Dictionaries(props);
}
public void createWordNet(String wnDir) throws IOException {
wordNet = new WordNet(wnDir);
}
public void closeWordNet() {
wordNet.close();
}
public void setEventExtractor(EventExtractor eventExtractor) {
this.eventExtractor = eventExtractor;
}
public Dictionaries getDict() {
return dict;
}
public WordNet getWordNet() {
return wordNet;
}
public int sizeOfEvent() {
return eventExtractor.sizeOfEvent();
}
public static MentionExtractor createExtractor(String extractorClassName) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (MentionExtractor) Class.forName(extractorClassName).newInstance();
}
public abstract List<List<Mention>> extractPredictedMentions(Document doc, Options options) throws IOException;
protected void deleteDuplicatedMentions(List<Mention> mentions, Sentence sent) {
//remove duplicated mentions
Set<Mention> remove = new HashSet<Mention>();
for(int i = 0; i < mentions.size(); ++i) {
Mention mention1 = mentions.get(i);
for(int j = i + 1; j < mentions.size(); ++j) {
Mention mention2 = mentions.get(j);
if(mention1.equals(mention2)) {
remove.add(mention2);
}
}
}
mentions.removeAll(remove);
}
protected void deleteSpuriousNamedEntityMentions(List<Mention> mentions, Sentence sent) {
//remove overlap mentions
Set<Mention> remove = new HashSet<Mention>();
for(Mention mention1 : mentions) {
if(mention1.isPureNerMention(sent, dict)) {
for(Mention mention2 : mentions) {
if(mention1.overlap(mention2)) {
remove.add(mention1);
}
}
}
}
mentions.removeAll(remove);
//remove single number named entity mentions
remove.clear();
String[] NUMBERS = {"NUMBER", "ORDINAL", "CARDINAL", "MONEY", "QUANTITY"};
HashSet<String> numberNER = new HashSet<String>(Arrays.asList(NUMBERS));
for(Mention mention : mentions) {
if(mention.endIndex - mention.startIndex == 1) {
if(numberNER.contains(mention.headword.ner)) {
remove.add(mention);
}
}
}
mentions.removeAll(remove);
//remove NORP mentions as modifiers
remove.clear();
for(Mention mention : mentions) {
if((dict.isAdjectivalDemonym(mention.getSpan(sent)) || mention.headword.ner.equals("NORP"))
&& (mention.headword.postag.equals("JJ") || !dict.rolesofNoun.contains(mention.headword.basic_deprel))) {
remove.add(mention);
}
}
mentions.removeAll(remove);
//remove mentions with non-noun head
//TODO
}
protected void deleteSpuriousPronominalMentions(List<Mention> mentions, Sentence sent) {
//remove "you know" mentions
Set<Mention> remove = new HashSet<Mention>();
for(Mention mention : mentions) {
if(mention.isPronominal()
&& (mention.endIndex - mention.startIndex == 1)
&& mention.headString.equals("you")) {
if(mention.headIndex + 1 < sent.length()) {
Lexicon lex = sent.getLexicon(mention.headIndex + 1);
if(lex.form.equals("know")) {
remove.add(mention);
}
}
}
}
mentions.removeAll(remove);
//remove "you know" part in a mention
remove.clear();
for(Mention mention : mentions) {
if(mention.endIndex - mention.startIndex > 2) {
if(sent.getLexicon(mention.endIndex - 2).form.toLowerCase().equals("you")
&& sent.getLexicon(mention.endIndex - 1).form.toLowerCase().equals("know")) {
mention.endIndex = mention.endIndex - 2;
boolean duplicated = false;
for(Mention m2 : mentions) {
if(mention == m2) {
continue;
}
if(mention.equals(m2)) {
duplicated = true;
break;
}
}
if(duplicated) {
remove.add(mention);
}
else {
mention.process(sent, mentions, dict, wordNet, remove);
}
}
}
}
mentions.removeAll(remove);
}
public List<Mention> getSingleMentionList(Document doc, List<List<Mention>> mentionList, Options options) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
List<Mention> allMentions = new ArrayList<Mention>();
for(List<Mention> mentions : mentionList) {
allMentions.addAll(mentions);
}
//extract events for mentions
if(options.useEventFeature()) {
extractEvents(mentionList, doc, options);
}
//find speaker for each mention
findSpeakers(doc, allMentions, mentionList);
//Collections.sort(allMentions, Mention.syntacticOrderComparator);
//re-assign mention ID;
for(int i = 0; i < allMentions.size(); ++i) {
Mention mention = allMentions.get(i);
mention.mentionID = i;
}
if(options.usePreciseMatch()) {
findPreciseMatchRelation(doc, allMentions);
}
return allMentions;
}
/**
*
* @param doc
* @param allMentions
*/
protected void findSpeakers(Document doc, List<Mention> allMentions, List<List<Mention>> mentionList) {
Map<String, SpeakerInfo> speakersMap = new HashMap<String, SpeakerInfo>();
speakersMap.put("<DEFAULT_SPEAKER>", new SpeakerInfo(0, "<DEFAULT_SPEAKER>", false));
// find default speakers from the speaker tags of document doc
findDefaultSpeakers(doc, allMentions, speakersMap);
//makr quotations
markQuotaions(doc, false);
findQuotationSpeakers(doc, allMentions, mentionList, dict, speakersMap);
Collections.sort(allMentions, Mention.headIndexWithSpeakerOrderComparator);
//find previous speakerinfo
SpeakerInfo defaultSpeakerInfo = speakersMap.get("<DEFAULT_SPEAKER>");
SpeakerInfo preSpeakerInfo = defaultSpeakerInfo;
Mention preMention = null;
for(Mention mention : allMentions) {
if(mention.speakerInfo.isQuotationSpeaker()) {
continue;
}
if(preMention != null && !preMention.speakerInfo.equals(mention.speakerInfo)) {
preSpeakerInfo = preMention.speakerInfo;
}
if(preSpeakerInfo.equals(defaultSpeakerInfo)) {
mention.preSpeakerInfo = null;
}
else {
mention.preSpeakerInfo = preSpeakerInfo;
}
preMention = mention;
}
}
protected void findQuotationSpeakers(Document doc, List<Mention> allMentions,
List<List<Mention>> mentionList, Dictionaries dict, Map<String, SpeakerInfo> speakersMap) {
Pair<Integer, Integer> beginQuotation = new Pair<Integer, Integer>();
Pair<Integer, Integer> endQuotation = new Pair<Integer, Integer>();
boolean insideQuotation = false;
int sizeOfDoc = doc.size();
for(int i = 0; i < sizeOfDoc; ++i) {
Sentence sent = doc.getSentence(i);
for(int j = 1; j < sent.length(); ++j) {
int utterIndex = sent.getLexicon(j).utterance;
if(utterIndex != 0 && !insideQuotation) {
insideQuotation = true;
beginQuotation.first = i;
beginQuotation.second = j;
}
else if(utterIndex == 0 && insideQuotation) {
insideQuotation = false;
endQuotation.first = i;
endQuotation.second = j;
findQuotationSpeakers(doc, allMentions, mentionList, dict, speakersMap, beginQuotation, endQuotation);
}
}
}
if(insideQuotation) {
endQuotation.first = sizeOfDoc - 1;
endQuotation.second = doc.getSentence(endQuotation.first).length();
findQuotationSpeakers(doc, allMentions, mentionList, dict, speakersMap, beginQuotation, endQuotation);
}
}
protected void findQuotationSpeakers(Document doc, List<Mention> allMentions, List<List<Mention>> mentionList,
Dictionaries dict, Map<String, SpeakerInfo> speakersMap,
Pair<Integer, Integer> beginQuotation, Pair<Integer, Integer> endQuotation) {
Sentence sent = doc.getSentence(beginQuotation.first);
List<Mention> mentions = mentionList.get(beginQuotation.first);
SpeakerInfo speakerInfo = findQuotationSpeaker(sent, mentions, 1, beginQuotation.second, dict, speakersMap);
if(speakerInfo != null) {
assignUtterancetoSpeaker(doc, mentionList, dict, beginQuotation, endQuotation, speakerInfo);
return;
}
sent = doc.getSentence(endQuotation.first);
mentions = mentionList.get(endQuotation.first);
speakerInfo = findQuotationSpeaker(sent, mentions, endQuotation.second, sent.length(), dict, speakersMap);
if(speakerInfo != null) {
assignUtterancetoSpeaker(doc, mentionList, dict, beginQuotation, endQuotation, speakerInfo);
return;
}
if(beginQuotation.second <= 2 && beginQuotation.first > 0) {
sent = doc.getSentence(beginQuotation.first - 1);
mentions = mentionList.get(beginQuotation.first - 1);
speakerInfo = findQuotationSpeaker(sent, mentions, 1, sent.length(), dict, speakersMap);
if(speakerInfo != null) {
assignUtterancetoSpeaker(doc, mentionList, dict, beginQuotation, endQuotation, speakerInfo);
return;
}
}
if(endQuotation.second == doc.getSentence(endQuotation.first).length() - 1
&& doc.size() > endQuotation.first + 1) {
sent = doc.getSentence(endQuotation.first + 1);
mentions = mentionList.get(endQuotation.first + 1);
speakerInfo = findQuotationSpeaker(sent, mentions, 1, sent.length(), dict, speakersMap);
if(speakerInfo != null) {
assignUtterancetoSpeaker(doc, mentionList, dict, beginQuotation, endQuotation, speakerInfo);
return;
}
}
}
private void assignUtterancetoSpeaker(Document doc, List<List<Mention>> mentionList, Dictionaries dict,
Pair<Integer, Integer> beginQuotation, Pair<Integer, Integer> endQuotation, SpeakerInfo speakerInfo) {
for(int i = beginQuotation.first; i <= endQuotation.first; ++i) {
Sentence sent = doc.getSentence(i);
int start = i == beginQuotation.first ? beginQuotation.second : 1;
int end = i == endQuotation.first ? endQuotation.second : sent.length() - 1;
List<Mention> mentions = mentionList.get(i);
for(Mention mention : mentions) {
if(mention.startIndex >= start && mention.endIndex <= end) {
mention.setSpeakerInfo(speakerInfo);
}
}
}
}
protected SpeakerInfo findQuotationSpeaker(Sentence sent, List<Mention> mentions,
int startIndex, int endIndex, Dictionaries dict, Map<String, SpeakerInfo> speakersMap) {
for(int i = endIndex - 1; i >= startIndex; --i) {
if(sent.getLexicon(i).utterance != 0) {
continue;
}
String lemma = sent.getLexicon(i).lemma;
if(dict.reportVerb.contains(lemma)) {
int reportVerbPos = i;
Lexicon reportVerb = sent.getLexicon(reportVerbPos);
for(int j = startIndex; j < endIndex; ++j) {
Lexicon lex = sent.getLexicon(j);
if(lex.collapsed_head == reportVerbPos && (lex.collapsed_deprel.equals("nsubj") || lex.collapsed_deprel.equals("xsubj"))
|| reportVerb.collapsed_deprel.startsWith("conj_") && lex.collapsed_head == reportVerb.collapsed_head && (lex.collapsed_deprel.equals("nsubj") || lex.collapsed_deprel.equals("xsubj"))) {
int speakerHeadIndex = j;
for(Mention mention : mentions) {
if(mention.getBelognTo() == null
&& mention.headIndex == speakerHeadIndex
&& mention.startIndex >= startIndex && mention.endIndex < endIndex) {
if(mention.utteranceInfo == null) {
String speakerName = mention.getSpan(sent);
SpeakerInfo speakerInfo = new SpeakerInfo(speakersMap.size(), speakerName, true);
speakersMap.put(speakerInfo.toString(), speakerInfo);
speakerInfo.setSpeaker(mention);
mention.utteranceInfo = speakerInfo;
}
return mention.utteranceInfo;
}
}
String speakerName = sent.getLexicon(speakerHeadIndex).form;
SpeakerInfo speakerInfo = new SpeakerInfo(speakersMap.size(), speakerName, true);
speakersMap.put(speakerInfo.toString(), speakerInfo);
return speakerInfo;
}
}
}
}
return null;
}
/**
* mark quotations for a document
* @param doc
* @param normalQuotationType
*/
private void markQuotaions(Document doc, boolean normalQuotationType) {
int utteranceIndex = 0;
boolean insideQuotation = false;
boolean hasQuotation = false;
for(Sentence sent : doc.getSentences()) {
for(Lexicon lex : sent.getLexicons()) {
lex.utterance = utteranceIndex;
if(lex.form.equals("``") || (!insideQuotation && normalQuotationType && lex.form.equals("\""))) {
utteranceIndex++;
lex.utterance = utteranceIndex;
insideQuotation = true;
hasQuotation = true;
}
else if((utteranceIndex > 0 && lex.form.equals("''")) || (insideQuotation && normalQuotationType && lex.form.equals("\""))) {
insideQuotation = false;
utteranceIndex--;
}
}
}
if(!hasQuotation && !normalQuotationType) {
markQuotaions(doc, true);
}
}
/**
* find default speakers from the speaker tags of document
* @param doc
* @param allMentions
* @param speakersMap
*/
protected void findDefaultSpeakers(Document doc, List<Mention> allMentions, Map<String, SpeakerInfo> speakersMap) {
for(Mention mention : allMentions) {
Sentence sent = doc.getSentence(mention.sentID);
String speaker = sent.getSpeaker().equals("-") ? "<DEFAULT_SPEAKER>" : sent.getSpeaker();
SpeakerInfo speakerInfo = speakersMap.get(speaker);
if(speakerInfo == null) {
speakerInfo = new SpeakerInfo(speakersMap.size(), speaker, false);
speakersMap.put(speaker, speakerInfo);
}
mention.setSpeakerInfo(speakerInfo);
}
}
protected void findPreciseMatchRelation(Document doc, List<Mention> allMentions) {
for(int i = 1; i < allMentions.size(); ++i) {
Mention anaph = allMentions.get(i);
//find precise match
for(int j = 0; j < i; ++j) {
Mention antec = allMentions.get(j);
if(anaph.preciseMatch(doc.getSentence(anaph.sentID), antec, doc.getSentence(antec.sentID), dict)) {
anaph.addPreciseMatch(antec);
}
}
//find string match
for(int j = i - 1; j >= 0; --j) {
Mention antec = allMentions.get(j);
if(anaph.stringMatch(doc.getSentence(anaph.sentID), antec, doc.getSentence(antec.sentID), dict)) {
anaph.addStringMatch(antec);
}
}
}
}
protected void extractEvents(List<List<Mention>> mentionList, Document doc, Options options) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
eventExtractor.extractEvents(doc, mentionList, options);
}
protected void findSyntacticRelation(List<Mention> mentions, Sentence sent, Options options) throws InstantiationException, IllegalAccessException, ClassNotFoundException, MentionException{
markListMemberRelation(mentions, sent, RelationExtractor.createExtractor(options.getListMemberRelationExtractor()));
deleteSpuriousListMentions(mentions, sent);
correctHeadIndexforNERMentions(mentions, sent);
markAppositionRelation(mentions, sent, RelationExtractor.createExtractor(options.getAppositionRelationExtractor()));
markRoleAppositionRelation(mentions, sent, RelationExtractor.createExtractor(options.getRoleAppositionRelationExtractor()));
markPredicateNominativeRelation(mentions, sent, RelationExtractor.createExtractor(options.getPredicateNominativeRelationExtractor()));
deletePleonasticItwithTemproal(mentions, sent);
//markRelativePronounRelation(mentions, sent, RelationExtractor.createExtractor(options.getRelativePronounRelationExtractor()));
}
/**
* remove nested mention with shared headword (except enumeration/list): pick larger one
* @param mentions
* @param sent
*/
protected void deleteSpuriousListMentions(List<Mention> mentions, Sentence sent) {
Set<Mention> remove = new HashSet<Mention>();
for(Mention mention1 : mentions) {
for(Mention mention2 : mentions) {
if(mention1.headIndex == mention2.headIndex && mention2.cover(mention1) && mention1.getBelognTo() == null) {
remove.add(mention1);
}
}
}
mentions.removeAll(remove);
}
/**
* remove pleonastic it with Temporal mentions (e.g. it is summer)
* @param mentions
* @param sent
*/
protected void deletePleonasticItwithTemproal(List<Mention> mentions, Sentence sent) {
Set<Mention> remove = new HashSet<Mention>();
for(Mention mention : mentions) {
if(mention.isPronominal() && mention.headString.equals("it") && mention.getPredicateNominatives() != null) {
for(Mention predN : mention.getPredicateNominatives()) {
if(!mentions.contains(predN)) {
continue;
}
if(predN.isProper() && predN.headword.ner.equals("DATE")
|| predN.isNominative() && dict.temporals.contains(predN.headString)) {
remove.add(mention);
break;
}
}
}
else if(mention.isPronominal() && mention.headString.equals("it")) {
Lexicon headword = sent.getLexicon(mention.originalHeadIndex);
int head = headword.collapsed_head;
if(sent.getLexicon(head).lemma.equals("be") && headword.collapsed_deprel.equals("nsubj")) {
for(Mention mention2 : mentions) {
Lexicon headword2 = sent.getLexicon(mention2.originalHeadIndex);
if(headword2.id > head && headword2.collapsed_head == head && headword2.collapsed_deprel.startsWith("prep_")
&& (mention2.isProper() && mention2.headword.ner.equals("DATE")
|| mention2.isNominative() && dict.temporals.contains(mention2.headString))) {
remove.add(mention);
}
}
}
}
}
mentions.removeAll(remove);
}
protected void correctHeadIndexforNERMentions(List<Mention> mentions, Sentence sent) {
for(Mention mention : mentions) {
mention.correctHeadIndex(sent, dict, wordNet);
}
}
protected void markListMemberRelation(List<Mention> mentions, Sentence sent, RelationExtractor extractor) throws MentionException {
Set<Pair<Integer, Integer>> foundPairs = extractor.extractRelation(sent, mentions);
markMentionRelation(mentions, sent, foundPairs, "LISTMEMBER");
}
protected void markAppositionRelation(List<Mention> mentions, Sentence sent, RelationExtractor extractor) throws MentionException {
Set<Pair<Integer, Integer>> foundPairs = extractor.extractRelation(sent, mentions);
markMentionRelation(mentions, sent, foundPairs, "APPOSITION");
}
protected void markRoleAppositionRelation(List<Mention> mentions, Sentence sent, RelationExtractor extractor) throws MentionException {
Set<Pair<Integer, Integer>> foundPairs = extractor.extractRelation(sent, mentions);
markMentionRelation(mentions, sent, foundPairs, "ROLE_APPOSITION");
}
protected void markPredicateNominativeRelation(List<Mention> mentions, Sentence sent, RelationExtractor extractor) throws MentionException {
Set<Pair<Integer, Integer>> foundPairs = extractor.extractRelation(sent, mentions);
markMentionRelation(mentions, sent, foundPairs, "PREDICATE_NOMINATIVE");
}
protected void markRelativePronounRelation(List<Mention> mentions, Sentence sent, RelationExtractor extractor) throws MentionException {
Set<Pair<Integer, Integer>> foundPairs = extractor.extractRelation(sent, mentions);
markMentionRelation(mentions, sent, foundPairs, "RELATIVE_PRONOUN");
}
protected void markMentionRelation(List<Mention> mentions, Sentence sent, Set<Pair<Integer, Integer>> foundPairs, String relation) throws MentionException {
for(Mention mention1 : mentions) {
for(Mention mention2 : mentions) {
if(mention1.equals(mention2)) {
continue;
}
if(relation.equals("LISTMEMBER")) {
for(Pair<Integer, Integer> pair : foundPairs) {
if(pair.first == mention1.mentionID && pair.second == mention2.mentionID) {
mention2.addListMember(mention1, sent);
}
}
}
else if(relation.equals("PREDICATE_NOMINATIVE")) {
for(Pair<Integer, Integer> pair : foundPairs) {
if(pair.first == mention1.mentionID && pair.second == mention2.mentionID) {
mention2.addPredicativeNominative(mention1, dict);
}
}
}
else if(relation.equals("ROLE_APPOSITION")) {
for(Pair<Integer, Integer> pair : foundPairs) {
if(pair.first == mention1.mentionID && pair.second == mention2.mentionID) {
mention2.addRoleApposition(mention1, sent, dict);
}
}
}
else{
for(Pair<Integer, Integer> pair : foundPairs) {
if(pair.first == mention1.originalHeadIndex && pair.second == mention2.originalHeadIndex) {
if(relation.equals("APPOSITION")) {
mention2.addApposition(mention1, dict);
}
else if(relation.equals("RELATIVE_PRONOUN")) {
mention2.addRelativePronoun(mention1);
}
else {
throw new MentionException("Unknown mention relation: " + relation);
}
}
}
}
}
}
}
public void displayMentions(Document doc, List<List<Mention>> mentionList, PrintStream printer){
printer.println("#begin document " + doc.getFileName() + " docId " + doc.getDocId());
int sentId = 0;
for(List<Mention> mentions : mentionList){
printer.println("sent Id: " + sentId);
for(Mention mention : mentions){
displayMention(doc.getSentence(sentId), mention, printer);
}
sentId++;
printer.println("----------------------------------------");
}
printer.println("end document");
printer.flush();
}
public void displayMention(Sentence sent, Mention mention, PrintStream printer){
mention.display(sent, printer);
}
}
| gpl-2.0 |
everin/jSignerFast | src/test/java/it/everin/ui/jSignerFastTest.java | 424 | package it.everin.ui;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class jSignerFastTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test() {
System.out.println("ciao");
//fail("Not yet implemented");
}
}
| gpl-2.0 |
TheMartinLab/GlobalPackages | misc/email/PropertiesFactory.java | 536 | /**
* @author Eric D. Dill eddill@ncsu.edu
* @author James D. Martin jdmartin@ncsu.edu
* Copyright © 2010-2013 North Carolina State University. All rights reserved
*/
package email;
import java.util.Properties;
public class PropertiesFactory {
public static Properties getGmailProperties() {
Properties gmail = new Properties();
gmail.put("mail.smtp.auth", "true");
gmail.put("mail.smtp.starttls.enable", "true");
gmail.put("mail.smtp.host", "smtp.gmail.com");
gmail.put("mail.smtp.port", "587");
return gmail;
}
}
| gpl-2.0 |
ravitej-aluru/UI-Automation-Framework.Java | selenium-extensions/src/test/java/io/ravitej/selenium/extensions/tests/WebDriverExtensionsTests.java | 4010 | package io.ravitej.selenium.extensions.tests;
import io.ravitej.selenium.extensions.WebDriverExtensions;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.SoftAssertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver.TargetLocator;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for WebDriverExtensions.
*
* @author Ravitej Aluru
*/
public class WebDriverExtensionsTests {
private WebDriver mockWebDriver = mock(WebDriver.class, Mockito.withSettings().extraInterfaces(TakesScreenshot.class));
private TargetLocator mockTargetLocator = mock(TargetLocator.class);
private Alert mockAlert = mock(Alert.class);
private File mockFile = mock(File.class);
@Before
public void beforeTest() {
when(mockWebDriver.switchTo()).thenReturn(mockTargetLocator);
when(mockTargetLocator.alert()).thenReturn(mockAlert);
}
@Test
public void is_alert_displayed_should_return_true_and_alert_text_if_alert_displayed() {
final String alertText = "some mockAlert text";
when(mockAlert.getText()).thenReturn(alertText);
Pair<Boolean, String> p = WebDriverExtensions.isAlertDisplayed(mockWebDriver);
assertThat(p).extracting("key", "value").containsExactly(true, alertText);
}
@Test
public void is_alert_displayed_should_return_false_and_empty_string_if_alert_is_not_displayed() {
when(mockAlert.getText()).thenThrow(NoAlertPresentException.class);
Pair<Boolean, String> p = WebDriverExtensions.isAlertDisplayed(mockWebDriver);
assertThat(p).extracting("key", "value").containsExactly(false, "");
}
@Test
public void take_screenshot_should_return_file_if_successful_on_first_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE)).thenReturn(mockFile);
File screenshot = WebDriverExtensions.takeScreenshot(mockWebDriver);
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(screenshot)
.isInstanceOf(File.class)
.isNotNull();
});
}
@Test
public void take_screenshot_should_return_file_if_successful_on_second_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException())
.thenReturn(mockFile);
File screenshot = WebDriverExtensions.takeScreenshot(mockWebDriver);
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(screenshot)
.isInstanceOf(File.class)
.isNotNull();
});
}
@Test
public void take_screenshot_should_throw_webdriverexception_if_not_successful_on_second_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException());
assertThatExceptionOfType(WebDriverException.class).isThrownBy(() -> {
WebDriverExtensions.takeScreenshot(mockWebDriver);
});
}
@Test
public void take_screenshot_should_wait_for_given_amount_of_time_if_not_successful_on_first_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException())
.thenReturn(mockFile);
final long waitTime = 1000;
long before = System.currentTimeMillis();
WebDriverExtensions.takeScreenshot(mockWebDriver, waitTime);
long after = System.currentTimeMillis();
//checking that the method took at least 1 second to execute since the waitTime is 1 second.
assertThat(after - before).isGreaterThanOrEqualTo(waitTime);
}
} | gpl-2.0 |
ncuongce/SleepyTrout | src/com/androidgames/framework/gl/SpriteBatcher.java | 4487 | package com.androidgames.framework.gl;
import javax.microedition.khronos.opengles.GL10;
import android.util.FloatMath;
import com.androidgames.framework.impl.GLGraphics;
import com.androidgames.framework.math.Vector2;
public class SpriteBatcher {
final float[] verticesBuffer;
int bufferIndex;
final Vertices vertices;
int numSprites;
public SpriteBatcher(GLGraphics glGraphics, int maxSprites) {
this.verticesBuffer = new float[maxSprites*4*4];
this.vertices = new Vertices(glGraphics, maxSprites*4, maxSprites*6, false, true);
this.bufferIndex = 0;
this.numSprites = 0;
short[] indices = new short[maxSprites*6];
int len = indices.length;
short j = 0;
for (int i = 0; i < len; i += 6, j += 4) {
indices[i + 0] = (short)(j + 0);
indices[i + 1] = (short)(j + 1);
indices[i + 2] = (short)(j + 2);
indices[i + 3] = (short)(j + 2);
indices[i + 4] = (short)(j + 3);
indices[i + 5] = (short)(j + 0);
}
vertices.setIndices(indices, 0, indices.length);
}
public void beginBatch(Texture texture) {
texture.bind();
numSprites = 0;
bufferIndex = 0;
}
public void endBatch() {
vertices.setVertices(verticesBuffer, 0, bufferIndex);
vertices.bind();
vertices.draw(GL10.GL_TRIANGLES, 0, numSprites * 6);
vertices.unbind();
}
public void drawSprite(float x, float y, float width, float height, TextureRegion region) {
float halfWidth = width / 2;
float halfHeight = height / 2;
float x1 = x - halfWidth;
float y1 = y - halfHeight;
float x2 = x + halfWidth;
float y2 = y + halfHeight;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v1;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v1;
numSprites++;
}
public void drawSprite(float x, float y, float width, float height, float angle, TextureRegion region) {
float halfWidth = width / 2;
float halfHeight = height / 2;
float rad = angle * Vector2.TO_RADIANS;
float cos = FloatMath.cos(rad);
float sin = FloatMath.sin(rad);
float x1 = -halfWidth * cos - (-halfHeight) * sin;
float y1 = -halfWidth * sin + (-halfHeight) * cos;
float x2 = halfWidth * cos - (-halfHeight) * sin;
float y2 = halfWidth * sin + (-halfHeight) * cos;
float x3 = halfWidth * cos - halfHeight * sin;
float y3 = halfWidth * sin + halfHeight * cos;
float x4 = -halfWidth * cos - halfHeight * sin;
float y4 = -halfWidth * sin + halfHeight * cos;
x1 += x;
y1 += y;
x2 += x;
y2 += y;
x3 += x;
y3 += y;
x4 += x;
y4 += y;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x3;
verticesBuffer[bufferIndex++] = y3;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v1;
verticesBuffer[bufferIndex++] = x4;
verticesBuffer[bufferIndex++] = y4;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v1;
numSprites++;
}
}
| gpl-2.0 |
tkpb/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java | 53484 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Adapters;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.SQLite.SQLiteCursor;
import org.telegram.SQLite.SQLitePreparedStatement;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Cells.GraySectionCell;
import org.telegram.ui.Cells.HashtagSearchCell;
import org.telegram.ui.Cells.HintDialogCell;
import org.telegram.ui.Cells.ProfileSearchCell;
import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Components.FlickerLoadingView;
import org.telegram.ui.Components.ForegroundColorSpanThemable;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.FilteredSearchView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
private Context mContext;
private Runnable searchRunnable;
private Runnable searchRunnable2;
private ArrayList<TLObject> searchResult = new ArrayList<>();
private ArrayList<CharSequence> searchResultNames = new ArrayList<>();
private ArrayList<MessageObject> searchResultMessages = new ArrayList<>();
private ArrayList<String> searchResultHashtags = new ArrayList<>();
private String lastSearchText;
private boolean searchWas;
private int reqId = 0;
private int lastReqId;
private DialogsSearchAdapterDelegate delegate;
private int needMessagesSearch;
private boolean messagesSearchEndReached;
private String lastMessagesSearchString;
private String currentMessagesQuery;
private int nextSearchRate;
private int lastSearchId;
private int lastGlobalSearchId;
private int lastLocalSearchId;
private int lastMessagesSearchId;
private int dialogsType;
private SearchAdapterHelper searchAdapterHelper;
private RecyclerListView innerListView;
private int selfUserId;
private int currentAccount = UserConfig.selectedAccount;
private ArrayList<RecentSearchObject> recentSearchObjects = new ArrayList<>();
private LongSparseArray<RecentSearchObject> recentSearchObjectsById = new LongSparseArray<>();
private ArrayList<TLRPC.User> localTipUsers = new ArrayList<>();
private ArrayList<FiltersView.DateData> localTipDates = new ArrayList<>();
private FilteredSearchView.Delegate filtersDelegate;
private int folderId;
public boolean isSearching() {
return waitingResponseCount > 0;
}
public static class DialogSearchResult {
public TLObject object;
public int date;
public CharSequence name;
}
protected static class RecentSearchObject {
TLObject object;
int date;
long did;
}
public interface DialogsSearchAdapterDelegate {
void searchStateChanged(boolean searching, boolean animated);
void didPressedOnSubDialog(long did);
void needRemoveHint(int did);
void needClearList();
void runResultsEnterAnimation();
}
private class CategoryAdapterRecycler extends RecyclerListView.SelectionAdapter {
public void setIndex(int value) {
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = new HintDialogCell(mContext);
view.setLayoutParams(new RecyclerView.LayoutParams(AndroidUtilities.dp(80), AndroidUtilities.dp(86)));
return new RecyclerListView.Holder(view);
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return true;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
HintDialogCell cell = (HintDialogCell) holder.itemView;
TLRPC.TL_topPeer peer = MediaDataController.getInstance(currentAccount).hints.get(position);
TLRPC.Dialog dialog = new TLRPC.TL_dialog();
TLRPC.Chat chat = null;
TLRPC.User user = null;
int did = 0;
if (peer.peer.user_id != 0) {
did = peer.peer.user_id;
user = MessagesController.getInstance(currentAccount).getUser(peer.peer.user_id);
} else if (peer.peer.channel_id != 0) {
did = -peer.peer.channel_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.channel_id);
} else if (peer.peer.chat_id != 0) {
did = -peer.peer.chat_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.chat_id);
}
cell.setTag(did);
String name = "";
if (user != null) {
name = UserObject.getFirstName(user);
} else if (chat != null) {
name = chat.title;
}
cell.setDialog(did, true, name);
}
@Override
public int getItemCount() {
return MediaDataController.getInstance(currentAccount).hints.size();
}
}
public DialogsSearchAdapter(Context context, int messagesSearch, int type, int folderId) {
this.folderId = folderId;
searchAdapterHelper = new SearchAdapterHelper(false);
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override
public void onDataSetChanged(int searchId) {
waitingResponseCount--;
lastGlobalSearchId = searchId;
if (lastLocalSearchId != searchId) {
searchResult.clear();
}
if (lastMessagesSearchId != searchId) {
searchResultMessages.clear();
}
searchWas = true;
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
}
notifyDataSetChanged();
if (delegate != null) {
delegate.runResultsEnterAnimation();
}
}
@Override
public void onSetHashtags(ArrayList<SearchAdapterHelper.HashtagObject> arrayList, HashMap<String, SearchAdapterHelper.HashtagObject> hashMap) {
for (int a = 0; a < arrayList.size(); a++) {
searchResultHashtags.add(arrayList.get(a).hashtag);
}
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, false);
}
notifyDataSetChanged();
}
@Override
public boolean canApplySearchResults(int searchId) {
return searchId == lastSearchId;
}
});
mContext = context;
needMessagesSearch = messagesSearch;
dialogsType = type;
selfUserId = UserConfig.getInstance(currentAccount).getClientUserId();
loadRecentSearch();
MediaDataController.getInstance(currentAccount).loadHints(true);
}
public RecyclerListView getInnerListView() {
return innerListView;
}
public void setDelegate(DialogsSearchAdapterDelegate delegate) {
this.delegate = delegate;
}
public boolean isMessagesSearchEndReached() {
return messagesSearchEndReached;
}
public void loadMoreSearchMessages() {
if (reqId != 0) {
return;
}
searchMessagesInternal(lastMessagesSearchString, lastMessagesSearchId);
}
public String getLastSearchString() {
return lastMessagesSearchString;
}
private void searchMessagesInternal(final String query, int searchId) {
if (needMessagesSearch == 0 || TextUtils.isEmpty(lastMessagesSearchString) && TextUtils.isEmpty(query)) {
return;
}
if (reqId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true);
reqId = 0;
}
if (TextUtils.isEmpty(query)) {
searchResultMessages.clear();
lastReqId = 0;
lastMessagesSearchString = null;
searchWas = false;
notifyDataSetChanged();
return;
}
final TLRPC.TL_messages_searchGlobal req = new TLRPC.TL_messages_searchGlobal();
req.limit = 20;
req.q = query;
req.filter = new TLRPC.TL_inputMessagesFilterEmpty();
if (query.equals(lastMessagesSearchString) && !searchResultMessages.isEmpty()) {
MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1);
req.offset_id = lastMessage.getId();
req.offset_rate = nextSearchRate;
int id;
if (lastMessage.messageOwner.peer_id.channel_id != 0) {
id = -lastMessage.messageOwner.peer_id.channel_id;
} else if (lastMessage.messageOwner.peer_id.chat_id != 0) {
id = -lastMessage.messageOwner.peer_id.chat_id;
} else {
id = lastMessage.messageOwner.peer_id.user_id;
}
req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id);
} else {
req.offset_rate = 0;
req.offset_id = 0;
req.offset_peer = new TLRPC.TL_inputPeerEmpty();
}
lastMessagesSearchString = query;
final int currentReqId = ++lastReqId;
reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
final ArrayList<MessageObject> messageObjects = new ArrayList<>();
if (error == null) {
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
SparseArray<TLRPC.Chat> chatsMap = new SparseArray<>();
SparseArray<TLRPC.User> usersMap = new SparseArray<>();
for (int a = 0; a < res.chats.size(); a++) {
TLRPC.Chat chat = res.chats.get(a);
chatsMap.put(chat.id, chat);
}
for (int a = 0; a < res.users.size(); a++) {
TLRPC.User user = res.users.get(a);
usersMap.put(user.id, user);
}
for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a);
MessageObject messageObject = new MessageObject(currentAccount, message, usersMap, chatsMap, false, true);
messageObjects.add(messageObject);
messageObject.setQuery(query);
}
}
AndroidUtilities.runOnUIThread(() -> {
if (currentReqId == lastReqId && (searchId <= 0 || searchId == lastSearchId)) {
waitingResponseCount--;
if (error == null) {
currentMessagesQuery = query;
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true);
MessagesController.getInstance(currentAccount).putUsers(res.users, false);
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
if (req.offset_id == 0) {
searchResultMessages.clear();
}
nextSearchRate = res.next_rate;
for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a);
long did = MessageObject.getDialogId(message);
Integer maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did);
if (maxId != null && message.id <= maxId) {
continue;
}
searchResultMessages.add(messageObjects.get(a));
long dialog_id = MessageObject.getDialogId(message);
ConcurrentHashMap<Long, Integer> read_max = message.out ? MessagesController.getInstance(currentAccount).dialogs_read_outbox_max : MessagesController.getInstance(currentAccount).dialogs_read_inbox_max;
Integer value = read_max.get(dialog_id);
if (value == null) {
value = MessagesStorage.getInstance(currentAccount).getDialogReadMax(message.out, dialog_id);
read_max.put(dialog_id, value);
}
message.unread = value < message.id;
}
searchWas = true;
messagesSearchEndReached = res.messages.size() != 20;
if (searchId > 0) {
lastMessagesSearchId = searchId;
if (lastLocalSearchId != searchId) {
searchResult.clear();
}
if (lastGlobalSearchId != searchId) {
searchAdapterHelper.clear();
}
}
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
delegate.runResultsEnterAnimation();
}
}
}
reqId = 0;
});
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}
public boolean hasRecentSearch() {
return dialogsType != 2 && dialogsType != 4 && dialogsType != 5 && dialogsType != 6 && (!recentSearchObjects.isEmpty() || !MediaDataController.getInstance(currentAccount).hints.isEmpty());
}
public boolean isRecentSearchDisplayed() {
return needMessagesSearch != 2 && !searchWas && (!recentSearchObjects.isEmpty() || !MediaDataController.getInstance(currentAccount).hints.isEmpty()) && dialogsType != 2 && dialogsType != 4 && dialogsType != 5 && dialogsType != 6;
}
public void loadRecentSearch() {
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1");
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
ArrayList<TLRPC.User> encUsers = new ArrayList<>();
final ArrayList<RecentSearchObject> arrayList = new ArrayList<>();
final LongSparseArray<RecentSearchObject> hashMap = new LongSparseArray<>();
while (cursor.next()) {
long did = cursor.longValue(0);
boolean add = false;
int lower_id = (int) did;
int high_id = (int) (did >> 32);
if (lower_id != 0) {
if (lower_id > 0) {
if (dialogsType != 2 && !usersToLoad.contains(lower_id)) {
usersToLoad.add(lower_id);
add = true;
}
} else {
if (!chatsToLoad.contains(-lower_id)) {
chatsToLoad.add(-lower_id);
add = true;
}
}
} else if (dialogsType == 0 || dialogsType == 3) {
if (!encryptedToLoad.contains(high_id)) {
encryptedToLoad.add(high_id);
add = true;
}
}
if (add) {
RecentSearchObject recentSearchObject = new RecentSearchObject();
recentSearchObject.did = did;
recentSearchObject.date = cursor.intValue(1);
arrayList.add(recentSearchObject);
hashMap.put(recentSearchObject.did, recentSearchObject);
}
}
cursor.dispose();
ArrayList<TLRPC.User> users = new ArrayList<>();
if (!encryptedToLoad.isEmpty()) {
ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad);
for (int a = 0; a < encryptedChats.size(); a++) {
hashMap.get((long) encryptedChats.get(a).id << 32).object = encryptedChats.get(a);
}
}
if (!chatsToLoad.isEmpty()) {
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
for (int a = 0; a < chats.size(); a++) {
TLRPC.Chat chat = chats.get(a);
long did = -chat.id;
if (chat.migrated_to != null) {
RecentSearchObject recentSearchObject = hashMap.get(did);
hashMap.remove(did);
if (recentSearchObject != null) {
arrayList.remove(recentSearchObject);
}
} else {
hashMap.get(did).object = chat;
}
}
}
if (!usersToLoad.isEmpty()) {
MessagesStorage.getInstance(currentAccount).getUsersInternal(TextUtils.join(",", usersToLoad), users);
for (int a = 0; a < users.size(); a++) {
TLRPC.User user = users.get(a);
RecentSearchObject recentSearchObject = hashMap.get(user.id);
if (recentSearchObject != null) {
recentSearchObject.object = user;
}
}
}
Collections.sort(arrayList, (lhs, rhs) -> {
if (lhs.date < rhs.date) {
return 1;
} else if (lhs.date > rhs.date) {
return -1;
} else {
return 0;
}
});
AndroidUtilities.runOnUIThread(() -> setRecentSearch(arrayList, hashMap));
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void putRecentSearch(final long did, TLObject object) {
RecentSearchObject recentSearchObject = recentSearchObjectsById.get(did);
if (recentSearchObject == null) {
recentSearchObject = new RecentSearchObject();
recentSearchObjectsById.put(did, recentSearchObject);
} else {
recentSearchObjects.remove(recentSearchObject);
}
recentSearchObjects.add(0, recentSearchObject);
recentSearchObject.did = did;
recentSearchObject.object = object;
recentSearchObject.date = (int) (System.currentTimeMillis() / 1000);
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
SQLitePreparedStatement state = MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("REPLACE INTO search_recent VALUES(?, ?)");
state.requery();
state.bindLong(1, did);
state.bindInteger(2, (int) (System.currentTimeMillis() / 1000));
state.step();
state.dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void clearRecentSearch() {
recentSearchObjectsById = new LongSparseArray<>();
recentSearchObjects = new ArrayList<>();
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("DELETE FROM search_recent WHERE 1").stepThis().dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void removeRecentSearch(long did) {
RecentSearchObject object = recentSearchObjectsById.get(did);
if (object == null) {
return;
}
recentSearchObjectsById.remove(did);
recentSearchObjects.remove(object);
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("DELETE FROM search_recent WHERE did = " + did).stepThis().dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void addHashtagsFromMessage(CharSequence message) {
searchAdapterHelper.addHashtagsFromMessage(message);
}
private void setRecentSearch(ArrayList<RecentSearchObject> arrayList, LongSparseArray<RecentSearchObject> hashMap) {
recentSearchObjects = arrayList;
recentSearchObjectsById = hashMap;
for (int a = 0; a < recentSearchObjects.size(); a++) {
RecentSearchObject recentSearchObject = recentSearchObjects.get(a);
if (recentSearchObject.object instanceof TLRPC.User) {
MessagesController.getInstance(currentAccount).putUser((TLRPC.User) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.Chat) {
MessagesController.getInstance(currentAccount).putChat((TLRPC.Chat) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.EncryptedChat) {
MessagesController.getInstance(currentAccount).putEncryptedChat((TLRPC.EncryptedChat) recentSearchObject.object, true);
}
}
notifyDataSetChanged();
}
private void searchDialogsInternal(final String query, final int searchId) {
if (needMessagesSearch == 2) {
return;
}
String q = query.trim().toLowerCase();
if (q.length() == 0) {
lastSearchId = 0;
updateSearchResults(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), lastSearchId);
return;
}
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
ArrayList<TLObject> resultArray = new ArrayList<>();
ArrayList<CharSequence> resultArrayNames = new ArrayList<>();
ArrayList<TLRPC.User> encUsers = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).localSearch(dialogsType, q, resultArray, resultArrayNames, encUsers, -1);
updateSearchResults(resultArray, resultArrayNames, encUsers, searchId);
FiltersView.fillTipDates(q, localTipDates);
AndroidUtilities.runOnUIThread(() -> {
if (filtersDelegate != null) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
});
});
}
private void updateSearchResults(final ArrayList<TLObject> result, final ArrayList<CharSequence> names, final ArrayList<TLRPC.User> encUsers, final int searchId) {
AndroidUtilities.runOnUIThread(() -> {
waitingResponseCount--;
if (searchId != lastSearchId) {
return;
}
lastLocalSearchId = searchId;
if (lastGlobalSearchId != searchId) {
searchAdapterHelper.clear();
}
if (lastMessagesSearchId != searchId) {
searchResultMessages.clear();
}
searchWas = true;
for (int a = 0; a < result.size(); a++) {
TLObject obj = result.get(a);
if (obj instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) obj;
MessagesController.getInstance(currentAccount).putUser(user, true);
} else if (obj instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) obj;
MessagesController.getInstance(currentAccount).putChat(chat, true);
} else if (obj instanceof TLRPC.EncryptedChat) {
TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) obj;
MessagesController.getInstance(currentAccount).putEncryptedChat(chat, true);
}
}
MessagesController.getInstance(currentAccount).putUsers(encUsers, true);
searchResult = result;
searchResultNames = names;
searchAdapterHelper.mergeResults(searchResult);
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
delegate.runResultsEnterAnimation();
}
});
}
public boolean isHashtagSearch() {
return !searchResultHashtags.isEmpty();
}
public void clearRecentHashtags() {
searchAdapterHelper.clearRecentHashtags();
searchResultHashtags.clear();
notifyDataSetChanged();
}
int waitingResponseCount;
public void searchDialogs(String text) {
if (text != null && text.equals(lastSearchText)) {
return;
}
lastSearchText = text;
if (searchRunnable != null) {
Utilities.searchQueue.cancelRunnable(searchRunnable);
searchRunnable = null;
}
if (searchRunnable2 != null) {
AndroidUtilities.cancelRunOnUIThread(searchRunnable2);
searchRunnable2 = null;
}
String query;
if (text != null) {
query = text.trim();
} else {
query = null;
}
if (TextUtils.isEmpty(query)) {
searchAdapterHelper.unloadRecentHashtags();
searchResult.clear();
searchResultNames.clear();
searchResultHashtags.clear();
searchAdapterHelper.mergeResults(null);
searchAdapterHelper.queryServerSearch(null, true, true, true, true, dialogsType == 2, 0, dialogsType == 0, 0, 0);
searchWas = false;
lastSearchId = 0;
waitingResponseCount = 0;
if (delegate != null) {
delegate.searchStateChanged(false, true);
}
searchMessagesInternal(null, 0);
notifyDataSetChanged();
localTipDates.clear();
if (filtersDelegate != null) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
} else {
if (needMessagesSearch != 2 && (query.startsWith("#") && query.length() == 1)) {
messagesSearchEndReached = true;
if (searchAdapterHelper.loadRecentHashtags()) {
searchResultMessages.clear();
searchResultHashtags.clear();
ArrayList<SearchAdapterHelper.HashtagObject> hashtags = searchAdapterHelper.getHashtags();
for (int a = 0; a < hashtags.size(); a++) {
searchResultHashtags.add(hashtags.get(a).hashtag);
}
waitingResponseCount = 0;
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(false, false);
}
}
} else {
searchResultHashtags.clear();
}
final int searchId = ++lastSearchId;
waitingResponseCount = 3;
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(true, false);
}
Utilities.searchQueue.postRunnable(searchRunnable = () -> {
searchRunnable = null;
searchDialogsInternal(query, searchId);
AndroidUtilities.runOnUIThread(searchRunnable2 = () -> {
searchRunnable2 = null;
if (searchId != lastSearchId) {
return;
}
if (needMessagesSearch != 2) {
searchAdapterHelper.queryServerSearch(query, true, dialogsType != 4, true, dialogsType != 4, dialogsType == 2, 0, dialogsType == 0, 0, searchId);
} else {
waitingResponseCount -= 2;
}
if (needMessagesSearch == 0) {
waitingResponseCount--;
} else {
searchMessagesInternal(text, searchId);
}
});
}, 300);
}
}
@Override
public int getItemCount() {
if (waitingResponseCount == 3) {
return 0;
}
if (isRecentSearchDisplayed()) {
return (!recentSearchObjects.isEmpty() ? recentSearchObjects.size() + 1 : 0) + (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
}
int count = 0;
if (!searchResultHashtags.isEmpty()) {
count += searchResultHashtags.size() + 1;
return count;
}
count += searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int globalCount = searchAdapterHelper.getGlobalSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int messagesCount = searchResultMessages.size();
count += localServerCount;
if (globalCount != 0) {
count += globalCount + 1;
}
if (phoneCount != 0) {
count += phoneCount;
}
if (messagesCount != 0) {
count += messagesCount + 1 + (messagesSearchEndReached ? 0 : 1);
}
return count;
}
public Object getItem(int i) {
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (i > offset && i - 1 - offset < recentSearchObjects.size()) {
TLObject object = recentSearchObjects.get(i - 1 - offset).object;
if (object instanceof TLRPC.User) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(((TLRPC.User) object).id);
if (user != null) {
object = user;
}
} else if (object instanceof TLRPC.Chat) {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) object).id);
if (chat != null) {
object = chat;
}
}
return object;
} else {
return null;
}
}
if (!searchResultHashtags.isEmpty()) {
if (i > 0) {
return searchResultHashtags.get(i - 1);
} else {
return null;
}
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<TLObject> localServerSearch = searchAdapterHelper.getLocalServerSearch();
ArrayList<Object> phoneSearch = searchAdapterHelper.getPhoneSearch();
int localCount = searchResult.size();
int localServerCount = localServerSearch.size();
int phoneCount = phoneSearch.size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return searchResult.get(i);
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return localServerSearch.get(i);
} else {
i -= localServerCount;
if (i >= 0 && i < phoneCount) {
return phoneSearch.get(i);
} else {
i -= phoneCount;
if (i > 0 && i < globalCount) {
return globalSearch.get(i - 1);
} else {
i -= globalCount;
if (i > 0 && i < messagesCount) {
return searchResultMessages.get(i - 1);
}
}
}
}
}
return null;
}
public boolean isGlobalSearch(int i) {
if (isRecentSearchDisplayed()) {
return false;
}
if (!searchResultHashtags.isEmpty()) {
return false;
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<TLObject> localServerSearch = searchAdapterHelper.getLocalServerSearch();
int localCount = searchResult.size();
int localServerCount = localServerSearch.size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return false;
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return false;
} else {
i -= localServerCount;
if (i > 0 && i < phoneCount) {
return false;
} else {
i -= phoneCount;
if (i > 0 && i < globalCount) {
return true;
} else {
i -= globalCount;
if (i > 0 && i < messagesCount) {
return false;
}
}
}
}
}
return false;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
int type = holder.getItemViewType();
return type != 1 && type != 3;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
switch (viewType) {
case 0:
view = new ProfileSearchCell(mContext);
break;
case 1:
view = new GraySectionCell(mContext);
break;
case 2:
view = new DialogCell(mContext, false, true);
break;
case 3:
FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext);
flickerLoadingView.setViewType(FlickerLoadingView.DIALOG_TYPE);
flickerLoadingView.setIsSingleCell(true);
view = flickerLoadingView;
break;
case 4:
view = new HashtagSearchCell(mContext);
break;
case 5:
RecyclerListView horizontalListView = new RecyclerListView(mContext) {
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (getParent() != null && getParent().getParent() != null) {
getParent().getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(-1) || canScrollHorizontally(1));
}
return super.onInterceptTouchEvent(e);
}
};
horizontalListView.setTag(9);
horizontalListView.setItemAnimator(null);
horizontalListView.setLayoutAnimation(null);
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
};
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalListView.setLayoutManager(layoutManager);
//horizontalListView.setDisallowInterceptTouchEvents(true);
horizontalListView.setAdapter(new CategoryAdapterRecycler());
horizontalListView.setOnItemClickListener((view1, position) -> {
if (delegate != null) {
delegate.didPressedOnSubDialog((Integer) view1.getTag());
}
});
horizontalListView.setOnItemLongClickListener((view12, position) -> {
if (delegate != null) {
delegate.needRemoveHint((Integer) view12.getTag());
}
return true;
});
view = horizontalListView;
innerListView = horizontalListView;
break;
case 6:
view = new TextCell(mContext, 16, false);
break;
}
if (viewType == 5) {
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(86)));
} else {
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: {
ProfileSearchCell cell = (ProfileSearchCell) holder.itemView;
TLRPC.User user = null;
TLRPC.Chat chat = null;
TLRPC.EncryptedChat encryptedChat = null;
CharSequence username = null;
CharSequence name = null;
boolean isRecent = false;
String un = null;
Object obj = getItem(position);
if (obj instanceof TLRPC.User) {
user = (TLRPC.User) obj;
un = user.username;
} else if (obj instanceof TLRPC.Chat) {
chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) obj).id);
if (chat == null) {
chat = (TLRPC.Chat) obj;
}
un = chat.username;
} else if (obj instanceof TLRPC.EncryptedChat) {
encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(((TLRPC.EncryptedChat) obj).id);
user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id);
}
if (isRecentSearchDisplayed()) {
isRecent = true;
cell.useSeparator = position != getItemCount() - 1;
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<Object> phoneSearch = searchAdapterHelper.getPhoneSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = phoneSearch.size();
int phoneCount2 = phoneCount;
if (phoneCount > 0 && phoneSearch.get(phoneCount - 1) instanceof String) {
phoneCount2 -= 2;
}
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
cell.useSeparator = (position != getItemCount() - 1 && position != localCount + phoneCount2 + localServerCount - 1 && position != localCount + globalCount + phoneCount + localServerCount - 1);
if (position < searchResult.size()) {
name = searchResultNames.get(position);
if (name != null && user != null && user.username != null && user.username.length() > 0) {
if (name.toString().startsWith("@" + user.username)) {
username = name;
name = null;
}
}
} else {
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (!TextUtils.isEmpty(foundUserName)) {
String nameSearch = null;
String nameSearchLower = null;
int index;
if (user != null) {
nameSearch = ContactsController.formatName(user.first_name, user.last_name);
} else if (chat != null) {
nameSearch = chat.title;
}
if (nameSearch != null && (index = AndroidUtilities.indexOfIgnoreCase(nameSearch, foundUserName)) != -1) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(nameSearch);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder;
} else if (un != null) {
if (foundUserName.startsWith("@")) {
foundUserName = foundUserName.substring(1);
}
try {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append("@");
spannableStringBuilder.append(un);
if ((index = AndroidUtilities.indexOfIgnoreCase(un, foundUserName)) != -1) {
int len = foundUserName.length();
if (index == 0) {
len++;
} else {
index++;
}
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
username = spannableStringBuilder;
} catch (Exception e) {
username = un;
FileLog.e(e);
}
}
}
}
}
boolean savedMessages = false;
if (user != null && user.id == selfUserId) {
name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
username = null;
savedMessages = true;
}
if (chat != null && chat.participants_count != 0) {
String membersString;
if (ChatObject.isChannel(chat) && !chat.megagroup) {
membersString = LocaleController.formatPluralString("Subscribers", chat.participants_count);
} else {
membersString = LocaleController.formatPluralString("Members", chat.participants_count);
}
if (username instanceof SpannableStringBuilder) {
((SpannableStringBuilder) username).append(", ").append(membersString);
} else if (!TextUtils.isEmpty(username)) {
username = TextUtils.concat(username, ", ", membersString);
} else {
username = membersString;
}
}
cell.setData(user != null ? user : chat, encryptedChat, name, username, isRecent, savedMessages);
break;
}
case 1: {
GraySectionCell cell = (GraySectionCell) holder.itemView;
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (position < offset) {
cell.setText(LocaleController.getString("ChatHints", R.string.ChatHints));
} else {
cell.setText(LocaleController.getString("Recent", R.string.Recent), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
}
} else if (!searchResultHashtags.isEmpty()) {
cell.setText(LocaleController.getString("Hashtags", R.string.Hashtags), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
position -= localCount + localServerCount;
if (position >= 0 && position < phoneCount) {
cell.setText(LocaleController.getString("PhoneNumberSearch", R.string.PhoneNumberSearch));
} else {
position -= phoneCount;
if (position >= 0 && position < globalCount) {
cell.setText(LocaleController.getString("GlobalSearch", R.string.GlobalSearch));
} else {
cell.setText(LocaleController.getString("SearchMessages", R.string.SearchMessages));
}
}
}
break;
}
case 2: {
DialogCell cell = (DialogCell) holder.itemView;
cell.useSeparator = (position != getItemCount() - 1);
MessageObject messageObject = (MessageObject) getItem(position);
cell.setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date, false);
break;
}
case 4: {
HashtagSearchCell cell = (HashtagSearchCell) holder.itemView;
cell.setText(searchResultHashtags.get(position - 1));
cell.setNeedDivider(position != searchResultHashtags.size());
break;
}
case 5: {
RecyclerListView recyclerListView = (RecyclerListView) holder.itemView;
((CategoryAdapterRecycler) recyclerListView.getAdapter()).setIndex(position / 2);
break;
}
case 6: {
String str = (String) getItem(position);
TextCell cell = (TextCell) holder.itemView;
cell.setColors(null, Theme.key_windowBackgroundWhiteBlueText2);
cell.setText(LocaleController.formatString("AddContactByPhone", R.string.AddContactByPhone, PhoneFormat.getInstance().format("+" + str)), false);
break;
}
}
}
@Override
public int getItemViewType(int i) {
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (i < offset) {
return 5;
}
if (i == offset) {
return 1;
}
return 0;
}
if (!searchResultHashtags.isEmpty()) {
return i == 0 ? 1 : 4;
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return 0;
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return 0;
} else {
i -= localServerCount;
if (i >= 0 && i < phoneCount) {
Object object = getItem(i);
if (object instanceof String) {
String str = (String) object;
if ("section".equals(str)) {
return 1;
} else {
return 6;
}
}
return 0;
} else {
i -= phoneCount;
if (i >= 0 && i < globalCount) {
if (i == 0) {
return 1;
} else {
return 0;
}
} else {
i -= globalCount;
if (i >= 0 && i < messagesCount) {
if (i == 0) {
return 1;
} else {
return 2;
}
}
}
}
}
}
return 3;
}
public void setFiltersDelegate(FilteredSearchView.Delegate filtersDelegate, boolean update) {
this.filtersDelegate = filtersDelegate;
if (filtersDelegate != null && update) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
}
}
| gpl-2.0 |
caronpe/dessinvectoriel | controler/ActionOutilTrait.java | 1809 | package controler;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.Observable;
import java.util.Observer;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
// INTERNE
import model.Model;
import ressources.URLIcons;
/**
* Listener pour le bouton trait.
*
* @author Alexandre Thorez
* @author Fabien Huitelec
* @author Pierre-Édouard Caron
*
* @version 0.4 finale
*/
public class ActionOutilTrait extends AbstractAction implements Observer {
private Model model;
private JButton bouton;
/**
* Ne comporte pas de nom, autrement
* l'affichage ne s'effectuerait pas correctement
*
* @param model Modèle du MVC
*/
public ActionOutilTrait(Model model, JButton bouton) {
this.model = model;
model.addObserver(this);
this.bouton = bouton;
// Values
this.putValue(SHORT_DESCRIPTION, "Sélectionne l'outil trait");
this.putValue(SMALL_ICON, new ImageIcon(URLIcons.CRAYON));
}
/**
* Sélectionne l'outil trait dans le modèle.
*/
public void actionPerformed(ActionEvent e) {
model.setObjetCourant("trait");
model.deselectionnerToutesLesFormes();
}
/**
* Crée des bordures lorsque cet outil est sélectionné dans le modèle.
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable arg0, Object arg1) {
if (model.getObjetCourant().equals("trait")) {
bouton.setBackground(new Color(220, 220, 220));
bouton.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.GRAY));
} else {
bouton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
bouton.setBackground(Color.WHITE);
}
}
} | gpl-2.0 |
EderRoger/design_pattern | test/src/command/RemoteCeilingFanTest.java | 1075 | package command;
import org.junit.Test;
/**
* Created by eder on 19/10/15.
*/
public class RemoteCeilingFanTest {
@Test
public void testRemoteControlCeilingFan(){
RemoteControl remoteControl = new RemoteControl();
CeilingFan ceilingFan = new CeilingFan("Living room");
CeilingFanHightCommand ceilingFanHightCommand = new CeilingFanHightCommand(ceilingFan);
CeilingFanMediumCommand ceilingFanMediumCommand = new CeilingFanMediumCommand(ceilingFan);
CeilingFanOffCommand ceilingFanOffCommand = new CeilingFanOffCommand(ceilingFan);
remoteControl.setCommand(0, ceilingFanHightCommand, ceilingFanOffCommand);
remoteControl.setCommand(1, ceilingFanMediumCommand, ceilingFanOffCommand);
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
remoteControl.onButtonWasPushed(1);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
}
}
| gpl-2.0 |
loverdos/javac-openjdk7 | src/main/java/openjdk7/com/sun/tools/javac/code/BoundKind.java | 1721 | /*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package openjdk7.com.sun.tools.javac.code;
/**
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public enum BoundKind {
EXTENDS("? extends "),
SUPER("? super "),
UNBOUND("?");
private final String name;
BoundKind(String name) {
this.name = name;
}
public String toString() { return name; }
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/fxch_ST0_ST2.java | 1856 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fxch_ST0_ST2 extends Executable
{
public fxch_ST0_ST2(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double tmp = cpu.fpu.ST(0);
cpu.fpu.setST(0, cpu.fpu.ST(2));
cpu.fpu.setST(2, tmp);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
colloquium/spacewalk | java/code/src/com/redhat/rhn/frontend/action/systems/monitoring/ProbesListSetupAction.java | 2226 | /**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.systems.monitoring;
import com.redhat.rhn.domain.server.Server;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnAction;
import com.redhat.rhn.frontend.taglibs.list.helper.ListHelper;
import com.redhat.rhn.frontend.taglibs.list.helper.Listable;
import com.redhat.rhn.manager.monitoring.MonitoringManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ProbesListSetupAction
* @version $Rev: 59372 $
*/
public class ProbesListSetupAction extends RhnAction implements Listable {
/**
*
* {@inheritDoc}
*/
public ActionForward execute(ActionMapping mapping,
ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) {
ListHelper helper = new ListHelper(this, request);
helper.execute();
RequestContext requestContext = new RequestContext(request);
Server server = requestContext.lookupAndBindServer();
request.setAttribute("sid", server.getId());
return mapping.findForward("default");
}
/**
*
* {@inheritDoc}
*/
public List getResult(RequestContext rctx) {
Server server = rctx.lookupAndBindServer();
return MonitoringManager.getInstance().
probesForSystem(rctx.getCurrentUser(), server, null);
}
}
| gpl-2.0 |
meijmOrg/Repo-test | freelance-hr-res/src/java/com/yh/hr/res/pt/queryhelper/PtReportHistoryQueryHelper.java | 1027 | package com.yh.hr.res.pt.queryhelper;
import com.yh.hr.res.pt.dto.PtReportHistoryDTO;
import com.yh.platform.core.dao.DaoUtil;
import com.yh.platform.core.exception.ServiceException;
import com.yh.platform.core.util.BeanHelper;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
/**
* 获取报表历史数据
*/
public class PtReportHistoryQueryHelper {
/**
* 查询报表历史
* @param taskOid
* @param reportType
* @return
* @throws ServiceException
*/
public static PtReportHistoryDTO getPtReportHistory(Long taskOid, String reportType) throws ServiceException {
final StringBuffer hBuffer = new StringBuffer("from PtReportHistory pt where 1 =1 ");
hBuffer.append(" and pt.taskOid =" + taskOid);
hBuffer.append(" and pt.reportType ='" + reportType+"'");
List<PtReportHistoryDTO> list = BeanHelper.copyProperties(DaoUtil.find(hBuffer.toString()), PtReportHistoryDTO.class);
if(CollectionUtils.isNotEmpty(list))
{
return list.get(0);
}
return null;
}
} | gpl-2.0 |
Decentrify/GVoD | hops/core/src/main/java/se/sics/nstream/hops/kafka/avro/AvroParser.java | 4973 | /*
* Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C)
* 2009 Royal Institute of Technology (KTH)
*
* KompicsToolbox is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package se.sics.nstream.hops.kafka.avro;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Alex Ormenisan <aaor@kth.se>
*/
public class AvroParser {
private static final Logger LOG = LoggerFactory.getLogger(AvroParser.class);
public static GenericRecord blobToAvro(Schema schema, ByteBuf data) {
int readPos = data.readerIndex();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
try (InputStream in = new ByteBufInputStream(data)) {
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
GenericRecord record = reader.read(null, decoder);
readPos = data.readerIndex() - decoder.inputStream().available();
data.readerIndex(readPos);
return record;
} catch (EOFException ex) {
data.readerIndex(readPos);
return null;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static List<GenericRecord> blobToAvroList(Schema schema, InputStream in) {
List<GenericRecord> records = new ArrayList<>();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
while (true) {
GenericRecord record = reader.read(null, decoder);
records.add(record);
}
} catch (EOFException ex) {
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return records;
}
public static byte[] avroToBlob(Schema schema, GenericRecord record) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
try {
writer.write(record, encoder);
encoder.flush();
} catch (Exception ex) {
throw new RuntimeException("hmmm", ex);
}
byte[] bData = out.toByteArray();
return bData;
}
public static byte[] nAvroToBlob(Schema schema, int nrMsgs, Random rand) {
ByteBuf buf = Unpooled.buffer();
OutputStream out = new ByteBufOutputStream(buf);
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
GenericRecordBuilder grb;
for (int i = 0; i < nrMsgs; i++) {
grb = new GenericRecordBuilder(schema);
for (Schema.Field field : schema.getFields()) {
//TODO Alex - I assume each field is a string
grb.set(field, "val" + (1000 + rand.nextInt(1000)));
}
try {
writer.write(grb.build(), encoder);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
try {
encoder.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
byte[] result = new byte[buf.writerIndex()];
buf.readBytes(result);
return result;
}
}
| gpl-2.0 |
kartoFlane/superluminal2 | src/java/com/kartoflane/superluminal2/ui/sidebar/data/ImageDataComposite.java | 3552 | package com.kartoflane.superluminal2.ui.sidebar.data;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.kartoflane.superluminal2.Superluminal;
import com.kartoflane.superluminal2.components.enums.Images;
import com.kartoflane.superluminal2.components.enums.OS;
import com.kartoflane.superluminal2.core.Cache;
import com.kartoflane.superluminal2.core.Manager;
import com.kartoflane.superluminal2.mvc.controllers.AbstractController;
import com.kartoflane.superluminal2.mvc.controllers.ImageController;
import com.kartoflane.superluminal2.utils.UIUtils;
import com.kartoflane.superluminal2.utils.Utils;
public class ImageDataComposite extends Composite implements DataComposite
{
private ImageController controller = null;
private Label label = null;
private Button btnFollowHull;
private Label lblFollowHelp;
public ImageDataComposite( Composite parent, ImageController control )
{
super( parent, SWT.NONE );
setLayout( new GridLayout( 2, false ) );
controller = control;
label = new Label( this, SWT.NONE );
label.setAlignment( SWT.CENTER );
label.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) );
String alias = control.getAlias();
label.setText( "Image" + ( alias == null ? "" : " (" + alias + ")" ) );
Label separator = new Label( this, SWT.SEPARATOR | SWT.HORIZONTAL );
separator.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) );
btnFollowHull = new Button( this, SWT.CHECK );
btnFollowHull.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, true, false, 1, 1 ) );
btnFollowHull.setText( "Follow Hull" );
lblFollowHelp = new Label( this, SWT.NONE );
lblFollowHelp.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false, false, 1, 1 ) );
lblFollowHelp.setImage( Cache.checkOutImage( this, "cpath:/assets/help.png" ) );
String msg = "When checked, this object will follow the hull image, so that " +
"when hull is moved, this object is moved as well.";
UIUtils.addTooltip( lblFollowHelp, Utils.wrapOSNot( msg, Superluminal.WRAP_WIDTH, Superluminal.WRAP_TOLERANCE, OS.MACOSX() ) );
btnFollowHull.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
if ( btnFollowHull.getSelection() ) {
controller.setParent( Manager.getCurrentShip().getImageController( Images.HULL ) );
}
else {
controller.setParent( Manager.getCurrentShip().getShipController() );
}
controller.updateFollowOffset();
}
}
);
updateData();
}
@Override
public void updateData()
{
String alias = controller.getAlias();
label.setText( "Image" + ( alias == null ? "" : " (" + alias + ")" ) );
ImageController hullController = Manager.getCurrentShip().getImageController( Images.HULL );
btnFollowHull.setVisible( controller != hullController );
btnFollowHull.setSelection( controller.getParent() == hullController );
lblFollowHelp.setVisible( controller != hullController );
}
@Override
public void setController( AbstractController controller )
{
this.controller = (ImageController)controller;
}
public void reloadController()
{
}
@Override
public void dispose()
{
Cache.checkInImage( this, "cpath:/assets/help.png" );
super.dispose();
}
}
| gpl-2.0 |
LeonardCohen/coding | IDDD_Samples-master/agilepm/src/test/java/com/saasovation/agilepm/application/product/ProductApplicationServiceTest.java | 8537 | // Copyright 2012,2013 Vaughn Vernon
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.saasovation.agilepm.application.product;
import java.util.UUID;
import com.saasovation.agilepm.application.ProductApplicationCommonTest;
import com.saasovation.agilepm.domain.model.discussion.DiscussionAvailability;
import com.saasovation.agilepm.domain.model.product.Product;
import com.saasovation.agilepm.domain.model.product.ProductId;
import com.saasovation.agilepm.domain.model.team.ProductOwner;
public class ProductApplicationServiceTest extends ProductApplicationCommonTest {
public ProductApplicationServiceTest() {
super();
}
public void testDiscussionProcess() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithStartedDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithStartedDiscussionInitiation.discussionInitiationId());
String discussionId = UUID.randomUUID().toString().toUpperCase();
InitiateDiscussionCommand command =
new InitiateDiscussionCommand(
product.tenantId().id(),
product.productId().id(),
discussionId);
this.productApplicationService.initiateDiscussion(command);
Product productWithInitiatedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(discussionId, productWithInitiatedDiscussion.discussion().descriptor().id());
}
public void testNewProduct() throws Exception {
ProductOwner productOwner = this.persistedProductOwnerForTest();
String newProductId =
this.productApplicationService.newProduct(
new NewProductCommand(
"T-12345",
productOwner.productOwnerId().id(),
"My Product",
"The description of My Product."));
Product newProduct =
this.productRepository
.productOfId(
productOwner.tenantId(),
new ProductId(newProductId));
assertNotNull(newProduct);
assertEquals("My Product", newProduct.name());
assertEquals("The description of My Product.", newProduct.description());
}
public void testNewProductWithDiscussion() throws Exception {
ProductOwner productOwner = this.persistedProductOwnerForTest();
String newProductId =
this.productApplicationService.newProductWithDiscussion(
new NewProductCommand(
"T-12345",
productOwner.productOwnerId().id(),
"My Product",
"The description of My Product."));
Product newProduct =
this.productRepository
.productOfId(
productOwner.tenantId(),
new ProductId(newProductId));
assertNotNull(newProduct);
assertEquals("My Product", newProduct.name());
assertEquals("The description of My Product.", newProduct.description());
assertEquals(DiscussionAvailability.REQUESTED, newProduct.discussion().availability());
}
public void testRequestProductDiscussion() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
}
public void testRetryProductDiscussionRequest() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithDiscussionInitiation.discussionInitiationId());
this.productApplicationService.retryProductDiscussionRequest(
new RetryProductDiscussionRequestCommand(
product.tenantId().id(),
productWithDiscussionInitiation.discussionInitiationId()));
Product productWithRetriedRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRetriedRequestedDiscussion.discussion().availability());
}
public void testStartDiscussionInitiation() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
assertNull(productWithRequestedDiscussion.discussionInitiationId());
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithDiscussionInitiation.discussionInitiationId());
}
public void testTimeOutProductDiscussionRequest() throws Exception {
// TODO: student assignment
}
}
| gpl-2.0 |
AlanGuerraQuispe/SisAtuxPerfumeria | atux-desktop/src/main/java/com/atux/desktop/promocion/PromocionPst.java | 7829 | package com.atux.desktop.promocion;
import com.atux.bean.precios.Local;
import com.atux.bean.precios.LocalFlt;
import com.atux.bean.promocion.Promocion;
import com.atux.bean.promocion.PromocionDetalle;
import com.atux.bean.promocion.PromocionLocal;
import com.atux.config.APDD;
import com.atux.desktop.comun.picks.SeleccionarLocalPst;
import com.atux.dominio.promocion.PromocionService;
import com.atux.service.qryMapper.ProveedorQryMapper;
import com.aw.core.report.ReportUtils;
import com.aw.stereotype.AWPresenter;
import com.aw.swing.mvp.Presenter;
import com.aw.swing.mvp.action.Action;
import com.aw.swing.mvp.action.ActionDialog;
import com.aw.swing.mvp.action.types.*;
import com.aw.swing.mvp.binding.component.support.ColumnInfo;
import com.aw.swing.mvp.grid.GridInfoProvider;
import com.aw.swing.mvp.grid.GridProvider;
import com.aw.swing.mvp.navigation.Flow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.swing.*;
import java.io.File;
import java.util.List;
/**
* Created by JAVA on 15/11/2014.
*/
@AWPresenter(title = "Proveedor - Precio")
public class PromocionPst extends Presenter<Promocion> {
protected final Log LOG = LogFactory.getLog(getClass());
private FrmPromocion vsr;
@Autowired
ProveedorQryMapper proveedorQryMapper;
@Autowired
PromocionService promocionService;
JFileChooser chooser = new JFileChooser();
GridProvider gdp;
GridProvider gdpLocal;
@Autowired
APDD apdd;
public PromocionPst() {
setBackBean(new Promocion());
setShowAuditInfo(false);
}
@Override
protected void registerBinding() {
bindingMgr.bind(vsr.txtCoPromocion, "coPromocion").setUIReadOnly(true);
bindingMgr.bind(vsr.txtNoPromocion, "noPromocion");
bindingMgr.bind(vsr.txtMensajeCorto, "mensajeCorto");
bindingMgr.bind(vsr.txtMensajeLargo, "mensajeLargo");
bindingMgr.bind(vsr.txtObservacion, "observacion");
bindingMgr.bind(vsr.txtFeIchanicio, "fechaInicio");
bindingMgr.bind(vsr.txtFechaFin, "fechaFin");
bindingMgr.bind(vsr.chkEstado, "esPromocion").registerTrueFalse("A", "I");
}
@Override
protected void registerGridProviders() {
gdp = gridProviderMgr.registerGridProvider(new IPDetalle());
gdpLocal = gridProviderMgr.registerGridProvider(new IPLocal());
}
private class IPDetalle extends GridInfoProvider<Promocion> {
public ColumnInfo[] getColumnInfo() {
ColumnInfo[] columns = new ColumnInfo[]{
new ColumnInfo("Código", "coProducto", 50, ColumnInfo.LEFT),
new ColumnInfo("Producto", "deProducto", 80, ColumnInfo.LEFT),
new ColumnInfo("Cant. Ent.", "caEntero", 30, ColumnInfo.RIGHT),
new ColumnInfo("Cant. Frac.", "caFraccion", 30, ColumnInfo.RIGHT),
new ColumnInfo("Prom. Código", "coProductoP", 50, ColumnInfo.LEFT),
new ColumnInfo("Prom. Producto", "deProductoP", 80, ColumnInfo.LEFT),
new ColumnInfo("Prom. Cant. Ent.", "caEnteroP", 30, ColumnInfo.RIGHT),
new ColumnInfo("Prom. Cant Frac.", "caFraccionP", 30, ColumnInfo.RIGHT),
new ColumnInfo("Estado", "esProductoPlan", 80, ColumnInfo.LEFT).setDropDownFormatter(apdd.ES_TABLA),
};
return columns;
}
public List<PromocionDetalle> getValues(Promocion precioLista) {
return precioLista.getDetalle();
}
}
private class IPLocal extends GridInfoProvider<Promocion> {
public ColumnInfo[] getColumnInfo() {
ColumnInfo[] columns = new ColumnInfo[]{
new ColumnInfo("Código", "coLocal", 50, ColumnInfo.LEFT),
new ColumnInfo("Local", "deLocal", 80, ColumnInfo.LEFT)
};
return columns;
}
public List<PromocionLocal> getValues(Promocion precioLista) {
return precioLista.getDetalleLocal();
}
}
@Override
protected void afterInitComponents() {
}
protected void registerActions() {
actionRsr.registerAction("Nuevo", new InsertAction(PromocionDetalle.class), gdp)
.notNeedVisualComponent()
.refreshGridAtEnd()
.noExecValidation()
.setKeyTrigger(ActionDialog.KEY_F2)
.setTargetPstClass(PromocionCrudPst.class);
actionRsr.registerAction("Delete", new DeleteItemAction() {
@Override
protected Object executeIntern() throws Throwable {
getBackBean().getDetalle().remove(gdp.getSelectedRow());
return null;
}
}, gdp)
.notNeedVisualComponent()
.needSelectedRow()
.refreshGridAtEnd()
.setKeyTrigger(ActionDialog.KEY_F4)
;
actionRsr.registerAction("DeleteLocal", new DeleteItemAction() {
@Override
protected Object executeIntern() throws Throwable {
getBackBean().getDetalleLocal().remove(gdpLocal.getSelectedRow());
return null;
}
}, gdpLocal)
.notNeedVisualComponent()
.needSelectedRow()
.refreshGridAtEnd()
.setKeyTrigger(ActionDialog.KEY_F4)
;
actionRsr.registerAction("Guardar", new Action() {
@Override
protected Object executeIntern() throws Throwable {
promocionService.grabar(getBackBean());
return null;
}
}).notNeedVisualComponent()
.setKeyTrigger(ActionDialog.KEY_F10)
.closeViewAtEnd();
actionRsr.registerAction("Seleccionar", new ShowPstAction(LocalFlt.class){
@Override
public Object executeOnReturn(Flow initialFlow, Flow endFlow) {
// endFlow.getAttribute(Flow.BACK_BEAN_NAME);
List<Local> localList= (List<Local>) endFlow.getAttribute("selectedRows");
for (Local local : localList) {
PromocionLocal promocionLocal=new PromocionLocal();
promocionLocal.setCoLocal(local.getCoLocal());
promocionLocal.setDeLocal(local.getDeLocal());
getBackBean().getDetalleLocal().add(promocionLocal);
}
return super.executeOnReturn(initialFlow, endFlow);
}
}, gdpLocal)
.refreshGridAtEnd()
.notNeedVisualComponent()
.noExecValidation()
.setKeyTrigger(ActionDialog.KEY_F6)
.setTargetPstClass(SeleccionarLocalPst.class)
;
}
public void descargarAction() {
try {
ReportUtils.showReport(new File(getClass().getResource("/plantilla_precio_proveedor.xls").toURI()).getAbsolutePath());
} catch (Throwable e) {
logger.error("Error ", e);
}
}
public void examinarAction() {
int returnVal = chooser.showOpenDialog(vsr.pnlMain);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
//This is where a real application would open the file.
logger.info("Opening: " + file.getName() + "." + "\n");
} else {
logger.info("Open command cancelled by user." + "\n");
}
}
}
| gpl-2.0 |
bugdetector/Gezi-Yorum | app/src/main/java/com/example/murat/gezi_yorum/Fragments/Notifications.java | 5164 | package com.example.murat.gezi_yorum.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.murat.gezi_yorum.Entity.Constants;
import com.example.murat.gezi_yorum.Entity.User;
import com.example.murat.gezi_yorum.R;
import com.example.murat.gezi_yorum.Utils.NotificationsAdapter;
import com.example.murat.gezi_yorum.Utils.URLRequestHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Shows notification
*/
public class Notifications extends Fragment {
private ListView trip_invitation_notifications;
private ListView friendship_requests;
private Handler handler;
private JSONArray trip_invitation_notificationsList;
private JSONArray friendship_requestsList;
private User user;
private Boolean isPaused;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle(getString(R.string.notification));
trip_invitation_notifications = view.findViewById(R.id.notifications);
friendship_requests = view.findViewById(R.id.friend_notifications);
handler = new Handler();
user = new User(getContext().getSharedPreferences(Constants.PREFNAME, Context.MODE_PRIVATE));
new Thread(new Runnable() {
@Override
public void run() {
JSONObject request = new JSONObject();
try {
request.put("token", user.token);
request.put("username", user.username);
String url = Constants.APP + "checkTripRequest";
URLRequestHandler urlhandler = new URLRequestHandler(request.toString(), url);
if(urlhandler.getResponseMessage()){
String notitificationsResponse = urlhandler.getResponse();
trip_invitation_notificationsList = new JSONArray(notitificationsResponse);
}
url = Constants.APP + "getFriendRequests";
urlhandler = new URLRequestHandler(request.toString(), url);
if(urlhandler.getResponseMessage()){
String notitificationsResponse = urlhandler.getResponse();
friendship_requestsList = new JSONArray(notitificationsResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
if(!isPaused)
loadAdapter();
}
});
}
}).start();
}
@Override
public void onResume() {
super.onResume();
isPaused = false;
}
@Override
public void onPause() {
super.onPause();
isPaused = true;
}
public void loadAdapter(){
if(trip_invitation_notificationsList != null && trip_invitation_notificationsList.length() > 0) {
trip_invitation_notifications.setAdapter(
new NotificationsAdapter(getContext(), trip_invitation_notificationsList, NotificationsAdapter.TRIP, this)
);
}else {
getView().findViewById(R.id.trip_not_text).setVisibility(View.GONE);
}
if(friendship_requestsList != null && friendship_requestsList.length() > 0) {
friendship_requests.setAdapter(
new NotificationsAdapter(getContext(), friendship_requestsList, NotificationsAdapter.FRIENDSHIP,this)
);
}else {
getView().findViewById(R.id.friend_not_text).setVisibility(View.GONE);
}
if((trip_invitation_notificationsList == null || trip_invitation_notificationsList.length() == 0)
&& (friendship_requestsList == null || friendship_requestsList.length() == 0)) {
getActivity().findViewById(R.id.nothing).setVisibility(View.VISIBLE);
}
}
public void acceptOrDenyFriendRequest(int i){
friendship_requestsList.remove(i);
friendship_requests.setAdapter(
new NotificationsAdapter(getContext(), friendship_requestsList, NotificationsAdapter.FRIENDSHIP,this)
);
}
public void denyTripRequest(int i){
trip_invitation_notificationsList.remove(i);
trip_invitation_notifications.setAdapter(
new NotificationsAdapter(getContext(), trip_invitation_notificationsList, NotificationsAdapter.TRIP,this)
);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.notifications_fragment, container,false);
}
}
| gpl-2.0 |
esutoniagodesu/egd-web | src/main/java/ee/esutoniagodesu/domain/jmet/table/Kwginf.java | 1728 | package ee.esutoniagodesu.domain.jmet.table;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Immutable
@Table(name = "kwginf", schema = "jmet")
public final class Kwginf implements Serializable {
private static final long serialVersionUID = 4247060263515704962L;
private short id;
private String kw;
private String descr;
@Basic
@Column(name = "descr", nullable = true, insertable = true, updatable = true, length = 255)
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
@Id
@Column(name = "id", nullable = false, insertable = true, updatable = true)
public short getId() {
return id;
}
public void setId(short id) {
this.id = id;
}
@Basic
@Column(name = "kw", nullable = false, insertable = true, updatable = true, length = 20)
public String getKw() {
return kw;
}
public void setKw(String kw) {
this.kw = kw;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Kwginf kwginf = (Kwginf) o;
if (id != kwginf.id) return false;
if (descr != null ? !descr.equals(kwginf.descr) : kwginf.descr != null) return false;
if (kw != null ? !kw.equals(kwginf.kw) : kwginf.kw != null) return false;
return true;
}
public int hashCode() {
int result = (int) id;
result = 31 * result + (kw != null ? kw.hashCode() : 0);
result = 31 * result + (descr != null ? descr.hashCode() : 0);
return result;
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/com/sun/imageio/stream/CloseableDisposerRecord.java | 1969 | /*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.imageio.stream;
import java.io.Closeable;
import java.io.IOException;
import sun.java2d.DisposerRecord;
/**
* Convenience class that closes a given resource (e.g. RandomAccessFile),
* typically associated with an Image{Input,Output}Stream, prior to the
* stream being garbage collected.
*/
public class CloseableDisposerRecord implements DisposerRecord {
private Closeable closeable;
public CloseableDisposerRecord(Closeable closeable) {
this.closeable = closeable;
}
public synchronized void dispose() {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
} finally {
closeable = null;
}
}
}
}
| gpl-2.0 |
jmccrae/naisc | word-align/src/main/java/org/insightcentre/unlp/naisc/wordalign/WordAlignmentFeatureExtractorFactory.java | 560 | package org.insightcentre.unlp.naisc.wordalign;
import java.util.Map;
/**
* A factory for making word alignment feature extractors
*
* @author John McCrae <john@mccr.ae>
*/
public interface WordAlignmentFeatureExtractorFactory {
/**
* An identifier for this WAFE
* @return The identifier
*/
String id();
/**
* Creata a new word alignment feature extractor
* @param params The parameters of the configuration file
* @return The WAFE
*/
WordAlignmentFeatureExtractor make(Map<String, Object> params);
}
| gpl-2.0 |
aleister09/android | src/main/java/com/owncloud/android/ui/adapter/FileListListAdapter.java | 25342 | /**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author Tobias Kaminsky
* @author David A. Velasco
* @author masensio
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2016 ownCloud Inc.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter;
import android.accounts.Account;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.db.PreferenceManager;
import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.RemoteFile;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
import com.owncloud.android.ui.activity.ComponentsGetter;
import com.owncloud.android.ui.fragment.ExtendedListFragment;
import com.owncloud.android.ui.interfaces.OCFileListFragmentInterface;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeTypeUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Vector;
/**
* This Adapter populates a ListView with all files and folders in an ownCloud
* instance.
*/
public class FileListListAdapter extends BaseAdapter {
private Context mContext;
private Vector<OCFile> mFilesAll = new Vector<OCFile>();
private Vector<OCFile> mFiles = null;
private boolean mJustFolders;
private boolean mShowHiddenFiles;
private FileDataStorageManager mStorageManager;
private Account mAccount;
private ComponentsGetter mTransferServiceGetter;
private OCFileListFragmentInterface OCFileListFragmentInterface;
private FilesFilter mFilesFilter;
private OCFile currentDirectory;
private static final String TAG = FileListListAdapter.class.getSimpleName();
public FileListListAdapter(
boolean justFolders,
Context context,
ComponentsGetter transferServiceGetter,
OCFileListFragmentInterface OCFileListFragmentInterface
) {
this.OCFileListFragmentInterface = OCFileListFragmentInterface;
mJustFolders = justFolders;
mContext = context;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
mTransferServiceGetter = transferServiceGetter;
// Read sorting order, default to sort by name ascending
FileStorageUtils.mSortOrder = PreferenceManager.getSortOrder(mContext);
FileStorageUtils.mSortAscending = PreferenceManager.getSortAscending(mContext);
// Fetch preferences for showing hidden files
mShowHiddenFiles = PreferenceManager.showHiddenFilesEnabled(mContext);
// initialise thumbnails cache on background thread
new ThumbnailsCacheManager.InitDiskCacheTask().execute();
}
public FileListListAdapter(
boolean justFolders,
Context context,
ComponentsGetter transferServiceGetter,
OCFileListFragmentInterface OCFileListFragmentInterface,
FileDataStorageManager fileDataStorageManager
) {
this(justFolders, context, transferServiceGetter, OCFileListFragmentInterface);
mStorageManager = fileDataStorageManager;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public int getCount() {
return mFiles != null ? mFiles.size() : 0;
}
@Override
public Object getItem(int position) {
if (mFiles == null || mFiles.size() <= position) {
return null;
}
return mFiles.get(position);
}
public void setFavoriteAttributeForItemID(String fileId, boolean favorite) {
for (int i = 0; i < mFiles.size(); i++) {
if (mFiles.get(i).getRemoteId().equals(fileId)) {
mFiles.get(i).setFavorite(favorite);
break;
}
}
for (int i = 0; i < mFilesAll.size(); i++) {
if (mFilesAll.get(i).getRemoteId().equals(fileId)) {
mFilesAll.get(i).setFavorite(favorite);
break;
}
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
@Override
public long getItemId(int position) {
if (mFiles == null || mFiles.size() <= position) {
return 0;
}
return mFiles.get(position).getFileId();
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
OCFile file = null;
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (mFiles != null && mFiles.size() > position) {
file = mFiles.get(position);
}
// Find out which layout should be displayed
ViewType viewType;
if (parent instanceof GridView) {
if (file != null && (MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file))) {
viewType = ViewType.GRID_IMAGE;
} else {
viewType = ViewType.GRID_ITEM;
}
} else {
viewType = ViewType.LIST_ITEM;
}
// create view only if differs, otherwise reuse
if (convertView == null || convertView.getTag() != viewType) {
switch (viewType) {
case GRID_IMAGE:
view = inflator.inflate(R.layout.grid_image, parent, false);
view.setTag(ViewType.GRID_IMAGE);
break;
case GRID_ITEM:
view = inflator.inflate(R.layout.grid_item, parent, false);
view.setTag(ViewType.GRID_ITEM);
break;
case LIST_ITEM:
view = inflator.inflate(R.layout.list_item, parent, false);
view.setTag(ViewType.LIST_ITEM);
break;
}
}
if (file != null) {
ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);
fileIcon.setTag(file.getFileId());
TextView fileName;
String name = file.getFileName();
switch (viewType) {
case LIST_ITEM:
TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
TextView fileSizeSeparatorV = (TextView) view.findViewById(R.id.file_separator);
TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
lastModV.setVisibility(View.VISIBLE);
lastModV.setText(DisplayUtils.getRelativeTimestamp(mContext, file.getModificationTimestamp()));
fileSizeSeparatorV.setVisibility(View.VISIBLE);
fileSizeV.setVisibility(View.VISIBLE);
fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
case GRID_ITEM:
// filename
fileName = (TextView) view.findViewById(R.id.Filename);
name = file.getFileName();
fileName.setText(name);
case GRID_IMAGE:
// sharedIcon
ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
if (file.isSharedViaLink()) {
sharedIconV.setImageResource(R.drawable.shared_via_link);
sharedIconV.setVisibility(View.VISIBLE);
sharedIconV.bringToFront();
} else if (file.isSharedWithSharee() || file.isSharedWithMe()) {
sharedIconV.setImageResource(R.drawable.shared_via_users);
sharedIconV.setVisibility(View.VISIBLE);
sharedIconV.bringToFront();
} else {
sharedIconV.setVisibility(View.GONE);
}
// local state
ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
localStateView.bringToFront();
FileDownloaderBinder downloaderBinder =
mTransferServiceGetter.getFileDownloaderBinder();
FileUploaderBinder uploaderBinder =
mTransferServiceGetter.getFileUploaderBinder();
OperationsServiceBinder opsBinder =
mTransferServiceGetter.getOperationsServiceBinder();
localStateView.setVisibility(View.INVISIBLE); // default first
if ( //synchronizing
opsBinder != null &&
opsBinder.isSynchronizing(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if ( // downloading
downloaderBinder != null &&
downloaderBinder.isDownloading(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if ( //uploading
uploaderBinder != null &&
uploaderBinder.isUploading(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if (file.getEtagInConflict() != null) { // conflict
localStateView.setImageResource(R.drawable.ic_synchronizing_error);
localStateView.setVisibility(View.VISIBLE);
} else if (file.isDown()) {
localStateView.setImageResource(R.drawable.ic_synced);
localStateView.setVisibility(View.VISIBLE);
}
break;
}
// For all Views
if (file.getIsFavorite()) {
view.findViewById(R.id.favorite_action).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.favorite_action).setVisibility(View.GONE);
}
ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
checkBoxV.setVisibility(View.GONE);
view.setBackgroundColor(Color.WHITE);
AbsListView parentList = (AbsListView) parent;
if (parentList.getChoiceMode() != AbsListView.CHOICE_MODE_NONE &&
parentList.getCheckedItemCount() > 0
) {
if (parentList.isItemChecked(position)) {
view.setBackgroundColor(mContext.getResources().getColor(
R.color.selected_item_background));
checkBoxV.setImageResource(
R.drawable.ic_checkbox_marked);
} else {
view.setBackgroundColor(Color.WHITE);
checkBoxV.setImageResource(
R.drawable.ic_checkbox_blank_outline);
}
checkBoxV.setVisibility(View.VISIBLE);
}
// this if-else is needed even though kept-in-sync icon is visible by default
// because android reuses views in listview
if (!file.isAvailableOffline()) {
view.findViewById(R.id.keptOfflineIcon).setVisibility(View.GONE);
} else {
view.findViewById(R.id.keptOfflineIcon).setVisibility(View.VISIBLE);
}
// No Folder
if (!file.isFolder()) {
if ((MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file)) && file.getRemoteId() != null) {
// Thumbnail in Cache?
Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(file.getRemoteId());
if (thumbnail != null && !file.needsUpdateThumbnail()) {
if (MimeTypeUtil.isVideo(file)) {
Bitmap withOverlay = ThumbnailsCacheManager.addVideoOverlay(thumbnail);
fileIcon.setImageBitmap(withOverlay);
} else {
fileIcon.setImageBitmap(thumbnail);
}
} else {
// generate new Thumbnail
if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, fileIcon)) {
try {
final ThumbnailsCacheManager.ThumbnailGenerationTask task =
new ThumbnailsCacheManager.ThumbnailGenerationTask(
fileIcon, mStorageManager, mAccount
);
if (thumbnail == null) {
if (MimeTypeUtil.isVideo(file)) {
thumbnail = ThumbnailsCacheManager.mDefaultVideo;
} else {
thumbnail = ThumbnailsCacheManager.mDefaultImg;
}
}
final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable =
new ThumbnailsCacheManager.AsyncThumbnailDrawable(
mContext.getResources(),
thumbnail,
task
);
fileIcon.setImageDrawable(asyncDrawable);
task.execute(file);
} catch (IllegalArgumentException e) {
Log_OC.d(TAG, "ThumbnailGenerationTask : " + e.getMessage());
}
}
}
if (file.getMimetype().equalsIgnoreCase("image/png")) {
fileIcon.setBackgroundColor(mContext.getResources()
.getColor(R.color.background_color));
}
} else {
fileIcon.setImageResource(MimeTypeUtil.getFileTypeIconId(file.getMimetype(),
file.getFileName()));
}
} else {
// Folder
fileIcon.setImageResource(
MimeTypeUtil.getFolderTypeIconId(
file.isSharedWithMe() || file.isSharedWithSharee(),
file.isSharedViaLink()
)
);
}
}
return view;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return (mFiles == null || mFiles.isEmpty());
}
/**
* Change the adapted directory for a new one
*
* @param directory New folder to adapt. Can be NULL, meaning
* "no content to adapt".
* @param updatedStorageManager Optional updated storage manager; used to replace
* mStorageManager if is different (and not NULL)
*/
public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager
, boolean onlyOnDevice) {
if (updatedStorageManager != null && !updatedStorageManager.equals(mStorageManager)) {
mStorageManager = updatedStorageManager;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
}
if (mStorageManager != null) {
mFiles = mStorageManager.getFolderContent(directory, onlyOnDevice);
if (mJustFolders) {
mFiles = getFolders(mFiles);
}
if (!mShowHiddenFiles) {
mFiles = filterHiddenFiles(mFiles);
}
mFiles = FileStorageUtils.sortOcFolder(mFiles);
mFilesAll.clear();
mFilesAll.addAll(mFiles);
currentDirectory = directory;
} else {
mFiles = null;
mFilesAll.clear();
}
notifyDataSetChanged();
}
private void searchForLocalFileInDefaultPath(OCFile file) {
if (file.getStoragePath() == null && !file.isFolder()) {
File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
if (f.exists()) {
file.setStoragePath(f.getAbsolutePath());
file.setLastSyncDateForData(f.lastModified());
}
}
}
public void setData(ArrayList<Object> objects, ExtendedListFragment.SearchType searchType) {
mFiles = new Vector<>();
if (searchType.equals(ExtendedListFragment.SearchType.SHARED_FILTER)) {
ArrayList<OCShare> shares = new ArrayList<>();
for (int i = 0; i < objects.size(); i++) {
// check type before cast as of long running data fetch it is possible that old result is filled
if (objects.get(i) instanceof OCShare) {
OCShare ocShare = (OCShare) objects.get(i);
shares.add(ocShare);
OCFile ocFile = mStorageManager.getFileByPath(ocShare.getPath());
if (!mFiles.contains(ocFile)) {
mFiles.add(ocFile);
}
}
}
mStorageManager.saveShares(shares);
} else {
for (int i = 0; i < objects.size(); i++) {
OCFile ocFile = FileStorageUtils.fillOCFile((RemoteFile) objects.get(i));
searchForLocalFileInDefaultPath(ocFile);
mFiles.add(ocFile);
}
}
if (!searchType.equals(ExtendedListFragment.SearchType.PHOTO_SEARCH) &&
!searchType.equals(ExtendedListFragment.SearchType.PHOTOS_SEARCH_FILTER) &&
!searchType.equals(ExtendedListFragment.SearchType.RECENTLY_MODIFIED_SEARCH) &&
!searchType.equals(ExtendedListFragment.SearchType.RECENTLY_MODIFIED_SEARCH_FILTER)) {
mFiles = FileStorageUtils.sortOcFolder(mFiles);
} else {
mFiles = FileStorageUtils.sortOcFolderDescDateModified(mFiles);
}
mFilesAll = new Vector<>();
mFilesAll.addAll(mFiles);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
OCFileListFragmentInterface.finishedFiltering();
}
});
}
/**
* Filter for getting only the folders
*
* @param files Collection of files to filter
* @return Folders in the input
*/
public Vector<OCFile> getFolders(Vector<OCFile> files) {
Vector<OCFile> ret = new Vector<>();
OCFile current;
for (int i = 0; i < files.size(); i++) {
current = files.get(i);
if (current.isFolder()) {
ret.add(current);
}
}
return ret;
}
public void setSortOrder(Integer order, boolean ascending) {
PreferenceManager.setSortOrder(mContext, order);
PreferenceManager.setSortAscending(mContext, ascending);
FileStorageUtils.mSortOrder = order;
FileStorageUtils.mSortAscending = ascending;
mFiles = FileStorageUtils.sortOcFolder(mFiles);
notifyDataSetChanged();
}
public ArrayList<OCFile> getCheckedItems(AbsListView parentList) {
SparseBooleanArray checkedPositions = parentList.getCheckedItemPositions();
ArrayList<OCFile> files = new ArrayList<>();
Object item;
for (int i = 0; i < checkedPositions.size(); i++) {
if (checkedPositions.valueAt(i)) {
item = getItem(checkedPositions.keyAt(i));
if (item != null) {
files.add((OCFile) item);
}
}
}
return files;
}
public Filter getFilter() {
if (mFilesFilter == null) {
mFilesFilter = new FilesFilter();
}
return mFilesFilter;
}
private class FilesFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
Vector<OCFile> filteredFiles = new Vector<>();
if (!TextUtils.isEmpty(constraint)) {
for (int i = 0; i < mFilesAll.size(); i++) {
OCFile currentFile = mFilesAll.get(i);
if (currentFile.getParentRemotePath().equals(currentDirectory.getRemotePath()) &&
currentFile.getFileName().toLowerCase().contains(constraint.toString().toLowerCase()) &&
!filteredFiles.contains(currentFile)) {
filteredFiles.add(currentFile);
}
}
}
results.values = filteredFiles;
results.count = filteredFiles.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
Vector<OCFile> ocFiles = (Vector<OCFile>) results.values;
mFiles = new Vector<>();
if (ocFiles != null && ocFiles.size() > 0) {
mFiles.addAll(ocFiles);
if (!mShowHiddenFiles) {
mFiles = filterHiddenFiles(mFiles);
}
mFiles = FileStorageUtils.sortOcFolder(mFiles);
}
notifyDataSetChanged();
OCFileListFragmentInterface.finishedFiltering();
}
}
/**
* Filter for hidden files
*
* @param files Collection of files to filter
* @return Non-hidden files
*/
public Vector<OCFile> filterHiddenFiles(Vector<OCFile> files) {
Vector<OCFile> ret = new Vector<>();
OCFile current;
for (int i = 0; i < files.size(); i++) {
current = files.get(i);
if (!current.isHidden() && !ret.contains(current)) {
ret.add(current);
}
}
return ret;
}
}
| gpl-2.0 |
Distrotech/jhylafax | src/java/net/sf/jhylafax/PollDialog.java | 2766 | /**
* JHylaFax - A java client for HylaFAX.
*
* Copyright (C) 2005 by Steffen Pingel <steffenp@gmx.de>
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.sf.jhylafax;
import static net.sf.jhylafax.JHylaFAX.i18n;
import gnu.hylafax.HylaFAXClient;
import javax.swing.JFrame;
import net.sf.jhylafax.fax.FaxJob;
import net.sf.jhylafax.fax.HylaFAXClientHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xnap.commons.gui.ErrorDialog;
import org.xnap.commons.io.Job;
import org.xnap.commons.io.ProgressMonitor;
import org.xnap.commons.io.UserAbortException;
/**
* A dialog for polling of faxes.
*
* @author Steffen Pingel
*/
public class PollDialog extends AbstractFaxDialog {
private final static Log logger = LogFactory.getLog(PollDialog.class);
public PollDialog(JFrame owner) {
super(owner);
addNumberTextField();
addDateControls();
FaxJob job = new FaxJob();
HylaFAXClientHelper.initializeFromSettings(job);
setJob(job);
updateLabels();
pack();
}
@Override
public boolean apply() {
if (!super.apply()) {
return false;
}
Job<?> ioJob = new Job() {
public Object run(ProgressMonitor monitor) throws Exception
{
monitor.setTotalSteps(4);
HylaFAXClient client = JHylaFAX.getInstance().getConnection(monitor);
monitor.work(1);
gnu.hylafax.Job pollJob = client.createJob();
HylaFAXClientHelper.applyParameter(pollJob, getJob());
pollJob.setProperty("POLL", "\"\" \"\"");
monitor.work(1);
client.submit(pollJob);
monitor.work(2);
return null;
}
};
try {
JHylaFAX.getInstance().runJob(PollDialog.this, ioJob);
JHylaFAX.getInstance().updateTables();
}
catch (UserAbortException e) {
return false;
}
catch (Exception e) {
logger.debug("Error polling fax", e);
ErrorDialog.showError(this, i18n.tr("Could not poll fax"),
i18n.tr("JHylaFAX Error"),
e);
return false;
}
return true;
}
public void updateLabels() {
super.updateLabels();
setTitle(i18n.tr("Poll Fax"));
}
}
| gpl-2.0 |
mio-to/airnoise | airnoise/dao/src/main/java/com/airnoise/services/DataBaseManagementService.java | 947 | /**
*
*/
package com.airnoise.services;
import java.sql.SQLException;
import com.airnoise.core.exception.PersistenceException;
import com.airnoise.dao.DataBaseManager;
/**
* @author tomio
*
*/
public class DataBaseManagementService {
private DataBaseManager manager;
public DataBaseManagementService(DataBaseManager manager) {
this.manager = manager;
}
public void createDB() throws PersistenceException {
try {
this.manager.getDataBaseManagementDAO().createDB();
} catch (SQLException e) {
throw new PersistenceException("Error creating database", e);
}
}
public void reinitializeDB() throws PersistenceException {
try {
this.manager.getDataBaseManagementDAO().reinitializeDB();
} catch (SQLException e) {
throw new PersistenceException("Error reinitializing the database", e);
}
}
}
| gpl-2.0 |
thangbn/Direct-File-Downloader | src/src/com/aelitis/azureus/core/peermanager/messaging/MessageStreamDecoder.java | 2758 | /*
* Created on Jan 25, 2005
* Created by Alon Rohter
* Copyright (C) 2004-2005 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.azureus.core.peermanager.messaging;
import com.aelitis.azureus.core.networkmanager.Transport;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Decodes a message stream into separate messages.
*/
public interface MessageStreamDecoder {
/**
* Decode message stream from the given transport.
* @param transport to decode from
* @param max_bytes to decode/read from the stream
* @return number of bytes decoded
* @throws IOException on decoding error
*/
public int performStreamDecode( Transport transport, int max_bytes ) throws IOException;
/**
* Get the messages decoded from the transport, if any, from the last decode op.
* @return decoded messages, or null if no new complete messages were decoded
*/
public Message[] removeDecodedMessages();
/**
* Get the number of protocol (overhead) bytes decoded from the transport, from the last decode op.
* @return number of protocol bytes recevied
*/
public int getProtocolBytesDecoded();
/**
* Get the number of (piece) data bytes decoded from the transport, from the last decode op.
* @return number of data bytes received
*/
public int getDataBytesDecoded();
/**
* Get the percentage of the current message that has already been received (read from the transport).
* @return percentage complete (0-99), or -1 if no message is currently being received
*/
public int getPercentDoneOfCurrentMessage();
/**
* Pause message decoding.
*/
public void pauseDecoding();
/**
* Resume message decoding.
*/
public void resumeDecoding();
/**
* Destroy this decoder, i.e. perform cleanup.
* @return any bytes already-read and still remaining within the decoder
*/
public ByteBuffer destroy();
}
| gpl-2.0 |
ia-toki/judgels-michael | app/org/iatoki/judgels/michael/controllers/MachineWatcherController.java | 13764 | package org.iatoki.judgels.michael.controllers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.EnumUtils;
import org.iatoki.judgels.play.InternalLink;
import org.iatoki.judgels.play.LazyHtml;
import org.iatoki.judgels.play.controllers.AbstractJudgelsController;
import org.iatoki.judgels.play.views.html.layouts.headingLayout;
import org.iatoki.judgels.play.views.html.layouts.headingWithActionLayout;
import org.iatoki.judgels.play.views.html.layouts.tabLayout;
import org.iatoki.judgels.michael.Machine;
import org.iatoki.judgels.michael.MachineNotFoundException;
import org.iatoki.judgels.michael.services.MachineService;
import org.iatoki.judgels.michael.MachineWatcher;
import org.iatoki.judgels.michael.adapters.MachineWatcherConfAdapter;
import org.iatoki.judgels.michael.MachineWatcherNotFoundException;
import org.iatoki.judgels.michael.services.MachineWatcherService;
import org.iatoki.judgels.michael.MachineWatcherType;
import org.iatoki.judgels.michael.MachineWatcherUtils;
import org.iatoki.judgels.michael.controllers.securities.LoggedIn;
import org.iatoki.judgels.michael.views.html.machine.watcher.listMachineWatchersView;
import play.data.Form;
import play.db.jpa.Transactional;
import play.filters.csrf.AddCSRFToken;
import play.filters.csrf.RequireCSRFCheck;
import play.i18n.Messages;
import play.mvc.Result;
import play.mvc.Security;
import play.twirl.api.Html;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.List;
@Security.Authenticated(value = LoggedIn.class)
@Singleton
@Named
public final class MachineWatcherController extends AbstractJudgelsController {
private final MachineService machineService;
private final MachineWatcherService machineWatcherService;
@Inject
public MachineWatcherController(MachineService machineService, MachineWatcherService machineWatcherService) {
this.machineService = machineService;
this.machineWatcherService = machineWatcherService;
}
@Transactional(readOnly = true)
public Result viewMachineWatchers(long machineId) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
List<MachineWatcherType> enabledWatchers = machineWatcherService.findEnabledWatcherByMachineJid(machine.getJid());
List<MachineWatcherType> unenabledWatchers = Lists.newArrayList(MachineWatcherType.values());
unenabledWatchers.removeAll(enabledWatchers);
LazyHtml content = new LazyHtml(listMachineWatchersView.render(machine.getId(), enabledWatchers, unenabledWatchers));
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.list"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result activateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postActivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
String conf = adapter.processRequestForm(form);
machineWatcherService.createWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result updateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
MachineWatcher machineWatcher = machineWatcherService.findByMachineJidAndWatcherType(machine.getJid(), MachineWatcherType.valueOf(watcherType));
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(machineWatcher.getConf()), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postUpdateMachineWatcher(machine.getId(), machineWatcher.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postUpdateMachineWatcher(long machineId, long machineWatcherId, String watcherType) throws MachineNotFoundException, MachineWatcherNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
MachineWatcher machineWatcher = machineWatcherService.findByWatcherId(machineWatcherId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
if (machine.getJid().equals(machineWatcher.getMachineJid())) {
String conf = adapter.processRequestForm(form);
machineWatcherService.updateWatcher(machineWatcher.getId(), machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
form.reject("error.notMachineWatcher");
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
}
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
public Result deactivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
machineWatcherService.removeWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType));
}
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
throw new UnsupportedOperationException();
}
}
private Result showActivateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.activate"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.activate"), routes.MachineWatcherController.activateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private Result showUpdateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.update"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.update"), routes.MachineWatcherController.updateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private void appendTabLayout(LazyHtml content, Machine machine) {
content.appendLayout(c -> tabLayout.render(ImmutableList.of(
new InternalLink(Messages.get("machine.update"), routes.MachineController.updateMachineGeneral(machine.getId())),
new InternalLink(Messages.get("machine.access"), routes.MachineAccessController.viewMachineAccesses(machine.getId())),
new InternalLink(Messages.get("machine.watcher"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
), c));
content.appendLayout(c -> headingWithActionLayout.render(Messages.get("machine.machine") + " #" + machine.getId() + ": " + machine.getDisplayName(), new InternalLink(Messages.get("commons.enter"), routes.MachineController.viewMachine(machine.getId())), c));
}
}
| gpl-2.0 |
NorthFacing/step-by-Java | java-base/sourceCodeBak/Thinking in Java/generics/FactoryConstraint.java | 638 | //: generics/FactoryConstraint.java
interface FactoryI<T> {
T create();
}
class Foo2<T> {
private T x;
public <F extends FactoryI<T>> Foo2(F factory) {
x = factory.create();
}
// ...
}
class IntegerFactory implements FactoryI<Integer> {
public Integer create() {
return new Integer(0);
}
}
class Widget {
public static class Factory implements FactoryI<Widget> {
public Widget create() {
return new Widget();
}
}
}
public class FactoryConstraint {
public static void main(String[] args) {
new Foo2<Integer>(new IntegerFactory());
new Foo2<Widget>(new Widget.Factory());
}
} ///:~
| gpl-2.0 |
software-jessies-org/scm | src/e/scm/AnnotatedLineRenderer.java | 1792 | package e.scm;
import java.awt.*;
import javax.swing.*;
public class AnnotatedLineRenderer extends e.gui.EListCellRenderer<AnnotatedLine> {
/** Used to draw the dashed line between adjacent lines from different revisions. */
private static final Stroke DASHED_STROKE = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, new float[] { 2.0f, 3.0f }, 0.0f);
/** The RevisionView we're rendering for. */
private RevisionView revisionView;
/** Whether or not we should draw a dashed line above this row. */
private boolean shouldDrawLine;
public AnnotatedLineRenderer(RevisionView parentRevisionView) {
super(false);
this.revisionView = parentRevisionView;
}
@Override public void doCustomization(JList<AnnotatedLine> list, AnnotatedLine line, int row, boolean isSelected, boolean isFocused) {
// Find out if this line is from a different revision to the
// previous line.
shouldDrawLine = false;
if (row > 0) {
ListModel<AnnotatedLine> model = list.getModel();
AnnotatedLine previousLine = model.getElementAt(row - 1);
if (line.revision != previousLine.revision) {
shouldDrawLine = true;
}
}
setText(line.formattedLine);
if (isSelected == false) {
setForeground((revisionView.getAnnotatedRevision() == line.revision) ? Color.BLUE : Color.BLACK);
}
}
public void paint(Graphics oldGraphics) {
Graphics2D g = (Graphics2D) oldGraphics;
super.paint(g);
if (shouldDrawLine) {
g.setColor(Color.LIGHT_GRAY);
g.setStroke(DASHED_STROKE);
g.drawLine(0, 0, getWidth(), 0);
}
}
}
| gpl-2.0 |
danaderp/unalcol | projects/optimizationRefactoringStrand/src/agentRefactoringStrand/Attribute.java | 137 | /**
*
*/
package agentRefactoringStrand;
/**
* @author Daavid
*
*/
public class Attribute {
private String name;
}
| gpl-2.0 |
yumjade/KickFor | src/com/example/kickfor/ProgressBarTimer.java | 941 | package com.example.kickfor;
import com.example.kickfor.team.ChangingRoomEntity;
import android.os.Handler;
import android.os.Message;
public class ProgressBarTimer implements Runnable{
private Object v=null;
private Handler handler=null;
private int what=-1;
private Object b=null;
public ProgressBarTimer(Handler handler, int what, Object v, Object b){
this.handler=handler;
this.what=what;
this.v=v;
this.b=b;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
Thread.sleep(10000);
}catch(Exception e){
e.printStackTrace();
}
if(b!=null && b instanceof ChangingRoomEntity){
((ChangingRoomEntity)b).pb1=true;
((ChangingRoomEntity)b).pb2=true;
Message msg=handler.obtainMessage();
msg.obj=v;
msg.what=what;
handler.sendMessage(msg);
}
else{
Message msg=handler.obtainMessage();
msg.obj=v;
msg.what=what;
handler.sendMessage(msg);
}
}
}
| gpl-2.0 |
Kalimaha/MLS_Barbaglia | src/main/java/it/unimarconi/utils/JobComparator.java | 228 | package it.unimarconi.utils;
import it.unimarconi.beans.Job;
import java.util.Comparator;
public class JobComparator implements Comparator<Job> {
public int compare(Job a, Job b) {
return a.compareTo(b);
}
} | gpl-2.0 |
unifieddigitalmedia/Just-Money-Transfers-Android | app/src/main/java/com/example/jmtransfers/jmtransfer/MainActivity.java | 2118 | package com.example.jmtransfers.jmtransfer; import android.content.SharedPreferences; import android.support.v7.app.ActionBar; import android.widget.TextView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
ProgressDialog progress ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
progress.dismiss();
Intent intent = new Intent(MainActivity.this, Dashboard.class);
startActivity(intent);
}
}.start();
ImageView logo = (ImageView) findViewById(R.id.logo);
logo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Dashboard.class);
startActivity(intent);
}
});
}
}
| gpl-2.0 |
markgiant/Minecraft | Shops/src/me/giantcrack/gs/Main.java | 2167 | package me.giantcrack.gs;
import me.giantcrack.eco.BalanceCmd;
import me.giantcrack.eco.BuyCmd;
import me.giantcrack.eco.EcoFile;
import me.giantcrack.eco.EconomyCmd;
import me.giantcrack.eco.SellCmd;
import me.giantcrack.eco.ValueCmd;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
public void onEnable() {
getCommand("buy").setExecutor(new BuyCmd());
getCommand("sell").setExecutor(new SellCmd());
getCommand("economy").setExecutor(new EconomyCmd());
getCommand("value").setExecutor(new ValueCmd());
getCommand("balance").setExecutor(new BalanceCmd());
getCommand("add").setExecutor(new AddItemCmd());
getCommand("edit").setExecutor(new EditItemCmd());
if (Config.getInstance().get("buysell") == null) {
Config.getInstance().set("buysell", 0.5);
}
ItemManager.getInstance().setUp();
Bukkit.getServer().getPluginManager().registerEvents(this, this);
}
public void onLoad() {
EcoFile.getInstance().setup(this);
ConverterFile.getInstance().setup(this);
Config.getInstance().setup(this);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
if (EcoFile.getInstance().get("Economy." + e.getPlayer().getUniqueId() + ".balance") == null) {
EcoFile.getInstance().setBalance(e.getPlayer(), 0.0);
}
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("convertitems")) {
if (sender.isOp()) {
ConverterFile.getInstance().convertOldConfig();
sender.sendMessage(ChatColor.GREEN + "File Converted!");
return true;
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
}
return false;
}
/***
* TODO LISt
*1.Finish Commands
*2.Test
*3.Do lava plugin
*/
}
| gpl-2.0 |