repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Sarius997/Multiplayer-PD
src/com/sarius/multiplayer_pd/windows/WndChooseWay.java
3331
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.sarius.multiplayer_pd.windows; import com.watabou.noosa.BitmapTextMultiline; import com.sarius.multiplayer_pd.actors.hero.HeroSubClass; import com.sarius.multiplayer_pd.items.TomeOfMastery; import com.sarius.multiplayer_pd.scenes.PixelScene; import com.sarius.multiplayer_pd.sprites.ItemSprite; import com.sarius.multiplayer_pd.ui.RedButton; import com.sarius.multiplayer_pd.ui.Window; import com.sarius.multiplayer_pd.utils.Utils; public class WndChooseWay extends Window { private static final String TXT_MESSAGE = "Which way will you follow?"; private static final String TXT_CANCEL = "I'll decide later"; private static final int WIDTH = 120; private static final int BTN_HEIGHT = 18; private static final float GAP = 2; public WndChooseWay( final TomeOfMastery tome, final HeroSubClass way1, final HeroSubClass way2 ) { super(); IconTitle titlebar = new IconTitle(); titlebar.icon( new ItemSprite( tome.image(), null ) ); titlebar.label( tome.name() ); titlebar.setRect( 0, 0, WIDTH, 0 ); add( titlebar ); Highlighter hl = new Highlighter( way1.desc() + "\n\n" + way2.desc() + "\n\n" + TXT_MESSAGE ); BitmapTextMultiline normal = PixelScene.createMultiline( hl.text, 6 ); normal.maxWidth = WIDTH; normal.measure(); normal.x = titlebar.left(); normal.y = titlebar.bottom() + GAP; add( normal ); if (hl.isHighlighted()) { normal.mask = hl.inverted(); BitmapTextMultiline highlighted = PixelScene.createMultiline( hl.text, 6 ); highlighted.maxWidth = normal.maxWidth; highlighted.measure(); highlighted.x = normal.x; highlighted.y = normal.y; add( highlighted ); highlighted.mask = hl.mask; highlighted.hardlight( TITLE_COLOR ); } RedButton btnWay1 = new RedButton( Utils.capitalize( way1.title() ) ) { @Override protected void onClick() { hide(); tome.choose( way1 ); } }; btnWay1.setRect( 0, normal.y + normal.height() + GAP, (WIDTH - GAP) / 2, BTN_HEIGHT ); add( btnWay1 ); RedButton btnWay2 = new RedButton( Utils.capitalize( way2.title() ) ) { @Override protected void onClick() { hide(); tome.choose( way2 ); } }; btnWay2.setRect( btnWay1.right() + GAP, btnWay1.top(), btnWay1.width(), BTN_HEIGHT ); add( btnWay2 ); RedButton btnCancel = new RedButton( TXT_CANCEL ) { @Override protected void onClick() { hide(); } }; btnCancel.setRect( 0, btnWay2.bottom() + GAP, WIDTH, BTN_HEIGHT ); add( btnCancel ); resize( WIDTH, (int)btnCancel.bottom() ); } }
gpl-3.0
DarioGT/OMS-PluginXML
org.modelsphere.jack/src/org/modelsphere/jack/srtool/actions/PageBreaksAction.java
3135
/************************************************************************* Copyright (C) 2009 Grandite This file is part of Open ModelSphere. Open ModelSphere is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can redistribute and/or modify this particular file even under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can reach Grandite at: 20-1220 Lebourgneuf Blvd. Quebec, QC Canada G2K 2G4 or open-modelsphere@grandite.com **********************************************************************/ package org.modelsphere.jack.srtool.actions; import javax.swing.Action; import org.modelsphere.jack.actions.AbstractApplicationAction; import org.modelsphere.jack.actions.SelectionActionListener; import org.modelsphere.jack.graphic.DiagramView; import org.modelsphere.jack.srtool.ApplicationContext; import org.modelsphere.jack.srtool.graphic.ApplicationDiagram; import org.modelsphere.jack.srtool.international.LocaleMgr; public class PageBreaksAction extends AbstractApplicationAction implements SelectionActionListener { public PageBreaksAction() { super(LocaleMgr.action.getString("hidePageBreaks")); } protected final void doActionPerformed() { ApplicationDiagram diag = (ApplicationDiagram) ApplicationContext.getFocusManager() .getFocusObject(); DiagramView view = diag.getMainView(); view.setPageBreak(!view.hasPageBreak()); } public final void updateSelectionAction() { if (isApplicationDiagramHaveFocus()) { setEnabled(true); putValue(Action.NAME, getItemName((ApplicationDiagram) ApplicationContext .getFocusManager().getFocusObject())); } else { setEnabled(false); } } public static String getItemName(ApplicationDiagram diag) { if (diag.getMainView().hasPageBreak()) return LocaleMgr.action.getString("hidePageBreaks"); else return LocaleMgr.action.getString("showPageBreaks"); } }
gpl-3.0
702nADOS/sumo
tools/contributed/traas/examples/java_wsclient/de/tudresden/ws/SimulationGetDistanceRoadResponse.java
1377
package de.tudresden.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für Simulation_getDistanceRoadResponse complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="Simulation_getDistanceRoadResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Simulation_getDistanceRoadResponse", propOrder = { "_return" }) public class SimulationGetDistanceRoadResponse { @XmlElement(name = "return") protected double _return; /** * Ruft den Wert der return-Eigenschaft ab. * */ public double getReturn() { return _return; } /** * Legt den Wert der return-Eigenschaft fest. * */ public void setReturn(double value) { this._return = value; } }
gpl-3.0
SimplicityApks/AmazeFileManager
src/com/amaze/filemanager/database/TabHandler.java
5745
/* * Copyright (C) 2014 Arpit Khurana <arpitkh96@gmail.com>, Vishal Nehra <vishalmeham2@gmail.com> * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; /** * Created by Vishal on 9/17/2014. */ public class TabHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "explorer.db"; private static final String TABLE_TAB = "tab"; public static final String COLUMN_ID = "id"; public static final String COLUMN_TAB_NO = "tab_no"; public static final String COLUMN_LABEL = "label"; public static final String COLUMN_PATH = "path"; public TabHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, DATABASE_NAME, factory, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String CREATE_TAB_TABLE = "CREATE TABLE " + TABLE_TAB + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_TAB_NO + " INTEGER," + COLUMN_LABEL + " TEXT," + COLUMN_PATH + " TEXT" + ")"; sqLiteDatabase.execSQL(CREATE_TAB_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_TAB); onCreate(sqLiteDatabase); } public void addTab(Tab tab) { ContentValues contentValues = new ContentValues(); contentValues.put(COLUMN_TAB_NO, tab.getTab()); contentValues.put(COLUMN_LABEL, tab.getLabel()); contentValues.put(COLUMN_PATH, tab.getPath()); SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); sqLiteDatabase.insert(TABLE_TAB, null, contentValues); sqLiteDatabase.close(); } public Tab findTab(int tabNo) { String query = "Select * FROM " + TABLE_TAB + " WHERE " + COLUMN_TAB_NO + "= \"" + tabNo + "\""; SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); Cursor cursor = sqLiteDatabase.rawQuery(query, null); Tab tab = new Tab(); if (cursor.moveToFirst()) { cursor.moveToFirst(); tab.setID(Integer.parseInt(cursor.getString(0))); tab.setTab(Integer.parseInt(cursor.getString(1))); tab.setLabel(cursor.getString(2)); tab.setPath(cursor.getString(3)); cursor.close(); } else { tab = null; } sqLiteDatabase.close(); return tab; } public void updateTab(Tab tab) { ContentValues contentValues = new ContentValues(); contentValues.put(COLUMN_LABEL, tab.getLabel()); contentValues.put(COLUMN_PATH, tab.getPath()); SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); sqLiteDatabase.update(TABLE_TAB, contentValues, tab.getTab() + "=" + COLUMN_TAB_NO, null); sqLiteDatabase.close(); } public boolean deleteTab(int tabNo) { boolean result = false; String query = "Select * FROM " + TABLE_TAB + " WHERE " + COLUMN_TAB_NO + " = \"" + tabNo + "\""; SQLiteDatabase sqLiteDatabase = getWritableDatabase(); Cursor cursor = sqLiteDatabase.rawQuery(query, null); Tab tab = new Tab(); if (cursor.moveToFirst()) { tab.setID(Integer.parseInt(cursor.getString(0))); sqLiteDatabase.delete(TABLE_TAB, COLUMN_ID + " = ?", new String[]{String.valueOf(tab.getID())}); cursor.close(); result = true; } sqLiteDatabase.close(); return result; } public List<Tab> getAllTabs() { List<Tab> tabList = new ArrayList<Tab>(); // Select all query String query = "Select * FROM " + TABLE_TAB; SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); Cursor cursor = sqLiteDatabase.rawQuery(query, null); // Looping through all rows and adding them to list if (cursor.moveToFirst()) { do { Tab tab = new Tab(); tab.setID(Integer.parseInt(cursor.getString(0))); tab.setTab(Integer.parseInt(cursor.getString(1))); tab.setLabel(cursor.getString(2)); tab.setPath(cursor.getString(3)); //Adding them to list tabList.add(tab); } while (cursor.moveToNext()); } return tabList; } public int getTabsCount() { String countQuery = "Select * FROM " + TABLE_TAB; SQLiteDatabase sqLiteDatabase = this.getReadableDatabase(); Cursor cursor = sqLiteDatabase.rawQuery(countQuery, null); int count = cursor.getCount(); cursor.close(); return count; } }
gpl-3.0
TheCount/jhilbert
src/main/java/jhilbert/expressions/KindMismatchException.java
1782
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert.expressions; /** * A {@link ExpressionException} throws when result and input * {@link jhilbert.data.Kind} do not match in an {@link Expression}. */ public class KindMismatchException extends ExpressionException { /** * Constructs a new <code>KindMismatchException</code> with the * specified detail message. * * @param message detail message. */ public KindMismatchException(final String message) { this(message, null); } /** * Constructs a new <code>KindMismatchException</code> with the * specified detail message and cause. * * @param message detail message. * @param cause the cause. */ public KindMismatchException(final String message, final Throwable cause) { super(message, cause); } }
gpl-3.0
itru/timesheet
src/main/java/com/aplana/timesheet/enums/UndertimeCausesEnum.java
936
package com.aplana.timesheet.enums; /** * @author eshangareev * @version 1.0 */ public enum UndertimeCausesEnum implements TSEnum { ASK_FOR_LEAVE(100, "Отпросился"), DOG_SICK(101, "Плохо себя чувствовал"), LATE_FOR_WORK(102, "Опоздал"), NO_TASKS(103, "Для меня нет задач"), STATE_OF_EMERGENCY_IN_THE_OFFICE(104, "В офисе произошло ЧП"), OTHER(105, "Другое"), PARTIAL_JOB_RATE(123, "Я работаю на часть ставки, положенное время отработал"), CORPORATE_EVENT(124, "Корпоративное мероприятие"); private int id; private String name; public int getId() { return id; } public String getName() { return name; } private UndertimeCausesEnum(int id, String name) { this.id = id; this.name = name; } }
gpl-3.0
Martin-Spamer/java-coaching
src/test/java/coaching/delegation/ManagerTest.java
622
package coaching.delegation; import org.junit.Test; import static org.junit.Assert.assertNotNull; import lombok.extern.slf4j.Slf4j; /** * Manager Test. */ @Slf4j public final class ManagerTest { /** * Test delegation. */ @Test public void testDelegation() { log.info("testDelegation"); final Manager manager = new Manager(); assertNotNull(manager); final Worker worker = new Worker(); assertNotNull(manager); assertNotNull(manager.setWorker(worker)); assertNotNull(manager.doProcess()); } }
gpl-3.0
danielhuson/dendroscope3
src/dendroscope/commands/SetMaintainEdgeLengthsCommand.java
3839
/* * SetMaintainEdgeLengthsCommand.java Copyright (C) 2020 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dendroscope.commands; import dendroscope.window.MultiViewer; import dendroscope.window.TreeViewer; import jloda.swing.commands.ICheckBoxCommand; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Iterator; /** * Daniel Huson, 4.2011 */ public class SetMaintainEdgeLengthsCommand extends CommandBaseMultiViewer implements ICheckBoxCommand { public boolean isSelected() { boolean hasOne = false; for (Iterator<TreeViewer> it = multiViewer.getTreeGrid().getSelectedOrAllIterator(); it.hasNext(); ) { TreeViewer viewer = it.next(); if (viewer.getMaintainEdgeLengths()) hasOne = true; else return false; } return hasOne; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Lock Edge Lengths"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "When set, all edge lengths are fixed, when not set, nodes can be moved arbitrarily"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it * * @param np * @throws java.io.IOException */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set maintainedgelengths="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); for (Iterator<TreeViewer> it = multiViewer.getTreeGrid().getSelectedOrAllIterator(); it.hasNext(); ) { TreeViewer viewer = it.next(); viewer.setMaintainEdgeLengths(value); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set maintainedgelengths={true|false};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((MultiViewer) getViewer()).getDir().getDocument().getNumberOfTrees() > 0; } /** * action to be performed * * @param ev */ @Override public void actionPerformed(ActionEvent ev) { execute("set maintainedgelengths=" + (!isSelected() + ";")); } }
gpl-3.0
NEMESIS13cz/Evercraft
java/evercraft/NEMESIS13cz/Items/Powders/ItemZincPowder.java
693
package evercraft.NEMESIS13cz.Items.Powders; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import evercraft.NEMESIS13cz.ModInformation; import evercraft.NEMESIS13cz.Main.ECTabs; public class ItemZincPowder extends Item { public ItemZincPowder() { setCreativeTab(ECTabs.tabECWGMaterials); //Tells the game what creative mode tab it goes in } @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(ModInformation.TEXTUREPATH + ":" + ModInformation.ZINC_POWDER); } }
gpl-3.0
iKeirNez/UUIDCompatibility
src/main/java/com/ikeirnez/uuidcompatibility/UUIDCompatibility.java
16254
package com.ikeirnez.uuidcompatibility; import com.ikeirnez.uuidcompatibility.commands.MainCommand; import com.ikeirnez.uuidcompatibility.utils.CustomConfigWrapper; import com.ikeirnez.uuidcompatibility.utils.Utils; import javassist.*; import net.ess3.api.IEssentials; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.mcstats.Metrics; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by iKeirNez on 29/06/2014. */ public class UUIDCompatibility extends JavaPlugin implements Listener { private static UUIDCompatibility instance; /** * Below is used for reflection */ public static final String CRAFT_SERVER_CLASS_NAME = Bukkit.getServer().getClass().getName(); public static final String OBC_PACKAGE = CRAFT_SERVER_CLASS_NAME.substring(0, CRAFT_SERVER_CLASS_NAME.length() - ".CraftServer".length()); public static final String HUMAN_ENTITY_CLASS = OBC_PACKAGE + ".entity.CraftHumanEntity"; public static String MESSAGE_PREFIX = ChatColor.AQUA + "[" + ChatColor.GOLD + "UUIDCompatibility" + ChatColor.AQUA + "] " + ChatColor.GREEN; public static UUIDCompatibility getInstance() { return instance; } private Metrics metrics; private Set<Plugin> compatibilityPlugins = Collections.newSetFromMap(new ConcurrentHashMap<Plugin, Boolean>()); // clunky, I know, but the only way as far as I'm aware public Map<UUID, String> playerRealNames = new ConcurrentHashMap<>(); private Map<Plugin, List<String>> classNameToPluginMap = new ConcurrentHashMap<>(); private CustomConfigWrapper nameMappingsWrapper, retrievesWrapper; private boolean debug = false; { instance = this; if (!Utils.classExists("com.ikeirnez.uuidcompatibility.hax.UUIDCompatibilityMethodCache")){ try { debug("Injecting code"); ClassPool classPool = ClassPool.getDefault(); // create class used for containing a reference to the getName method in ExternalAccess, this saves us getting it every time // this is effective as the getName() method is run A LOT, especially with certain plugins CtClass ctCacheClass = classPool.makeClass("com.ikeirnez.uuidcompatibility.hax.UUIDCompatibilityMethodCache"); CtField ctCacheField = new CtField(classPool.get(Method.class.getName()), "GET_NAME_METHOD", ctCacheClass); ctCacheField.setModifiers(Modifier.PUBLIC | Modifier.STATIC); ctCacheClass.addField(ctCacheField, CtField.Initializer.byExpr("Class.forName(\"" + ExternalAccess.class.getName() + "\", true, " + Bukkit.class.getName() + ".getPluginManager().getPlugin(\"" + getDescription().getName() + "\").getClass().getClassLoader()).getDeclaredMethod(\"getPlayerName\", new Class[]{" + HumanEntity.class.getName() + ".class})")); ctCacheClass.toClass(Bukkit.class.getClassLoader(), Bukkit.class.getProtectionDomain()); // hook into the getName method of CraftHumanEntity // in the case of this failing, print the stack trace and fallback to default methods CtClass ctCraftHumanEntityClass = classPool.get(HUMAN_ENTITY_CLASS); CtMethod ctGetNameMethod = ctCraftHumanEntityClass.getDeclaredMethod("getName"); ctGetNameMethod.setBody("{ try { return (String) com.ikeirnez.uuidcompatibility.hax.UUIDCompatibilityMethodCache.GET_NAME_METHOD.invoke(null, new Object[]{this}); } catch (" + Throwable.class.getName() + " e) { e.printStackTrace(); return getHandle().getName(); } }"); Class<?> craftServerClass = Bukkit.getServer().getClass(); ctCraftHumanEntityClass.toClass(craftServerClass.getClassLoader(), craftServerClass.getProtectionDomain()); } catch (Throwable throwable){ getLogger().severe("Error whilst injecting code"); throwable.printStackTrace(); } } else { debug("Skipping injection, already injected"); } } @Override public void onLoad() { getConfig().options().copyDefaults(true); saveConfig(); if (!getConfig().getBoolean("enabled")){ // warning will be shown in onEnable() return; } debug = getConfig().getBoolean("debug"); debug("Debugging is now enabled"); nameMappingsWrapper = new CustomConfigWrapper(new File(getDataFolder(), "nameMappings.yml")); retrievesWrapper = new CustomConfigWrapper(new File(getDataFolder(), "retrieves.yml")); loadCompatibilityPlugin(); } public void loadCompatibilityPlugin(){ PluginManager pluginManager = Bukkit.getPluginManager(); compatibilityPlugins.clear(); debug("Calculating plugins to enable UUID compatibility for"); List<String> pluginList = getConfig().getStringList("showOriginalNameIn.plugins"); if (pluginList.contains("*")){ compatibilityPlugins.addAll(Arrays.asList(pluginManager.getPlugins())); compatibilityPlugins.remove(this); // don't enable compatibility for our own plugin for (String pluginName : pluginList){ if (pluginName.startsWith("-")){ Plugin plugin = pluginManager.getPlugin(pluginName.substring(1, pluginName.length())); if (plugin != null){ compatibilityPlugins.remove(plugin); } } } } else { for (String pluginName : pluginList){ Plugin plugin = pluginManager.getPlugin(pluginName); if (plugin != null){ if (plugin == this){ getLogger().warning("Nice try, but compatibility cannot be enabled for the plugin \"UUIDCompatibility\""); continue; } compatibilityPlugins.add(plugin); } } } debug("The following plugins will have UUID compatibility enabled: " + Arrays.toString(compatibilityPlugins.toArray())); debug("Reading plugin jar files to cache class names..."); for (Plugin plugin : Bukkit.getPluginManager().getPlugins()){ if (!pluginList.contains(plugin.getName())){ continue; } List<String> classNames = new ArrayList<>(); File pluginJar = Utils.getJarForPlugin(plugin); if (compatibilityPlugins.contains(plugin)){ try { if (pluginJar.getName().endsWith(".jar")){ ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(pluginJar)); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null){ String entryName = zipEntry.getName(); if (!zipEntry.isDirectory() && entryName.endsWith(".class")){ StringBuilder className = new StringBuilder(); for (String part : entryName.split("/")){ if (className.length() != 0){ className.append("."); } className.append(part); if (part.endsWith(".class")){ className.setLength(className.length() - ".class".length()); } } classNames.add(className.toString()); } zipEntry = zipInputStream.getNextEntry(); } classNameToPluginMap.put(plugin, classNames); } } catch (Throwable throwable){ getLogger().severe("Error caching class names for plugin " + plugin.getName()); throwable.printStackTrace(); } } } } @Override public void onEnable(){ if (!getConfig().getBoolean("enabled")){ getLogger().severe("The plugin enabled status has not been set to true in the config, disabling..."); setEnabled(false); return; } PluginManager pluginManager = Bukkit.getPluginManager(); pluginManager.registerEvents(new UUIDCompatibilityListener(this), this); pluginManager.registerEvents(this, this); PluginCommand command = getCommand("uuidcompatibility"); MainCommand mainCommand = new MainCommand(this); command.setExecutor(mainCommand); command.setTabCompleter(mainCommand); importData(); try { metrics = new Metrics(this); Metrics.Graph storedGraph = metrics.createGraph("Player UUIDs <-> Names Stored"); storedGraph.addPlotter(new Metrics.Plotter() { @Override public int getValue() { return getNameMappingsWrapper().getConfig().getKeys(false).size(); } }); metrics.start(); } catch (IOException e){} } public void importData(){ if (!getRetrievesWrapper().getConfig().getBoolean("retrieved.world-data")){ getLogger().info("Retrieving UUID <-> Names from player dat files, please wait..."); for (OfflinePlayer offlinePlayer : Bukkit.getOfflinePlayers()){ String uuidString = offlinePlayer.getUniqueId().toString(); if (!getNameMappingsWrapper().getConfig().contains(uuidString)){ getNameMappingsWrapper().getConfig().set(uuidString, offlinePlayer.getName()); } } getNameMappingsWrapper().saveConfig(); getRetrievesWrapper().getConfig().set("retrieved.world-data", true); getRetrievesWrapper().saveConfig(); } if (!getRetrievesWrapper().getConfig().getBoolean("retrieved.essentials", false)){ Plugin essentialsPlugin = getServer().getPluginManager().getPlugin("Essentials"); if (essentialsPlugin != null){ getLogger().info("Retrieving UUID <-> Names from Essentials data, please wait..."); IEssentials essentials = (IEssentials) essentialsPlugin; File userDataFolder = new File(essentials.getDataFolder(), "userdata/"); if (userDataFolder.exists() && userDataFolder.isDirectory()){ File[] files = userDataFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".yml"); } }); if (files != null){ for (File file : files){ String fileName = file.getName(); if (fileName.endsWith(".yml")){ try { UUID uuid = UUID.fromString(fileName.substring(0, fileName.length() - 4)); String uuidString = uuid.toString(); if (!getNameMappingsWrapper().getConfig().contains(uuidString)){ getNameMappingsWrapper().getConfig().set(uuidString, essentials.getUser(uuid).getLastAccountName()); } } catch (IllegalArgumentException e){} } } getNameMappingsWrapper().saveConfig(); getRetrievesWrapper().getConfig().set("retrieved.essentials", true); getRetrievesWrapper().saveConfig(); } else { getLogger().severe("Something prevented"); } } else { getLogger().severe("Unable to import from Essentials due to the userdata file not existing or is not a directory"); } } } } @Override public void onDisable() { instance = null; } public void debug(String message){ if (debug){ getLogger().info(message); } } public String getOriginalName(Player player){ FileConfiguration nameMappings = getNameMappingsWrapper().getConfig(); UUID uuid = player.getUniqueId(); String uuidString = uuid.toString(); if (!nameMappings.contains(uuidString)){ String realName = getRealName(player); String newRealName = realName; int numberSuffix = 1; while (nameMappings.getValues(false).containsValue(newRealName)){ newRealName = realName + "_" + numberSuffix++; } nameMappings.set(uuidString, newRealName); getNameMappingsWrapper().saveConfig(); return newRealName; } return nameMappings.getString(uuidString); } public String getRealName(Player player){ UUID uuid = player.getUniqueId(); // I couldn't use metadata here instead as it makes a call to getName which results in an infinite continuous loop if (!playerRealNames.containsKey(uuid)){ try { Object gameProfile = player.getClass().getDeclaredMethod("getProfile").invoke(player); String realName = (String) gameProfile.getClass().getMethod("getName").invoke(gameProfile); playerRealNames.put(uuid, realName); return realName; } catch (Throwable e){ getLogger().severe("Error retrieving real name for " + uuid); e.printStackTrace(); return null; } } else { return playerRealNames.get(uuid); } } public Plugin isCompatibilityEnabledForClass(Class<?> clazz){ return isCompatibilityEnabledForClass(clazz.getName()); } public Plugin isCompatibilityEnabledForClass(String className){ for (Map.Entry<Plugin, List<String>> entry : classNameToPluginMap.entrySet()){ if (entry.getValue().contains(className)){ return entry.getKey(); } } return null; } public void refreshDisplayNames(Player player, boolean join){ String pName = player.getName(); String originalName = null; // cache original name when used, prevents this being fetched twice if (getConfig().getBoolean("showOriginalNameIn.displayName")){ player.setDisplayName(originalName = getOriginalName(player)); } else if (!join){ player.setDisplayName(pName); } if (getConfig().getBoolean("showOriginalNameIn.tabList")){ if (originalName == null){ originalName = getOriginalName(player); } player.setPlayerListName(originalName); } else if (!join){ player.setPlayerListName(pName); } } public Set<Plugin> getCompatibilityPlugins() { return compatibilityPlugins; } public CustomConfigWrapper getNameMappingsWrapper() { return nameMappingsWrapper; } public CustomConfigWrapper getRetrievesWrapper() { return retrievesWrapper; } }
gpl-3.0
caramalek/taskblocks
src/taskblocks/io/ProjectSaveLoad.java
18058
/* * Copyright (C) Jakub Neubauer, 2007 * * This file is part of TaskBlocks * * TaskBlocks is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * TaskBlocks 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 taskblocks.io; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import taskblocks.modelimpl.ColorLabel; import taskblocks.modelimpl.ManImpl; import taskblocks.modelimpl.TaskImpl; import taskblocks.modelimpl.TaskModelImpl; import taskblocks.utils.Pair; import taskblocks.utils.Utils; /** * Used to load/save the task project model * * @author jakub * */ public class ProjectSaveLoad { public static final String TASKMAN_E = "taskman"; public static final String TASKS_E = "tasks"; public static final String MANS_E = "mans"; public static final String TASK_E = "task"; public static final String MAN_E = "man"; public static final String PREDECESSORS_E = "predecessors"; public static final String PREDECESSOR_E = "predecessor"; public static final String VERSION_A = "version"; public static final String NAME_A = "name"; public static final String NICKNAME_A = "nickname"; public static final String WORKLOAD_A = "workload"; public static final String ID_A = "id"; public static final String START_A = "start"; public static final String END_A = "end"; public static final String DURATION_A = "duration"; public static final String ACTUAL_A = "actualDuration"; public static final String MAN_A = "man"; public static final String PRED_A = "pred"; public static final String COLOR_A = "color"; public static final String OBJ_A = "objective"; public static final String COMM_A = "comment"; // Id in Bugzilla, used when exporting to it. public static final String BUGID_A = "bugid"; TaskModelImpl _model; Map<String, TaskImpl> _taskIds; Map<String, ManImpl> _manIds; public static final int CURRENT_VERSION = 1; /** * Loads project data model from given file. * TODO: checks for missing data in elements * * @param f * @return * @throws WrongDataException */ public TaskModelImpl loadProject(URL f) throws WrongDataException { InputStream input = null; try { input = f.openStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc; doc = dbf.newDocumentBuilder().parse(input); Element rootE = doc.getDocumentElement(); if(!TASKMAN_E.equals(rootE.getNodeName())) { throw new WrongDataException("Document is not TaskBlocks project"); } // mapping ID -> ManImpl Map<String, ManImpl> mans = new HashMap<String, ManImpl>(); // mapping ID -> TaskImpl Map<String, TaskImpl>tasks = new HashMap<String, TaskImpl>(); // mapping tasks -> list of their predecessors IDs List<Pair<TaskImpl, String[]>> taskPredecessorsIds = new ArrayList<Pair<TaskImpl,String[]>>(); // check the data version. The first Taskblocks files had no version attribute. String versionAttr = rootE.getAttribute(VERSION_A); if(versionAttr != null && versionAttr.trim().length() > 0) { try { versionAttr = versionAttr.trim(); int version = Integer.parseInt(versionAttr); if(version > CURRENT_VERSION) { throw new WrongDataException("Cannot load higher version '" + version + "', current is '" + CURRENT_VERSION + "'."); } } catch(NumberFormatException e) { throw new WrongDataException("Wrong data file version: '" + versionAttr + "'"); } } // 1. load all tasks and mans alone, 2. bind them between each other Element mansE = getFirstChild(rootE, MANS_E); if(mansE != null) { Element[] manEs = Utils.getChilds(mansE, MAN_E); for(Element manE: manEs) { String manName = manE.getAttribute(NAME_A); String manWorkload = manE.getAttribute(WORKLOAD_A); String manId = manE.getAttribute(ID_A); String manNickname = manE.getAttribute(NICKNAME_A); ManImpl man = new ManImpl(); man.setName(manName); man.setNickname(manNickname); if(manWorkload != null && manWorkload.trim().length() > 0) { try { man.setWorkload(Double.parseDouble(manWorkload.trim())/100.0); } catch(NumberFormatException e) { // TODO Jakub: handle exception System.err.println("Cannot parse man's workload '" + manWorkload + "'"); } } mans.put(manId, man); } } Element tasksE = getFirstChild(rootE, TASKS_E); if(tasksE != null) { for(Element taskE: Utils.getChilds(tasksE, TASK_E)) { String taskId = taskE.getAttribute(ID_A); String taskName = taskE.getAttribute(NAME_A); String taskManId = taskE.getAttribute(MAN_A); ManImpl man = mans.get(taskManId); // mans are already loaded if(man == null) { throw new WrongDataException("Task with id " + taskId + " is not assigned to any man"); } long taskStart = xmlTimeToTaskTime(taskE.getAttribute(START_A)); String durAttr = taskE.getAttribute(DURATION_A); long taskEffort; if(durAttr != null && durAttr.trim().length() > 0) { taskEffort = xmlDurationToTaskDuration(durAttr); } else { String endAttr = taskE.getAttribute(END_A); long taskEnd = xmlTimeToTaskTime(endAttr); // start with effort=1. Increase it until the real duration is over for(long newEffort = 2; true; newEffort++) { long tmpEndTime = Utils.countFinishTime(taskStart, newEffort, man.getWorkload()); // Note: we compare to (taskEnd+1), since the tasks start/end are counted mathematically. For example task with // duration 1 day starting on 2011-01-01 ends on 2011-01-02 (the second day) if(tmpEndTime > (taskEnd+1)) { // we are over, step back taskEffort = newEffort-1; break; } } } String usedStr = taskE.getAttribute(ACTUAL_A); long taskWorkedTime = 0; if(usedStr != null && usedStr.trim().length() > 0) { taskWorkedTime = xmlDurationToTaskDuration(taskE.getAttribute(ACTUAL_A)); } String bugId = taskE.getAttribute(BUGID_A); String colorTxt = taskE.getAttribute(COLOR_A); String objective = taskE.getAttribute(OBJ_A); String comment = taskE.getAttribute(COMM_A); if(bugId != null && bugId.length() == 0) { bugId = null; } TaskImpl task = new TaskImpl(); task.setName(taskName); task.setStartTime(taskStart); task.setEffort(taskEffort); task.setWorkedTime(taskWorkedTime); task.setMan(man); task.setComment( comment ); task.setObjective(objective); task.setBugId(bugId); if(colorTxt != null && colorTxt.length() > 0) { int colorIndex = Integer.parseInt(colorTxt); if(colorIndex >= 0 && colorIndex < ColorLabel.COLOR_LABELS.length) { task.setColorLabel(ColorLabel.COLOR_LABELS[colorIndex]); } } // read predecessors ids Element predsE = getFirstChild(taskE, PREDECESSORS_E); if(predsE != null) { List<String> preds = new ArrayList<String>(); for(Element predE: Utils.getChilds(predsE, PREDECESSOR_E)) { preds.add(predE.getAttribute(PRED_A)); } taskPredecessorsIds.add(new Pair<TaskImpl, String[]>(task, preds.toArray(new String[preds.size()]))); } tasks.put(taskId, task); } } // now count the predecessors of tasks for(Pair<TaskImpl, String[]> taskAndPredIds: taskPredecessorsIds) { List<TaskImpl> preds = new ArrayList<TaskImpl>(); for(String predId: taskAndPredIds.snd) { TaskImpl pred = tasks.get(predId); if(pred == null) { System.out.println("Warning: Task predecessor with id " + predId + " doesn't exist"); // NOPMD by jakub on 6.8.09 15:50 } else if(pred == taskAndPredIds.fst) { System.out.println("Warning: Task with id " + predId + " is it's own predecessor"); // NOPMD by jakub on 6.8.09 15:50 } else { preds.add(pred); } } taskAndPredIds.fst.setPredecessors(preds.toArray(new TaskImpl[preds.size()])); } TaskModelImpl taskModel = new TaskModelImpl(tasks.values().toArray(new TaskImpl[tasks.size()]), mans.values().toArray(new ManImpl[mans.size()])); return taskModel; } catch (SAXException e) { throw new WrongDataException("Document is not valid data file", e); } catch (IOException e) { throw new WrongDataException("Can't read file: " + e.getMessage(), e); } catch (ParserConfigurationException e) { throw new WrongDataException("Document is not TaskBlocks project", e); } finally { if(input != null) { try { input.close(); } catch (IOException e) { throw new WrongDataException("Cannot close input stream: " + e.toString()); } } } } public void saveProject(URL url, TaskModelImpl model) throws TransformerException, ParserConfigurationException, IOException { if("file".equals(url.getProtocol())) { File f; try { f = new File(url.toURI()); } catch(URISyntaxException e) { f = new File(url.getPath()); } saveProject(f, model); } else if("http".equals(url.getProtocol())) { ByteArrayOutputStream tmp = new ByteArrayOutputStream(); saveProject(tmp, model); OutputStream out = null; HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); //con.setDoInput(false); con.setRequestMethod("PUT"); con.setRequestProperty("Content-Length", String.valueOf(tmp.size())); con.setRequestProperty("Content-Type", "application/xml"); con.connect(); out = con.getOutputStream(); out.write(tmp.toByteArray()); int responseCode = con.getResponseCode(); if(responseCode != 200) { throw new IOException("HTTP Error " + responseCode + ": " + con.getResponseMessage()); } } finally { if(out != null) { out.close(); } if(con != null) { con.disconnect(); } } } else { throw new IOException("Unsupported url protocol: " + url.getProtocol()); } } /** * Saves project to specified file * * @param f * @param model * @throws TransformerException * @throws ParserConfigurationException * @throws IOException */ public void saveProject(File f, TaskModelImpl model) throws TransformerException, ParserConfigurationException, IOException { FileOutputStream fos = new FileOutputStream(f); try { saveProject(fos, model); } finally { fos.close(); } } public void saveProject(OutputStream out, TaskModelImpl model) throws TransformerException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc; doc = dbf.newDocumentBuilder().newDocument(); _model = model; _taskIds = new HashMap<String, TaskImpl>(); _manIds = new HashMap<String, ManImpl>(); // build the xml tree saveProject(doc); prettyLayout((Element)doc.getFirstChild()); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(doc), new StreamResult(out)); } private void saveProject(Document doc) { Element rootE = doc.createElement(TASKMAN_E); doc.appendChild(rootE); Set<ManImpl> mans = new HashSet<ManImpl>(); // generate list of mans for(ManImpl m: _model._mans) { mans.add(m); } // generate task and man ids int lastTaskId = 1; int lastManId = 1; for(TaskImpl t: _model._tasks) { t._id = String.valueOf(lastTaskId++); } for(ManImpl man: mans) { man._id = String.valueOf(lastManId++); } // save mans Element mansE = doc.createElement(MANS_E); for(ManImpl man : mans) { saveMan(mansE, man); } rootE.appendChild(mansE); // save tasks Element tasksE = doc.createElement(TASKS_E); for(TaskImpl t: _model._tasks) { saveTask(tasksE, t); } rootE.setAttribute(VERSION_A, String.valueOf(CURRENT_VERSION)); rootE.appendChild(tasksE); } private void saveMan(Element mansE, ManImpl man) { Element manE = mansE.getOwnerDocument().createElement(MAN_E); manE.setAttribute(ID_A, man._id); manE.setAttribute(NAME_A, man.getName()); manE.setAttribute(NICKNAME_A, man.getNickname()); manE.setAttribute(WORKLOAD_A, String.valueOf((int)(man.getWorkload()*100))); mansE.appendChild(manE); } static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); private static String taskTimeToXmlTime(long day) { return df.format(new Date(day * Utils.MILLISECONDS_PER_DAY + 8*60*60*1000)); } private static String taskDurationToXmlDuration(long dur) { return "P" + dur + "D"; } private static long xmlTimeToTaskTime(String time) throws WrongDataException { try { return Long.parseLong(time); } catch(NumberFormatException e) { // do nothing } try { return df.parse(time).getTime()/Utils.MILLISECONDS_PER_DAY; } catch (ParseException e) { // DO NOTHING } throw new WrongDataException("Wrong time value: " + time); } private static long xmlDurationToTaskDuration(String dur) throws WrongDataException{ if(dur == null || dur.trim().length() == 0) { return 0; } try { return Long.parseLong(dur); } catch(NumberFormatException e) { // do nothing } if(dur.startsWith("P") && dur.endsWith("D")) { try { return Long.parseLong(dur.substring(1,dur.length()-1)); } catch(NumberFormatException e) { // do nothing } } throw new WrongDataException("Wrong duration value: " + dur); } private void saveTask(Element tasksE, TaskImpl t) { Element taskE = tasksE.getOwnerDocument().createElement(TASK_E); taskE.setAttribute(NAME_A, t.getName()); taskE.setAttribute(ID_A, t._id); taskE.setAttribute(START_A, taskTimeToXmlTime(t.getStartTime())); taskE.setAttribute(DURATION_A, taskDurationToXmlDuration(t.getEffort())); if(t.getWorkedTime() != 0) { taskE.setAttribute(ACTUAL_A, taskDurationToXmlDuration(t.getWorkedTime())); } taskE.setAttribute(MAN_A, t.getMan()._id); taskE.setAttribute(COMM_A, t.getComment()); taskE.setAttribute(OBJ_A, t.getObjective()); if(t.getColorLabel() != null) { taskE.setAttribute(COLOR_A, String.valueOf(t.getColorLabel()._index)); } if(t.getBugId() != null && t.getBugId().trim().length() > 0) { taskE.setAttribute(BUGID_A, t.getBugId().trim()); } // save predecessors if(t.getPredecessors().length > 0) { Element predsE = taskE.getOwnerDocument().createElement(PREDECESSORS_E); for(TaskImpl pred: t.getPredecessors()) { Element predE = predsE.getOwnerDocument().createElement(PREDECESSOR_E); predE.setAttribute(PRED_A, pred._id); predsE.appendChild(predE); } taskE.appendChild(predsE); } tasksE.appendChild(taskE); } private Element getFirstChild(Element e, String name) { NodeList nl = e.getChildNodes(); for(int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if(n.getNodeType() == Node.ELEMENT_NODE && name.equals(n.getNodeName())) { return (Element)n; } } return null; } private void prettyLayout(Element e) { prettyLayoutRec(e, ""); } private void prettyLayoutRec(Element e, String currentIndent) { // insert spaces before 'e' // but only if indent > 0. This also resolves problem that we cannot insert // anything in Document node (before root element). if(currentIndent.length() > 0) { e.getParentNode().insertBefore(e.getOwnerDocument().createTextNode(currentIndent), e); } // first check if element has some sub-element. if true, prettyLayout them // recursively with increase indent NodeList nl = e.getChildNodes(); boolean hasChildrenElems = false; for(int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) { hasChildrenElems = true; break; } } if(hasChildrenElems) { // \n after start-tag. it means before first child e.insertBefore(e.getOwnerDocument().createTextNode("\n"), e.getFirstChild()); // indent before end-tag. It means just as last child e.appendChild(e.getOwnerDocument().createTextNode(currentIndent)); // we must get the nodelist again, because previous adding of childs broked // the old nodelist. Node n = e.getFirstChild(); while(n != null) { if(n.getNodeType() == Node.ELEMENT_NODE) { prettyLayoutRec((Element)n, currentIndent + " "); } n = n.getNextSibling(); } } // \n after end-tag Node text = e.getOwnerDocument().createTextNode("\n"); if(e.getNextSibling() == null) { if(e.getParentNode().getNodeType() != Node.DOCUMENT_NODE) { e.getParentNode().appendChild(text); } } else { e.getParentNode().insertBefore(text, e.getNextSibling()); } } }
gpl-3.0
TripleSnail/Arkhados
src/arkhados/spell/buffs/ArmorBuff.java
3184
/* This file is part of Arkhados. Arkhados is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Arkhados 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 Arkhados. If not, see <http://www.gnu.org/licenses/>. */ package arkhados.spell.buffs; import arkhados.controls.CInfluenceInterface; import com.jme3.math.FastMath; public class ArmorBuff extends AbstractBuff { private float amount; private final float protectionPercent; protected ArmorBuff(float amount, float protectionPercent, float duration, int stacks) { super(duration, stacks); this.amount = amount; this.protectionPercent = protectionPercent; } protected ArmorBuff(float amount, float protectionPercent, float duration) { this(amount, protectionPercent, duration, 1); } @Override public void attachToCharacter(CInfluenceInterface targetInterface) { ArmorBuff armorBuff = null; for (AbstractBuff buff : targetInterface.getBuffs()) { if (buff instanceof ArmorBuff && buff != this) { armorBuff = (ArmorBuff) buff; if (armorBuff.getProtectionPercent() != getProtectionPercent()) { armorBuff = null; } else { break; } } } if (armorBuff == null) { super.attachToCharacter(targetInterface); } else { float newAmount = FastMath.clamp(armorBuff.getAmount() + getAmount(), armorBuff.getAmount(), 100); armorBuff.setAmount(newAmount); } } public float mitigate(float damage) { float portion = damage * protectionPercent; float amountAbsorbed = FastMath.clamp(portion, 0, amount); damage -= amountAbsorbed; amount -= amountAbsorbed; return damage; } @Override public boolean shouldContinue() { return super.shouldContinue() && amount > 0; } public float getAmount() { return amount; } public float getProtectionPercent() { return protectionPercent; } public void setAmount(float amount) { this.amount = amount; } static public class MyBuilder extends AbstractBuffBuilder { private float amount; private float protectionPercent; public MyBuilder(float duration, float amount, float protectionPercent) { super(duration); this.amount = amount; this.protectionPercent = protectionPercent; } @Override public ArmorBuff build() { return set(new ArmorBuff(amount, protectionPercent, duration)); } } }
gpl-3.0
umarnobbee/Ripped-Pixel-Dungeon
src/com/ripped/pixeldungeon/levels/traps/AlarmTrap.java
1546
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.ripped.pixeldungeon.levels.traps; import com.ripped.pixeldungeon.Assets; import com.ripped.pixeldungeon.Dungeon; import com.ripped.pixeldungeon.actors.Char; import com.ripped.pixeldungeon.actors.mobs.Mob; import com.ripped.pixeldungeon.effects.CellEmitter; import com.ripped.pixeldungeon.effects.Speck; import com.ripped.pixeldungeon.utils.GLog; import com.watabou.noosa.audio.Sample; public class AlarmTrap { // 0xDD3333 public static void trigger( int pos, Char ch ) { for (Mob mob : Dungeon.level.mobs) { if (mob != ch) { mob.beckon( pos ); } } if (Dungeon.visible[pos]) { GLog.w( "The trap emits a piercing sound that echoes throughout the dungeon!" ); CellEmitter.center( pos ).start( Speck.factory( Speck.SCREAM ), 0.3f, 3 ); } Sample.INSTANCE.play( Assets.SND_ALERT ); } }
gpl-3.0
pantelis60/L2Scripts_Underground
dist/gameserver/data/scripts/ai/seedofannihilation/Taklacan.java
1148
package ai.seedofannihilation; import l2s.gameserver.ai.Fighter; import l2s.gameserver.model.instances.NpcInstance; // Если его ударить включается таймер 20 минут, если не убить его за 20 минут, он исчезает и появляеться на месте респавна через 5 минут с полным ХП. (за 2 мин до исчезновения появляеться надпись, что РБ готовится к исчезновению) // На территории РБ появляються каждые 2 минуты по 3-4 столба, которые стоят 30 секунд. Если подвести к одной из них, РБ получает дебаф, который снижает Физ. и Маг. Защ. РБ чуть ли не на 90%. Висит дебафф 30 секунд. // Ставит в паралич всех, кто ударит или прокинет дебафф на него, кроме самонов skill 6650. public class Taklacan extends Fighter { public Taklacan(NpcInstance actor) { super(actor); } }
gpl-3.0
joseoliv/Cyan
meta/cyanLang/CyanMetaobjectAttachedTypeRegex.java
3974
package meta.cyanLang; import java.util.List; import ast.AnnotationAt; import meta.AnnotationArgumentsKind; import meta.AttachedDeclarationKind; import meta.CyanMetaobject; import meta.CyanMetaobjectAtAnnot; import meta.IActionAttachedType_semAn; import meta.ICompiler_semAn; import meta.LeftHandSideKind; import meta.MetaHelper; import meta.WrAnnotationAt; import meta.WrExpr; import meta.WrExprLiteralString; import meta.WrType; import meta.WrTypeWithAnnotations; public class CyanMetaobjectAttachedTypeRegex extends CyanMetaobjectAtAnnot implements IActionAttachedType_semAn { public CyanMetaobjectAttachedTypeRegex() { super("regex", AnnotationArgumentsKind.OneOrMoreParameters, new AttachedDeclarationKind[] { AttachedDeclarationKind.TYPE }); } @Override public void check() { final List<Object> paramList = this.getAnnotation().getJavaParameterList(); if ( paramList.size() != 1 ) { this.addError("This metaobject should take two elements"); } final Object first = paramList.get(0); if ( !(first instanceof String)) { addError("The argument to attached type '" + this.getName() + "' should be a regular expression (String)"); } strPattern = MetaHelper.removeQuotes((String ) first); pattern = null; try { pattern = java.util.regex.Pattern.compile(strPattern); } catch ( final java.util.regex.PatternSyntaxException e ) { this.addError("The parameter to this attached metaobject, '" + strPattern + "' is not " + "a valid regular expression. See java.util.regex.Pattern"); } } @Override public StringBuffer semAn_checkLeftTypeChangeRightExpr(ICompiler_semAn compiler_semAn, WrType leftType, Object leftASTNode, LeftHandSideKind leftKind, WrType rightType, WrExpr rightExpr) { if ( rightExpr instanceof WrExprLiteralString ) { final String rightValue = MetaHelper.removeQuotes((String) ((WrExprLiteralString ) rightExpr).getJavaValue()); if ( ! pattern.matcher(rightValue).matches() ) { this.addError(rightExpr.getFirstSymbol(), "Expression '" + rightValue + "' does not match the regular expression '" + strPattern + "' that is attached to the type of the left-hand side of the assignment or equivalent"); } } else { if ( rightType instanceof WrTypeWithAnnotations ) { // Type rawRightType = ((TypeWithAnnotations ) rightType).getInsideType(); for ( final AnnotationAt annot : ((WrTypeWithAnnotations ) rightType).getAnnotationToTypeList() ) { if ( annot.getCyanMetaobject() instanceof CyanMetaobjectAttachedTypeRegex) { final CyanMetaobjectAttachedTypeRegex mom = (CyanMetaobjectAttachedTypeRegex ) annot.getCyanMetaobject(); if ( this.strPattern.equals(mom.strPattern) ) { return null; } } } } final StringBuffer sb = new StringBuffer(""); final String tmpVar = MetaHelper.nextIdentifier(); final String msg = "In line " + rightExpr.getFirstSymbol().getLineNumber() + " of file '" + CyanMetaobject.escapeString(compiler_semAn.getEnv().getCurrentCompilationUnit().getFullFileNamePath()) + "' String '" + rightExpr.asString() + "' did not match the regular expression '" + CyanMetaobject.escapeString(strPattern) + "'. Its value is '$" + tmpVar + "'"; sb.append("({ (: String " + tmpVar + " :) \r\n" + " if ! (RegExpr(\"" + strPattern + "\") ~= " + tmpVar + ") { \r\n" + " throw: ExceptionStr(\"" + msg + "\")\r\n" + " } \r\n" + " ^" + tmpVar + " \r\n" + " } eval: (" + rightExpr.asString() + ")) "); return sb; } return null; } @Override public void checkAnnotation() { final WrAnnotationAt annot = this.getAnnotation(); if ( ! "String".equals(annot.getTypeAttached().getName()) ) { this.addError("The metaobject annotation '" + getName() + "' can only be attached to prototype String"); } } private String strPattern; private java.util.regex.Pattern pattern; }
gpl-3.0
HellFirePvP/ModularMachinery
src/main/java/hellfirepvp/modularmachinery/common/tiles/TileItemInputBus.java
1946
/******************************************************************************* * HellFirePvP / Modular Machinery 2019 * * This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3. * The source code is available on github: https://github.com/HellFirePvP/ModularMachinery * For further details, see the License file there. ******************************************************************************/ package hellfirepvp.modularmachinery.common.tiles; import hellfirepvp.modularmachinery.common.block.prop.ItemBusSize; import hellfirepvp.modularmachinery.common.machine.IOType; import hellfirepvp.modularmachinery.common.machine.MachineComponent; import hellfirepvp.modularmachinery.common.tiles.base.MachineComponentTile; import hellfirepvp.modularmachinery.common.tiles.base.TileInventory; import hellfirepvp.modularmachinery.common.tiles.base.TileItemBus; import hellfirepvp.modularmachinery.common.util.IOInventory; import javax.annotation.Nullable; /** * This class is part of the Modular Machinery Mod * The complete source code for this mod can be found on github. * Class: TileItemInputBus * Created by HellFirePvP * Date: 07.07.2017 / 17:54 */ public class TileItemInputBus extends TileItemBus implements MachineComponentTile { public TileItemInputBus() {} public TileItemInputBus(ItemBusSize type) { super(type); } @Override public IOInventory buildInventory(TileInventory tile, int size) { int[] slots = new int[size]; for (int i = 0; i < size; i++) { slots[i] = i; } return new IOInventory(tile, slots, new int[] {}); } @Nullable @Override public MachineComponent provideComponent() { return new MachineComponent.ItemBus(IOType.INPUT) { @Override public IOInventory getContainerProvider() { return TileItemInputBus.this.inventory; } }; } }
gpl-3.0
dmrub/kiara-java
Benchmarks/ZerocIceProject/src/main/java/dfki/sb/zerociceproject/Main/_BenchmarkDisp.java
4872
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.5.1 // // <auto-generated> // // Generated from file `benchmark.ice' // // Warning: do not edit this file. // // </auto-generated> // package dfki.sb.zerociceproject.Main; public abstract class _BenchmarkDisp extends Ice.ObjectImpl implements Benchmark { protected void ice_copyStateFrom(Ice.Object __obj) throws java.lang.CloneNotSupportedException { throw new java.lang.CloneNotSupportedException(); } public static final String[] __ids = { "::Ice::Object", "::Main::Benchmark" }; public boolean ice_isA(String s) { return java.util.Arrays.binarySearch(__ids, s) >= 0; } public boolean ice_isA(String s, Ice.Current __current) { return java.util.Arrays.binarySearch(__ids, s) >= 0; } public String[] ice_ids() { return __ids; } public String[] ice_ids(Ice.Current __current) { return __ids; } public String ice_id() { return __ids[1]; } public String ice_id(Ice.Current __current) { return __ids[1]; } public static String ice_staticId() { return __ids[1]; } public final MarketData sendMarketData(MarketData marketDataArg) { return sendMarketData(marketDataArg, null); } public final QuoteRequest sendQuoteRequest(QuoteRequest quoteRequestArg) { return sendQuoteRequest(quoteRequestArg, null); } public static Ice.DispatchStatus ___sendMarketData(Benchmark __obj, IceInternal.Incoming __inS, Ice.Current __current) { __checkMode(Ice.OperationMode.Normal, __current.mode); IceInternal.BasicStream __is = __inS.startReadParams(); MarketData marketDataArg; marketDataArg = new MarketData(); marketDataArg.__read(__is); __inS.endReadParams(); MarketData __ret = __obj.sendMarketData(marketDataArg, __current); IceInternal.BasicStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); __ret.__write(__os); __inS.__endWriteParams(true); return Ice.DispatchStatus.DispatchOK; } public static Ice.DispatchStatus ___sendQuoteRequest(Benchmark __obj, IceInternal.Incoming __inS, Ice.Current __current) { __checkMode(Ice.OperationMode.Normal, __current.mode); IceInternal.BasicStream __is = __inS.startReadParams(); QuoteRequest quoteRequestArg; quoteRequestArg = new QuoteRequest(); quoteRequestArg.__read(__is); __inS.endReadParams(); QuoteRequest __ret = __obj.sendQuoteRequest(quoteRequestArg, __current); IceInternal.BasicStream __os = __inS.__startWriteParams(Ice.FormatType.DefaultFormat); __ret.__write(__os); __inS.__endWriteParams(true); return Ice.DispatchStatus.DispatchOK; } private final static String[] __all = { "ice_id", "ice_ids", "ice_isA", "ice_ping", "sendMarketData", "sendQuoteRequest" }; public Ice.DispatchStatus __dispatch(IceInternal.Incoming in, Ice.Current __current) { int pos = java.util.Arrays.binarySearch(__all, __current.operation); if(pos < 0) { throw new Ice.OperationNotExistException(__current.id, __current.facet, __current.operation); } switch(pos) { case 0: { return ___ice_id(this, in, __current); } case 1: { return ___ice_ids(this, in, __current); } case 2: { return ___ice_isA(this, in, __current); } case 3: { return ___ice_ping(this, in, __current); } case 4: { return ___sendMarketData(this, in, __current); } case 5: { return ___sendQuoteRequest(this, in, __current); } } assert(false); throw new Ice.OperationNotExistException(__current.id, __current.facet, __current.operation); } protected void __writeImpl(IceInternal.BasicStream __os) { __os.startWriteSlice(ice_staticId(), -1, true); __os.endWriteSlice(); } protected void __readImpl(IceInternal.BasicStream __is) { __is.startReadSlice(); __is.endReadSlice(); } public static final long serialVersionUID = 0L; }
gpl-3.0
rbuj/FreeRouting
src/main/java/net/freerouting/freeroute/board/Component.java
8862
/* * Copyright (C) 2014 Alfons Wirtz * website www.freerouting.net * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License at <http://www.gnu.org/licenses/> * for more details. * * Component.java * * Created on 27. Mai 2004, 07:23 */ package net.freerouting.freeroute.board; import java.util.Locale; import net.freerouting.freeroute.datastructures.UndoableObjects; import net.freerouting.freeroute.geometry.planar.IntPoint; import net.freerouting.freeroute.geometry.planar.Point; import net.freerouting.freeroute.geometry.planar.Vector; import net.freerouting.freeroute.library.Package; /** * Describes board components consisting of an array of pins und other stuff * like component keepouts. * * @author Alfons Wirtz */ @SuppressWarnings("serial") public class Component implements UndoableObjects.Storable, ObjectInfoPanel.Printable, java.io.Serializable { /** * The name of the component. */ public final String name; /** * The location of the component. */ private Point location; /** * The rotation of the library package of the component in degree */ private double rotation_in_degree; /** * Contains information for gate swapping and pin swapping, if != null */ private net.freerouting.freeroute.library.LogicalPart logical_part = null; /** * If false, the component will be placed on the back side of the board. */ private boolean on_front; /** * The library package of the component if it is placed on the component * side. */ private final Package lib_package_front; /** * The library package of the component if it is placed on the solder side. */ private final Package lib_package_back; /** * Internal generated unique identification number. */ public final int no; /** * If true, the component cannot be moved. */ public final boolean position_fixed; /** * Creates a new instance of Component with the input parameters. If * p_on_front is false, the component will be placed on the back side. */ Component(String p_name, Point p_location, double p_rotation_in_degree, boolean p_on_front, Package p_package_front, Package p_package_back, int p_no, boolean p_position_fixed) { name = p_name; location = p_location; rotation_in_degree = p_rotation_in_degree; while (this.rotation_in_degree >= 360) { this.rotation_in_degree -= 360; } while (this.rotation_in_degree < 0) { this.rotation_in_degree += 360; } on_front = p_on_front; lib_package_front = p_package_front; lib_package_back = p_package_back; no = p_no; position_fixed = p_position_fixed; } /** * Returns the location of this component. */ public Point get_location() { return location; } /** * Returns the rotation of this component in degree. */ public double get_rotation_in_degree() { return rotation_in_degree; } public boolean is_placed() { return location != null; } /** * If false, the component will be placed on the back side of the board. */ public boolean placed_on_front() { return this.on_front; } /** * Translates the location of this Component by p_p_vector. The Pins in the * board must be moved seperately. */ public void translate_by(Vector p_vector) { if (location != null) { location = location.translate_by(p_vector); } } /** * Turns this component by p_factor times 90 degree around p_pole. */ public void turn_90_degree(int p_factor, IntPoint p_pole) { if (p_factor == 0) { return; } this.rotation_in_degree += p_factor * 90; while (this.rotation_in_degree >= 360) { this.rotation_in_degree -= 360; } while (this.rotation_in_degree < 0) { this.rotation_in_degree += 360; } if (location != null) { this.location = this.location.turn_90_degree(p_factor, p_pole); } } /** * Rotates this component by p_angle_in_degree around p_pole. */ public void rotate(double p_angle_in_degree, IntPoint p_pole, boolean p_flip_style_rotate_first) { if (p_angle_in_degree == 0) { return; } double turn_angle = p_angle_in_degree; if (p_flip_style_rotate_first && !this.placed_on_front()) { // take care of the order of mirroring and rotating on the back side of the board turn_angle = 360 - p_angle_in_degree; } this.rotation_in_degree += turn_angle; while (this.rotation_in_degree >= 360) { this.rotation_in_degree -= 360; } while (this.rotation_in_degree < 0) { this.rotation_in_degree += 360; } if (location != null) { this.location = this.location.to_float().rotate(Math.toRadians(p_angle_in_degree), p_pole.to_float()).round(); } } /** * Changes the placement side of this component and mirrors it at the * vertical line through p_pole. */ public void change_side(IntPoint p_pole) { this.on_front = !this.on_front; this.location = this.location.mirror_vertical(p_pole); } /** * Compares 2 components by name. Useful for example to display components * in alphabetic order. */ @Override public int compareTo(Object p_other) { if (p_other instanceof Component) { return this.name.compareToIgnoreCase(((Component) p_other).name); } return 1; } /** * Creates a copy of this component. */ @Override public Component clone() throws CloneNotSupportedException { Component result = new Component(name, location, rotation_in_degree, on_front, lib_package_front, lib_package_back, no, position_fixed); result.logical_part = this.logical_part; return result; } @Override public String toString() { return this.name; } /** * Returns information for pin swap and gate swap, if != null. */ public net.freerouting.freeroute.library.LogicalPart get_logical_part() { return this.logical_part; } /** * Sets the infomation for pin swap and gate swap. */ public void set_logical_part(net.freerouting.freeroute.library.LogicalPart p_logical_part) { this.logical_part = p_logical_part; } @Override public void print_info(ObjectInfoPanel p_window) { java.util.ResourceBundle resources = java.util.ResourceBundle.getBundle("net.freerouting.freeroute.board.resources.ObjectInfoPanel", Locale.getDefault()); p_window.append_bold(resources.getString("component") + " "); p_window.append_bold(this.name); if (this.location != null) { p_window.append(" " + resources.getString("at") + " "); p_window.append(this.location.to_float()); p_window.append(", " + resources.getString("rotation") + " "); p_window.append_without_transforming(rotation_in_degree); if (this.on_front) { p_window.append(", " + resources.getString("front")); } else { p_window.append(", " + resources.getString("back")); } } else { p_window.append(" " + resources.getString("not_yet_placed")); } p_window.append(", " + resources.getString("package")); Package lib_package = this.get_package(); p_window.append(lib_package.name, resources.getString("package_info"), lib_package); if (this.logical_part != null) { p_window.append(", " + resources.getString("logical_part") + " "); p_window.append(this.logical_part.name, resources.getString("logical_part_info"), this.logical_part); } p_window.newline(); } /** * Returns the library package of this component. */ public Package get_package() { Package result; if (this.on_front) { result = lib_package_front; } else { result = lib_package_back; } return result; } }
gpl-3.0
ericpauley/NC-BukkitLib
src/com/nodinchan/ncbukkit/command/Executor.java
3160
package com.nodinchan.ncbukkit.command; import java.lang.reflect.Method; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import com.nodinchan.ncbukkit.command.info.Async; import com.nodinchan.ncbukkit.command.info.Permission; /* Copyright (C) 2012 Nodin Chan <nodinchan@live.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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public final class Executor { private final CommandBase command; private final Method method; private final CommandManager manager; private final String permission; private final boolean async; public Executor(CommandBase command, Method method, CommandManager manager) { this.command = command; this.method = method; this.manager = manager; this.async = method.isAnnotationPresent(Async.class); if (method.isAnnotationPresent(Permission.class)) permission = method.getAnnotation(Permission.class).value(); else permission = ""; } /** * Called when onCommand is called in the CommandManager * * @param sender The command sender * * @param args The given arguments * * @throws Exception */ public void execute(CommandSender sender, String[] args) throws Exception { if (!permission.equals("") && !sender.hasPermission(permission)) { command.noPermission(sender); return; } Class<?>[] parameters = method.getParameterTypes(); Object[] params = new Object[parameters.length]; if (sender instanceof Player) { if (parameters[0].isAssignableFrom(Player.class)) { params[0] = (Player) sender; } else { command.invalidSender(sender); return; } } else { if (parameters[0].isAssignableFrom(ConsoleCommandSender.class)) { params[0] = (ConsoleCommandSender) sender; } else { command.invalidSender(sender); return; } } for (int parameter = 1; parameter < parameters.length; parameter++) { try { params[parameter] = manager.castParameter(parameters[parameter], args[parameter - 1]); } catch (IndexOutOfBoundsException e) { break; } } method.invoke(command, params); } /** * Gets the permission required to use the sub-command * * @return The required permission */ public String getPermission() { return permission; } /** * Gets whether or not this command should be run in a separate thread, as signaled by the @Async notification * @return Whether or not threading should be used */ public boolean isAsync() { return async; } }
gpl-3.0
mksmbrtsh/timestatistic
app/src/main/java/maximsblog/blogspot/com/timestatistic/AboutFragment.java
893
package maximsblog.blogspot.com.timestatistic; import android.app.Fragment; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class AboutFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about,container, false); TextView t = (TextView) view.findViewById(R.id.note_text); t.setText(getResources().getText(R.string.about_text)); Linkify.addLinks(t, Linkify.ALL); t.setMovementMethod(LinkMovementMethod.getInstance()); return view; } public static AboutFragment newInstance() { AboutFragment fragment = new AboutFragment(); return fragment; } }
gpl-3.0
enoy19/keyboard-light-composer
keyboard-light-composer-application/src/main/java/org/enoy/klc/app/components/utils/ExternalMonitorUtil.java
1081
package org.enoy.klc.app.components.utils; import org.enoy.klc.control.external.ExternalValue; import org.enoy.klc.control.external.ExternalValueContainer; import org.enoy.klc.control.external.ExternalValueNamespace; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class ExternalMonitorUtil { public static List<ExternalMonitorObject> getObjects() { Map<ExternalValueNamespace, Set<ExternalValue<?>>> values = ExternalValueContainer.getInstance().getAll(); List<ExternalMonitorObject> objects = new ArrayList<>(values.size()); values.forEach((ns, s) -> { final String scope = ns.getScope(); final String identifier = ns.getIdentifier(); synchronized (s) { s.forEach(v -> { ExternalMonitorObject emo = new ExternalMonitorObject(); emo.setScope(scope); emo.setIdentifier(identifier); emo.setParameter(v.getParameter()); emo.setType(v.getDataType().getDataTypeId()); emo.setData(v.getData().toString()); objects.add(emo); }); } }); return objects; } }
gpl-3.0
tair/tairwebapp
src/org/tair/abrc/handler/PaymentInfoHandler.java
8431
// ----------------------------------------------------------------------- // Copyright (c) 2010 Carnegie Institution for Science. All rights reserved. // ----------------------------------------------------------------------- package org.tair.abrc.handler; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.naming.InitialContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.jboss.logging.Logger; import org.tair.abrc.order.Const; import org.tair.abrc.order.Payment; /** * Web application that handles CyberSource payments for ABRC stocks. The * application caches received payments in memory in a set for comparison to * avoid excessive querying of the database for repeated receipts of the same * payment information (potential for denial of service attack). * * @author Tom Meyer and Bob Muller */ public class PaymentInfoHandler extends HttpServlet { /** Serial version UID for Serializable class */ private static final long serialVersionUID = 1L; /** * The list of payments received from CyberSource so far since the web app was * started; cache to avoid querying the database unless necessary. */ private static Set<Payment> receivedPayments = new HashSet<Payment>(10); /** Logger for this class */ private static final Logger logger = Logger.getLogger(PaymentInfoHandler.class); /** The JNDI name for the database initialized once */ String jndiName; /** * Initialize the servlet with JNDI information. */ public void init(ServletConfig config) throws ServletException { jndiName = config.getInitParameter("jndiName"); logger.debug("Attempting to initialize parameterized JNDI name " + jndiName); if (jndiName == null) { jndiName = "java:jdbc/tair/Webwriter"; } logger.info("Initialized " + jndiName); } /** * Service the servlet request. */ public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int tries = 10; while (!saveInfo(req) && tries-- > 0) try { Thread.sleep(6000); } catch (InterruptedException e) { // Ignore and exit } // Print "done" to the output page. PrintWriter out = res.getWriter(); res.setContentType("text/plain"); out.println("done"); } /** * Save the payment information in the request. * * @param req the HTTP request containing payment information * @return true if information successfully received, false otherwise */ boolean saveInfo(HttpServletRequest req) { Map<?, ?> m = req.getParameterMap(); Map<String, String> info = new HashMap<String, String>(); for (Object k : m.keySet()) { Object v = m.get(k); if (k instanceof String && v instanceof String[] && ((String[])v).length > 0) info.put((String)k, ((String[])v)[0]); } info.put("pending_payment_token", req.getParameter("merchantDefinedData2")); logger.debug("Got pending payment token: " + req.getParameter("merchantDefinedData2")); return saveInfo(new Payment(info)); } /** * Save payment information to the database. * * @param info the payment information to save * @return true if information successfully received, false if not */ boolean saveInfo(Payment info) { Connection conn = null; // Exits with false if exception occurs boolean returnCode = false; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup(jndiName); conn = ds.getConnection(); boolean exists = receivedPayments.contains(info); // Insert the payment if not already in the database if (conn != null && !exists && !queryPayment(info, conn)) { insertPayment(info, conn); conn.commit(); } // Set the return to true to indicate successful completion. returnCode = true; } catch (Exception e) { // Log and ignore logger.error("Error while saving information: " + e.getMessage(), e); } finally { try { if (conn != null) { conn.close(); } } catch (Exception e) { // Log and ignore logger.error("Error closing JDBC connection", e); } } return returnCode; } /** * Insert a payment into the database. * * @param info the payment to insert * @param conn the SQL connection * @throws SQLException when there is a problem inserting the row */ private void insertPayment(Payment info, Connection conn) throws SQLException { String query; PreparedStatement stmt; query = "INSERT INTO " + Const.PAYMENT_INFO_TABLE + " (decision,decision_publicSignature,orderAmount,orderAmount_publicSignature,orderCurrency,orderCurrency_publicSignature,orderNumber,orderNumber_publicSignature,orderPage_requestToken,orderPage_transactionType,requestID,pending_payment_token) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; logger.debug("Inserting payment information to database"); logger.debug(query); logger.info("Inserting payment decision: " + info.decision + ", order number: " + info.orderNumber + ", token: " + info.pending_payment_token); stmt = conn.prepareStatement(query); stmt.setString(1, info.decision); stmt.setString(2, info.decision_publicSignature); stmt.setString(3, info.orderAmount); stmt.setString(4, info.orderAmount_publicSignature); stmt.setString(5, info.orderCurrency); stmt.setString(6, info.orderCurrency_publicSignature); stmt.setString(7, info.orderNumber); stmt.setString(8, info.orderNumber_publicSignature); stmt.setString(9, info.orderPage_requestToken); stmt.setString(10, info.orderPage_transactionType); stmt.setString(11, info.requestID); stmt.setString(12, info.pending_payment_token); stmt.executeUpdate(); stmt.close(); conn.commit(); } /** * Query a payment from payment information to see whether the payment is * already in the database. * * @param info the payment information * @param conn the SQL connection * @return true if the payment exists, false if not * @throws SQLException when there is a problem querying the database */ private boolean queryPayment(Payment info, Connection conn) throws SQLException { boolean exists = false; String query = null; PreparedStatement stmt = null; // Add the payment to the list of payments received. receivedPayments.add(info); // Query to see whether the payment is already saved. ResultSet rs; try { query = "SELECT * FROM " + Const.PAYMENT_INFO_TABLE + " WHERE decision = ? AND decision_publicSignature = ? AND " + "orderAmount = ? AND orderAmount_publicSignature = ? AND " + "orderCurrency = ? AND orderCurrency_publicSignature = ? AND " + "orderNumber = ? AND orderNumber_publicSignature = ? AND " + "orderPage_requestToken = ? AND orderPage_transactionType = ? AND " + "requestID = ? AND pending_payment_token = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, info.decision); stmt.setString(2, info.decision_publicSignature); stmt.setString(3, info.orderAmount); stmt.setString(4, info.orderAmount_publicSignature); stmt.setString(5, info.orderCurrency); stmt.setString(6, info.orderCurrency_publicSignature); stmt.setString(7, info.orderNumber); stmt.setString(8, info.orderNumber_publicSignature); stmt.setString(9, info.orderPage_requestToken); stmt.setString(10, info.orderPage_transactionType); stmt.setString(11, info.requestID); stmt.setString(12, info.pending_payment_token); rs = stmt.executeQuery(); exists = rs.next(); } finally { stmt.close(); // closes result set as well } return exists; } }
gpl-3.0
gysgogo/levetube
lib/src/main/java/com/google/android/exoplayer2/source/DynamicConcatenatingMediaSource.java
22608
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.com.google.android.exoplayer2.source; import android.util.Pair; import android.util.SparseIntArray; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ExoPlayer.ExoPlayerComponent; import com.google.android.exoplayer2.ExoPlayer.ExoPlayerMessage; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.upstream.Allocator; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Util; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; /** * Concatenates multiple {@link MediaSource}s. The list of {@link MediaSource}s can be modified * during playback. Access to this class is thread-safe. */ public final class DynamicConcatenatingMediaSource implements MediaSource, ExoPlayerComponent { private static final int MSG_ADD = 0; private static final int MSG_ADD_MULTIPLE = 1; private static final int MSG_REMOVE = 2; private static final int MSG_MOVE = 3; // Accessed on the app thread. private final List<MediaSource> mediaSourcesPublic; // Accessed on the playback thread. private final List<MediaSourceHolder> mediaSourceHolders; private final MediaSourceHolder query; private final Map<MediaPeriod, MediaSource> mediaSourceByMediaPeriod; private final List<DeferredMediaPeriod> deferredMediaPeriods; private ExoPlayer player; private Listener listener; private boolean preventListenerNotification; private int windowCount; private int periodCount; public DynamicConcatenatingMediaSource() { this.mediaSourceByMediaPeriod = new IdentityHashMap<>(); this.mediaSourcesPublic = new ArrayList<>(); this.mediaSourceHolders = new ArrayList<>(); this.deferredMediaPeriods = new ArrayList<>(1); this.query = new MediaSourceHolder(null, null, -1, -1, -1); } /** * Appends a {@link MediaSource} to the playlist. * * @param mediaSource The {@link MediaSource} to be added to the list. */ public synchronized void addMediaSource(MediaSource mediaSource) { addMediaSource(mediaSourcesPublic.size(), mediaSource); } /** * Adds a {@link MediaSource} to the playlist. * * @param index The index at which the new {@link MediaSource} will be inserted. This index must * be in the range of 0 &lt;= index &lt;= {@link #getSize()}. * @param mediaSource The {@link MediaSource} to be added to the list. */ public synchronized void addMediaSource(int index, MediaSource mediaSource) { Assertions.checkNotNull(mediaSource); Assertions.checkArgument(!mediaSourcesPublic.contains(mediaSource)); mediaSourcesPublic.add(index, mediaSource); if (player != null) { player.sendMessages(new ExoPlayerMessage(this, MSG_ADD, Pair.create(index, mediaSource))); } } /** * Appends multiple {@link MediaSource}s to the playlist. * * @param mediaSources A collection of {@link MediaSource}s to be added to the list. The media * sources are added in the order in which they appear in this collection. */ public synchronized void addMediaSources(Collection<MediaSource> mediaSources) { addMediaSources(mediaSourcesPublic.size(), mediaSources); } /** * Adds multiple {@link MediaSource}s to the playlist. * * @param index The index at which the new {@link MediaSource}s will be inserted. This index must * be in the range of 0 &lt;= index &lt;= {@link #getSize()}. * @param mediaSources A collection of {@link MediaSource}s to be added to the list. The media * sources are added in the order in which they appear in this collection. */ public synchronized void addMediaSources(int index, Collection<MediaSource> mediaSources) { for (MediaSource mediaSource : mediaSources) { Assertions.checkNotNull(mediaSource); Assertions.checkArgument(!mediaSourcesPublic.contains(mediaSource)); } mediaSourcesPublic.addAll(index, mediaSources); if (player != null && !mediaSources.isEmpty()) { player.sendMessages(new ExoPlayerMessage(this, MSG_ADD_MULTIPLE, Pair.create(index, mediaSources))); } } /** * Removes a {@link MediaSource} from the playlist. * * @param index The index at which the media source will be removed. This index must be in the * range of 0 &lt;= index &lt; {@link #getSize()}. */ public synchronized void removeMediaSource(int index) { mediaSourcesPublic.remove(index); if (player != null) { player.sendMessages(new ExoPlayerMessage(this, MSG_REMOVE, index)); } } /** * Moves an existing {@link MediaSource} within the playlist. * * @param currentIndex The current index of the media source in the playlist. This index must be * in the range of 0 &lt;= index &lt; {@link #getSize()}. * @param newIndex The target index of the media source in the playlist. This index must be in the * range of 0 &lt;= index &lt; {@link #getSize()}. */ public synchronized void moveMediaSource(int currentIndex, int newIndex) { if (currentIndex == newIndex) { return; } mediaSourcesPublic.add(newIndex, mediaSourcesPublic.remove(currentIndex)); if (player != null) { player.sendMessages(new ExoPlayerMessage(this, MSG_MOVE, Pair.create(currentIndex, newIndex))); } } /** * Returns the number of media sources in the playlist. */ public synchronized int getSize() { return mediaSourcesPublic.size(); } /** * Returns the {@link MediaSource} at a specified index. * * @param index A index in the range of 0 &lt;= index &lt;= {@link #getSize()}. * @return The {@link MediaSource} at this index. */ public synchronized MediaSource getMediaSource(int index) { return mediaSourcesPublic.get(index); } @Override public synchronized void prepareSource(ExoPlayer player, boolean isTopLevelSource, Listener listener) { this.player = player; this.listener = listener; preventListenerNotification = true; addMediaSourcesInternal(0, mediaSourcesPublic); preventListenerNotification = false; maybeNotifyListener(); } @Override public void maybeThrowSourceInfoRefreshError() throws IOException { for (MediaSourceHolder mediaSourceHolder : mediaSourceHolders) { mediaSourceHolder.mediaSource.maybeThrowSourceInfoRefreshError(); } } @Override public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator) { int mediaSourceHolderIndex = findMediaSourceHolderByPeriodIndex(id.periodIndex); MediaSourceHolder holder = mediaSourceHolders.get(mediaSourceHolderIndex); MediaPeriodId idInSource = new MediaPeriodId(id.periodIndex - holder.firstPeriodIndexInChild); MediaPeriod mediaPeriod; if (!holder.isPrepared) { mediaPeriod = new DeferredMediaPeriod(holder.mediaSource, idInSource, allocator); deferredMediaPeriods.add((DeferredMediaPeriod) mediaPeriod); } else { mediaPeriod = holder.mediaSource.createPeriod(idInSource, allocator); } mediaSourceByMediaPeriod.put(mediaPeriod, holder.mediaSource); return mediaPeriod; } @Override public void releasePeriod(MediaPeriod mediaPeriod) { MediaSource mediaSource = mediaSourceByMediaPeriod.get(mediaPeriod); mediaSourceByMediaPeriod.remove(mediaPeriod); if (mediaPeriod instanceof DeferredMediaPeriod) { deferredMediaPeriods.remove(mediaPeriod); ((DeferredMediaPeriod) mediaPeriod).releasePeriod(); } else { mediaSource.releasePeriod(mediaPeriod); } } @Override public void releaseSource() { for (MediaSourceHolder mediaSourceHolder : mediaSourceHolders) { mediaSourceHolder.mediaSource.releaseSource(); } } @Override @SuppressWarnings("unchecked") public void handleMessage(int messageType, Object message) throws ExoPlaybackException { preventListenerNotification = true; switch (messageType) { case MSG_ADD: { Pair<Integer, MediaSource> messageData = (Pair<Integer, MediaSource>) message; addMediaSourceInternal(messageData.first, messageData.second); break; } case MSG_ADD_MULTIPLE: { Pair<Integer, Collection<MediaSource>> messageData = (Pair<Integer, Collection<MediaSource>>) message; addMediaSourcesInternal(messageData.first, messageData.second); break; } case MSG_REMOVE: { removeMediaSourceInternal((Integer) message); break; } case MSG_MOVE: { Pair<Integer, Integer> messageData = (Pair<Integer, Integer>) message; moveMediaSourceInternal(messageData.first, messageData.second); break; } default: { throw new IllegalStateException(); } } preventListenerNotification = false; maybeNotifyListener(); } private void maybeNotifyListener() { if (!preventListenerNotification) { listener.onSourceInfoRefreshed( new ConcatenatedTimeline(mediaSourceHolders, windowCount, periodCount), null); } } private void addMediaSourceInternal(int newIndex, MediaSource newMediaSource) { final MediaSourceHolder newMediaSourceHolder; Object newUid = System.identityHashCode(newMediaSource); DeferredTimeline newTimeline = new DeferredTimeline(); if (newIndex > 0) { MediaSourceHolder previousHolder = mediaSourceHolders.get(newIndex - 1); newMediaSourceHolder = new MediaSourceHolder(newMediaSource, newTimeline, previousHolder.firstWindowIndexInChild + previousHolder.timeline.getWindowCount(), previousHolder.firstPeriodIndexInChild + previousHolder.timeline.getPeriodCount(), newUid); } else { newMediaSourceHolder = new MediaSourceHolder(newMediaSource, newTimeline, 0, 0, newUid); } correctOffsets(newIndex, newTimeline.getWindowCount(), newTimeline.getPeriodCount()); mediaSourceHolders.add(newIndex, newMediaSourceHolder); newMediaSourceHolder.mediaSource.prepareSource(player, false, new Listener() { @Override public void onSourceInfoRefreshed(Timeline newTimeline, Object manifest) { updateMediaSourceInternal(newMediaSourceHolder, newTimeline); } }); } private void addMediaSourcesInternal(int index, Collection<MediaSource> mediaSources) { for (MediaSource mediaSource : mediaSources) { addMediaSourceInternal(index++, mediaSource); } } private void updateMediaSourceInternal(MediaSourceHolder mediaSourceHolder, Timeline timeline) { if (mediaSourceHolder == null) { throw new IllegalArgumentException(); } DeferredTimeline deferredTimeline = mediaSourceHolder.timeline; if (deferredTimeline.getTimeline() == timeline) { return; } int windowOffsetUpdate = timeline.getWindowCount() - deferredTimeline.getWindowCount(); int periodOffsetUpdate = timeline.getPeriodCount() - deferredTimeline.getPeriodCount(); if (windowOffsetUpdate != 0 || periodOffsetUpdate != 0) { int index = findMediaSourceHolderByPeriodIndex(mediaSourceHolder.firstPeriodIndexInChild); correctOffsets(index + 1, windowOffsetUpdate, periodOffsetUpdate); } mediaSourceHolder.timeline = deferredTimeline.cloneWithNewTimeline(timeline); if (!mediaSourceHolder.isPrepared) { for (int i = deferredMediaPeriods.size() - 1; i >= 0; i--) { if (deferredMediaPeriods.get(i).mediaSource == mediaSourceHolder.mediaSource) { deferredMediaPeriods.get(i).createPeriod(); deferredMediaPeriods.remove(i); } } } mediaSourceHolder.isPrepared = true; maybeNotifyListener(); } private void removeMediaSourceInternal(int index) { MediaSourceHolder holder = mediaSourceHolders.get(index); mediaSourceHolders.remove(index); Timeline oldTimeline = holder.timeline; correctOffsets(index, -oldTimeline.getWindowCount(), -oldTimeline.getPeriodCount()); holder.mediaSource.releaseSource(); } private void moveMediaSourceInternal(int currentIndex, int newIndex) { int startIndex = Math.min(currentIndex, newIndex); int endIndex = Math.max(currentIndex, newIndex); int windowOffset = mediaSourceHolders.get(startIndex).firstWindowIndexInChild; int periodOffset = mediaSourceHolders.get(startIndex).firstPeriodIndexInChild; mediaSourceHolders.add(newIndex, mediaSourceHolders.remove(currentIndex)); for (int i = startIndex; i <= endIndex; i++) { MediaSourceHolder holder = mediaSourceHolders.get(i); holder.firstWindowIndexInChild = windowOffset; holder.firstPeriodIndexInChild = periodOffset; windowOffset += holder.timeline.getWindowCount(); periodOffset += holder.timeline.getPeriodCount(); } } private void correctOffsets(int startIndex, int windowOffsetUpdate, int periodOffsetUpdate) { windowCount += windowOffsetUpdate; periodCount += periodOffsetUpdate; for (int i = startIndex; i < mediaSourceHolders.size(); i++) { mediaSourceHolders.get(i).firstWindowIndexInChild += windowOffsetUpdate; mediaSourceHolders.get(i).firstPeriodIndexInChild += periodOffsetUpdate; } } private int findMediaSourceHolderByPeriodIndex(int periodIndex) { query.firstPeriodIndexInChild = periodIndex; int index = Collections.binarySearch(mediaSourceHolders, query); return index >= 0 ? index : -index - 2; } private static final class MediaSourceHolder implements Comparable<MediaSourceHolder> { public final MediaSource mediaSource; public final Object uid; public DeferredTimeline timeline; public int firstWindowIndexInChild; public int firstPeriodIndexInChild; public boolean isPrepared; public MediaSourceHolder(MediaSource mediaSource, DeferredTimeline timeline, int window, int period, Object uid) { this.mediaSource = mediaSource; this.timeline = timeline; this.firstWindowIndexInChild = window; this.firstPeriodIndexInChild = period; this.uid = uid; } @Override public int compareTo(MediaSourceHolder other) { return this.firstPeriodIndexInChild - other.firstPeriodIndexInChild; } } private static final class ConcatenatedTimeline extends AbstractConcatenatedTimeline { private final int windowCount; private final int periodCount; private final int[] firstPeriodInChildIndices; private final int[] firstWindowInChildIndices; private final Timeline[] timelines; private final int[] uids; private final SparseIntArray childIndexByUid; public ConcatenatedTimeline(Collection<MediaSourceHolder> mediaSourceHolders, int windowCount, int periodCount) { super(mediaSourceHolders.size()); this.windowCount = windowCount; this.periodCount = periodCount; int childCount = mediaSourceHolders.size(); firstPeriodInChildIndices = new int[childCount]; firstWindowInChildIndices = new int[childCount]; timelines = new Timeline[childCount]; uids = new int[childCount]; childIndexByUid = new SparseIntArray(); int index = 0; for (MediaSourceHolder mediaSourceHolder : mediaSourceHolders) { timelines[index] = mediaSourceHolder.timeline; firstPeriodInChildIndices[index] = mediaSourceHolder.firstPeriodIndexInChild; firstWindowInChildIndices[index] = mediaSourceHolder.firstWindowIndexInChild; uids[index] = (int) mediaSourceHolder.uid; childIndexByUid.put(uids[index], index++); } } @Override protected int getChildIndexByPeriodIndex(int periodIndex) { return Util.binarySearchFloor(firstPeriodInChildIndices, periodIndex, true, false); } @Override protected int getChildIndexByWindowIndex(int windowIndex) { return Util.binarySearchFloor(firstWindowInChildIndices, windowIndex, true, false); } @Override protected int getChildIndexByChildUid(Object childUid) { if (!(childUid instanceof Integer)) { return C.INDEX_UNSET; } int index = childIndexByUid.get((int) childUid, -1); return index == -1 ? C.INDEX_UNSET : index; } @Override protected Timeline getTimelineByChildIndex(int childIndex) { return timelines[childIndex]; } @Override protected int getFirstPeriodIndexByChildIndex(int childIndex) { return firstPeriodInChildIndices[childIndex]; } @Override protected int getFirstWindowIndexByChildIndex(int childIndex) { return firstWindowInChildIndices[childIndex]; } @Override protected Object getChildUidByChildIndex(int childIndex) { return uids[childIndex]; } @Override public int getWindowCount() { return windowCount; } @Override public int getPeriodCount() { return periodCount; } } private static final class DeferredTimeline extends Timeline { private static final Object DUMMY_ID = new Object(); private static final Period period = new Period(); private final Timeline timeline; private final Object replacedID; public DeferredTimeline() { timeline = null; replacedID = null; } private DeferredTimeline(Timeline timeline, Object replacedID) { this.timeline = timeline; this.replacedID = replacedID; } public DeferredTimeline cloneWithNewTimeline(Timeline timeline) { return new DeferredTimeline(timeline, replacedID == null && timeline.getPeriodCount() > 0 ? timeline.getPeriod(0, period, true).uid : replacedID); } public Timeline getTimeline() { return timeline; } @Override public int getWindowCount() { return timeline == null ? 1 : timeline.getWindowCount(); } @Override public Window getWindow(int windowIndex, Window window, boolean setIds, long defaultPositionProjectionUs) { return timeline == null // Dynamic window to indicate pending timeline updates. ? window.set(setIds ? DUMMY_ID : null, C.TIME_UNSET, C.TIME_UNSET, false, true, 0, C.TIME_UNSET, 0, 0, 0) : timeline.getWindow(windowIndex, window, setIds, defaultPositionProjectionUs); } @Override public int getPeriodCount() { return timeline == null ? 1 : timeline.getPeriodCount(); } @Override public Period getPeriod(int periodIndex, Period period, boolean setIds) { if (timeline == null) { return period.set(setIds ? DUMMY_ID : null, setIds ? DUMMY_ID : null, 0, C.TIME_UNSET, C.TIME_UNSET); } timeline.getPeriod(periodIndex, period, setIds); if (period.uid == replacedID) { period.uid = DUMMY_ID; } return period; } @Override public int getIndexOfPeriod(Object uid) { return timeline == null ? (uid == DUMMY_ID ? 0 : C.INDEX_UNSET) : timeline.getIndexOfPeriod(uid == DUMMY_ID ? replacedID : uid); } } private static final class DeferredMediaPeriod implements MediaPeriod, MediaPeriod.Callback { public final MediaSource mediaSource; private final MediaPeriodId id; private final Allocator allocator; private MediaPeriod mediaPeriod; private Callback callback; private long preparePositionUs; public DeferredMediaPeriod(MediaSource mediaSource, MediaPeriodId id, Allocator allocator) { this.id = id; this.allocator = allocator; this.mediaSource = mediaSource; } public void createPeriod() { mediaPeriod = mediaSource.createPeriod(id, allocator); if (callback != null) { mediaPeriod.prepare(this, preparePositionUs); } } public void releasePeriod() { if (mediaPeriod != null) { mediaSource.releasePeriod(mediaPeriod); } } @Override public void prepare(Callback callback, long preparePositionUs) { this.callback = callback; this.preparePositionUs = preparePositionUs; if (mediaPeriod != null) { mediaPeriod.prepare(this, preparePositionUs); } } @Override public void maybeThrowPrepareError() throws IOException { if (mediaPeriod != null) { mediaPeriod.maybeThrowPrepareError(); } else { mediaSource.maybeThrowSourceInfoRefreshError(); } } @Override public TrackGroupArray getTrackGroups() { return mediaPeriod.getTrackGroups(); } @Override public long selectTracks(TrackSelection[] selections, boolean[] mayRetainStreamFlags, SampleStream[] streams, boolean[] streamResetFlags, long positionUs) { return mediaPeriod.selectTracks(selections, mayRetainStreamFlags, streams, streamResetFlags, positionUs); } @Override public void discardBuffer(long positionUs) { mediaPeriod.discardBuffer(positionUs); } @Override public long readDiscontinuity() { return mediaPeriod.readDiscontinuity(); } @Override public long getBufferedPositionUs() { return mediaPeriod.getBufferedPositionUs(); } @Override public long seekToUs(long positionUs) { return mediaPeriod.seekToUs(positionUs); } @Override public long getNextLoadPositionUs() { return mediaPeriod.getNextLoadPositionUs(); } @Override public boolean continueLoading(long positionUs) { return mediaPeriod != null && mediaPeriod.continueLoading(positionUs); } @Override public void onContinueLoadingRequested(MediaPeriod source) { callback.onContinueLoadingRequested(this); } @Override public void onPrepared(MediaPeriod mediaPeriod) { callback.onPrepared(this); } } }
gpl-3.0
swift/stroke
test/com/isode/stroke/roster/XMPPRosterControllerTest.java
14473
/* * Copyright (c) 2010-2011 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2015 Tarun Gupta. * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ package com.isode.stroke.roster; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import com.isode.stroke.roster.XMPPRosterSignalHandler; import com.isode.stroke.roster.XMPPRosterController; import com.isode.stroke.roster.XMPPRosterImpl; import com.isode.stroke.roster.RosterMemoryStorage; import com.isode.stroke.elements.RosterItemPayload; import com.isode.stroke.elements.Payload; import com.isode.stroke.elements.RosterPayload; import com.isode.stroke.elements.IQ; import com.isode.stroke.client.DummyStanzaChannel; import com.isode.stroke.queries.IQRouter; import com.isode.stroke.jid.JID; import java.util.Collection; import java.util.ArrayList; public class XMPPRosterControllerTest { private DummyStanzaChannel channel_; private IQRouter router_; private XMPPRosterImpl xmppRoster_; private XMPPRosterSignalHandler handler_; private RosterMemoryStorage rosterStorage_; private JID jid1_; private JID jid2_; private JID jid3_; @Before public void setUp() { channel_ = new DummyStanzaChannel(); router_ = new IQRouter(channel_); router_.setJID(new JID("me@bla.com")); xmppRoster_ = new XMPPRosterImpl(); handler_ = new XMPPRosterSignalHandler(xmppRoster_); rosterStorage_ = new RosterMemoryStorage(); jid1_ = new JID("foo@bar.com"); jid2_ = new JID("alice@wonderland.lit"); jid3_ = new JID("jane@austen.lit"); } private XMPPRosterController createController() { return new XMPPRosterController(router_, xmppRoster_, rosterStorage_); } @Test public void testGet_Response() { XMPPRosterController testling = createController(); testling.requestRoster(); RosterPayload payload = new RosterPayload(); payload.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); payload.addItem(new RosterItemPayload(jid2_, "Alice", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createResult(new JID("foo@bar.com"), channel_.sentStanzas.get(0).getID(), payload)); assertEquals(2, handler_.getEventCount()); assertNotNull(xmppRoster_.getItem(jid1_)); assertNotNull(xmppRoster_.getItem(jid2_)); } @Test public void testGet_EmptyResponse() { XMPPRosterController controller = new XMPPRosterController(router_, xmppRoster_, rosterStorage_); controller.requestRoster(); channel_.onIQReceived.emit(IQ.createResult(new JID("baz@fum.com/dum"), channel_.sentStanzas.get(0).getID(), null)); } @Test public void testAdd() { XMPPRosterController controller = new XMPPRosterController(router_, xmppRoster_, rosterStorage_); RosterPayload payload = new RosterPayload(); payload.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "eou", payload)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); assertEquals(0, xmppRoster_.getGroupsForJID(jid1_).size()); assertTrue(xmppRoster_.containsJID(jid1_)); assertEquals("Bob", xmppRoster_.getNameForJID(jid1_)); } @Test public void testGet_NoRosterInStorage() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); testling.requestRoster(); RosterPayload roster = channel_.sentStanzas.get(0).getPayload(new RosterPayload()); assertNotNull(roster.getVersion()); assertEquals("", roster.getVersion()); } @Test public void testGet_NoVersionInStorage() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); rosterStorage_.setRoster(new RosterPayload()); testling.requestRoster(); RosterPayload roster = channel_.sentStanzas.get(0).getPayload(new RosterPayload()); assertNotNull(roster.getVersion()); assertEquals("", roster.getVersion()); } @Test public void testGet_VersionInStorage() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); RosterPayload payload = new RosterPayload(); payload.setVersion("foover"); rosterStorage_.setRoster(payload); testling.requestRoster(); RosterPayload roster = channel_.sentStanzas.get(0).getPayload(new RosterPayload()); assertNotNull(roster.getVersion()); assertEquals("foover", roster.getVersion()); } @Test public void testGet_ServerDoesNotSupportVersion() { XMPPRosterController testling = createController(); RosterPayload payload = new RosterPayload(); payload.setVersion("foover"); rosterStorage_.setRoster(payload); testling.requestRoster(); RosterPayload roster = channel_.sentStanzas.get(0).getPayload(new RosterPayload()); assertNull(roster.getVersion()); } @Test public void testGet_ResponseWithoutNewVersion() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); RosterPayload storedRoster = new RosterPayload(); storedRoster.setVersion("version10"); storedRoster.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); storedRoster.addItem(new RosterItemPayload(jid2_, "Alice", RosterItemPayload.Subscription.Both)); rosterStorage_.setRoster(storedRoster); testling.requestRoster(); channel_.onIQReceived.emit(IQ.createResult(new JID("foo@bar.com"), channel_.sentStanzas.get(0).getID(), null)); assertEquals(2, handler_.getEventCount()); assertNotNull(xmppRoster_.getItem(jid1_)); assertNotNull(xmppRoster_.getItem(jid2_)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid2_, handler_.getLastJID()); assertNotNull(rosterStorage_.getRoster()); assertNotNull(rosterStorage_.getRoster().getVersion()); assertEquals("version10", rosterStorage_.getRoster().getVersion()); assertNotNull(rosterStorage_.getRoster().getItem(jid1_)); assertNotNull(rosterStorage_.getRoster().getItem(jid2_)); } @Test public void testGet_ResponseWithNewVersion() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); RosterPayload storedRoster = new RosterPayload(); storedRoster.setVersion("version10"); storedRoster.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); rosterStorage_.setRoster(storedRoster); testling.requestRoster(); RosterPayload serverRoster = new RosterPayload(); serverRoster.setVersion("version12"); serverRoster.addItem(new RosterItemPayload(jid2_, "Alice", RosterItemPayload.Subscription.Both)); Collection<String> groups = new ArrayList<String>(); groups.add("foo"); groups.add("bar"); serverRoster.addItem(new RosterItemPayload(jid3_, "Rabbit", RosterItemPayload.Subscription.Both, groups)); channel_.onIQReceived.emit(IQ.createResult(new JID("foo@bar.com"), channel_.sentStanzas.get(0).getID(), serverRoster)); assertEquals(2, handler_.getEventCount()); assertNull(xmppRoster_.getItem(jid1_)); assertNotNull(xmppRoster_.getItem(jid2_)); assertNotNull(xmppRoster_.getItem(jid3_)); assertEquals(jid3_, handler_.getLastJID()); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertNotNull(rosterStorage_.getRoster()); assertNotNull(rosterStorage_.getRoster().getVersion()); assertEquals("version12", rosterStorage_.getRoster().getVersion()); assertNull(rosterStorage_.getRoster().getItem(jid1_)); assertNotNull(rosterStorage_.getRoster().getItem(jid2_)); assertNotNull(rosterStorage_.getRoster().getItem(jid3_)); assertEquals(2, rosterStorage_.getRoster().getItem(jid3_).getGroups().size()); } @Test public void testAddFromNonAccount() { XMPPRosterController testling = createController(); RosterPayload payload = new RosterPayload(); payload.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); IQ request = IQ.createRequest(IQ.Type.Set, new JID(), "eou", payload); request.setFrom(jid2_); channel_.onIQReceived.emit(request); assertEquals(XMPPRosterEvents.None, handler_.getLastEvent()); } @Test public void testModify() { XMPPRosterController controller = new XMPPRosterController(router_, xmppRoster_, rosterStorage_); RosterPayload payload1 = new RosterPayload(); payload1.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id1", payload1)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); handler_.reset(); RosterPayload payload2 = new RosterPayload(); payload2.addItem(new RosterItemPayload(jid1_, "Bob2", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id2", payload2)); assertEquals(XMPPRosterEvents.Update, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); assertEquals("Bob2", xmppRoster_.getNameForJID(jid1_)); } @Test public void testRemove() { XMPPRosterController controller = new XMPPRosterController(router_, xmppRoster_, rosterStorage_); RosterPayload payload1 = new RosterPayload(); payload1.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id1", payload1)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); handler_.reset(); RosterPayload payload2 = new RosterPayload(); payload2.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Remove)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id2", payload2)); assertFalse(xmppRoster_.containsJID(jid1_)); assertEquals(XMPPRosterEvents.Remove, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); } @Test public void testRemove_RosterStorageUpdated() { XMPPRosterController testling = createController(); testling.setUseVersioning(true); RosterPayload storedRoster = new RosterPayload(); storedRoster.setVersion("version10"); storedRoster.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); storedRoster.addItem(new RosterItemPayload(jid2_, "Alice", RosterItemPayload.Subscription.Both)); rosterStorage_.setRoster(storedRoster); testling.requestRoster(); channel_.onIQReceived.emit(IQ.createResult(new JID("foo@bar.com"), channel_.sentStanzas.get(0).getID(), null)); RosterPayload payload2 = new RosterPayload(); payload2.setVersion("version15"); payload2.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Remove)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id2", payload2)); assertNotNull(rosterStorage_.getRoster()); assertNotNull(rosterStorage_.getRoster().getVersion()); assertEquals("version15", rosterStorage_.getRoster().getVersion()); assertNull(rosterStorage_.getRoster().getItem(jid1_)); assertNotNull(rosterStorage_.getRoster().getItem(jid2_)); } @Test public void testMany() { XMPPRosterController controller = new XMPPRosterController(router_, xmppRoster_, rosterStorage_); RosterPayload payload1 = new RosterPayload(); payload1.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id1", payload1)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); handler_.reset(); RosterPayload payload2 = new RosterPayload(); payload2.addItem(new RosterItemPayload(jid2_, "Alice", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id2", payload2)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid2_, handler_.getLastJID()); handler_.reset(); RosterPayload payload3 = new RosterPayload(); payload3.addItem(new RosterItemPayload(jid1_, "Ernie", RosterItemPayload.Subscription.Both)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id3", payload3)); assertEquals(XMPPRosterEvents.Update, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); handler_.reset(); RosterPayload payload4 = new RosterPayload(); RosterItemPayload item = new RosterItemPayload(jid3_, "Jane", RosterItemPayload.Subscription.Both); String janesGroup = "Jane's Group"; item.addGroup(janesGroup); payload4.addItem(item); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id4", payload4)); assertEquals(XMPPRosterEvents.Add, handler_.getLastEvent()); assertEquals(jid3_, handler_.getLastJID()); assertEquals(1, xmppRoster_.getGroupsForJID(jid3_).size()); assertEquals(janesGroup, xmppRoster_.getGroupsForJID(jid3_).toArray()[0]); handler_.reset(); RosterPayload payload5 = new RosterPayload(); payload5.addItem(new RosterItemPayload(jid1_, "Bob", RosterItemPayload.Subscription.Remove)); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id5", payload5)); assertFalse(xmppRoster_.containsJID(jid1_)); assertEquals(XMPPRosterEvents.Remove, handler_.getLastEvent()); assertEquals(jid1_, handler_.getLastJID()); handler_.reset(); RosterPayload payload6 = new RosterPayload(); RosterItemPayload item2 = new RosterItemPayload(jid2_, "Little Alice", RosterItemPayload.Subscription.Both); String alicesGroup = "Alice's Group"; item2.addGroup(alicesGroup); payload6.addItem(item2); channel_.onIQReceived.emit(IQ.createRequest(IQ.Type.Set, new JID(), "id6", payload6)); assertEquals(XMPPRosterEvents.Update, handler_.getLastEvent()); assertEquals(jid2_, handler_.getLastJID()); assertEquals("Little Alice", xmppRoster_.getNameForJID(jid2_)); assertEquals("Jane", xmppRoster_.getNameForJID(jid3_)); assertEquals(1, xmppRoster_.getGroupsForJID(jid2_).size()); assertEquals(alicesGroup, xmppRoster_.getGroupsForJID(jid2_).toArray()[0]); assertEquals(1, xmppRoster_.getGroupsForJID(jid3_).size()); assertEquals(janesGroup, xmppRoster_.getGroupsForJID(jid3_).toArray()[0]); handler_.reset(); } }
gpl-3.0
BitRanger/comper
src/org/blacklancer/comper/XMLBeanAssembler.java
6784
/******************************************************************************* * Copyright (c) 2014 Cai Bowen, Zhou Liangpeng. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Cai Bowen, Zhou Liangpeng. - initial API and implementation ******************************************************************************/ package org.blacklancer.comper; import java.io.File; import java.io.InputStream; import java.io.Serializable; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; /** * Usage: * * 1. For Object * * Setters can only set bean, short/Short, int/Integer ... double/Double, Date * List<String>, * List<Object> * * For XML files: * * 1. bean inside property will not be added to factory, even an id is specified * and you cannot get it later * e.g. even there is an id="c++11" in a subBean, you cannot call getBean("c++11")// returns null; * * 3. top level bean without an id will be build, but will not be added to Ioc container. * * 4. addBean("id", obj) returns false if id already exists * * example * <bean id="course" class="model.Course"> <property name="courseName" value="Programming"/> <property name="referenceBook" ref="jcip"/> <property name="mainBooks"> <list> <bean id="c++11" class="model.Book"><!-- will not be registered in factory > <property name="name" value="the c++ programming Language"/> <property name="author" value="B.S."/> <property name="publisher"> <ref> publisher </ref> </property> </bean> <ref>someOtherBook</ref> </list> </property> </bean> */ /** * * @author BowenCai * * @version 1.0 * @since 2013-12-24 * */ public class XMLBeanAssembler extends XMLBeanAssemblerBase implements Serializable { private static final long serialVersionUID = 1895612360389006713L; /** * This is a compile flag. * When this flag is enabled,fields that do not have a correspondent setter * will be set directly, regardless of its qualifier. * * However, In some environment, e.g., Google App Engine, * you cannot reflect on private field on some classes * due to different security policy. * So it is recommanded that this flag is not open. * */ public static final boolean REFLECT_ON_PRIVATE = false; private static XMLBeanAssembler handle = null; private XMLBeanAssembler() {} synchronized public static XMLBeanAssembler getInstance() { if(handle == null) { handle = new XMLBeanAssembler(); } return handle; } public void assemble(@Nonnull final InputSource in) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(in); doc.getDocumentElement().normalize(); super.doAssemble(doc); Logger.getLogger(LOGGER_NAME).info("Created [" + podMap.size() + "] beans"); } @Override public void assemble(@Nonnull final InputStream in) throws Exception { assemble(new InputSource(in)); } @Override public void assemble(@Nonnull final File file) throws Exception{ assemble(new InputSource(file.toURI().toASCIIString())); } /** * @return null if not found or exception is thrown in creating non-singleton bean */ @SuppressWarnings("unchecked") @Nullable @Override public <T> T getBean(@Nonnull String id) { Pod pod = super.podMap.get(id); if (pod == null) { return null; } if (pod.isSingleton()) { Object bn = pod.getInstance(); if (bn == null) { super.podMap.remove(id); return null; } else { return (T)bn; } } else { try { return (T) buildBean(pod.getDescription()); } catch (Exception e) { throw new RuntimeException( "faild building non-singleton bean of id[" + id + "]", e); } } } @Nullable @Override public Pod getPod(@Nonnull String id) { return podMap.get(id); } @Override public Set<Object> getBeans(@Nonnull Class<?> clazz) { Set<Object> set = new HashSet<>(16); for (Pod pod : super.podMap.values()) { Object bean = pod.getInternal(); if (clazz.isInstance(bean)) { pod.addAge(1); set.add(bean); } } return set; } @Override public boolean contains(@Nonnull Class<?> clazz) { Set<Object> beans = getBeans(clazz); return beans != null && beans.size() > 0; } @Override public void removeBean(@Nonnull String id) { Pod pod = super.podMap.remove(id); if (pod != null) { try { pod.destroy(); } catch (Exception e) { throw new RuntimeException( "faild destroy bean of id[" + id + "]", e); } } } @Override public <T> void updateBean(@Nonnull String id, @Nonnull T bean) { Pod oldPod = super.podMap.get(id); if (oldPod == null || oldPod.getInstance() == null) { throw new NullPointerException("cannot find bean[" + id + "]"); } oldPod.setInstance(bean); super.podMap.put(id, oldPod); } @Override public boolean addBean(@Nonnull String id, @Nonnull Object bean) { return addBean(id, bean, Integer.MAX_VALUE); } /** * new bean must not be non-singleton */ @Override public boolean addBean(@Nonnull String id, @Nonnull Object bean, @Nonnull int lifeSpan) { if (contains(id)) { return false; } Pod pod = new Pod(id, null, bean, lifeSpan); super.podMap.put(id, pod); return true; } @Override public boolean contains(String id) { return null != super.podMap.get(id); } @Override public boolean isSingletion(String id) { Pod pod = super.podMap.get(id); if (pod != null) { return super.podMap.get(id).isSingleton(); } else { throw new NullPointerException("cannot find bean[" + id + "]"); } } /** * @param visitor * @throws Exception */ @Override public void inTake(IAssemlberVisitor visitor) { Exception ex = null; String id = null; for (Map.Entry<String, Pod> entry : super.podMap.entrySet()) { Pod pod = entry.getValue(); /** * create singleton bean */ try { visitor.visit(getBean(pod.getBeanId())); } catch (Exception e) { /** * continue visiting. * log only the first exception. */ if (ex != null) { ex = e; id = pod.getBeanId(); } } } if (ex != null) { throw new RuntimeException( "exception when visiting bean of id[" + id + "]", ex); } } }
gpl-3.0
ssoloff/triplea-game-triplea
game-core/src/main/java/games/strategy/engine/data/GameParser.java
63165
package games.strategy.engine.data; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import games.strategy.engine.ClientContext; import games.strategy.engine.data.gameparser.XmlGameElementMapper; import games.strategy.engine.data.properties.BooleanProperty; import games.strategy.engine.data.properties.ColorProperty; import games.strategy.engine.data.properties.ComboProperty; import games.strategy.engine.data.properties.FileProperty; import games.strategy.engine.data.properties.GameProperties; import games.strategy.engine.data.properties.IEditableProperty; import games.strategy.engine.data.properties.NumberProperty; import games.strategy.engine.data.properties.StringProperty; import games.strategy.engine.delegate.IDelegate; import games.strategy.triplea.Constants; import games.strategy.triplea.attachments.TechAbilityAttachment; import games.strategy.triplea.attachments.TerritoryAttachment; import games.strategy.triplea.attachments.UnitAttachment; import games.strategy.triplea.delegate.GenericTechAdvance; import games.strategy.triplea.delegate.TechAdvance; import games.strategy.triplea.formatter.MyFormatter; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.extern.java.Log; import org.triplea.util.Tuple; import org.triplea.util.Version; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXParseException; /** Parses a game XML file into a {@link GameData} domain object. */ @Log public final class GameParser { private static final String RESOURCE_IS_DISPLAY_FOR_NONE = "NONE"; @Nonnull private final GameData data; private final Collection<SAXParseException> errorsSax = new ArrayList<>(); private final String mapName; private final XmlGameElementMapper xmlGameElementMapper; private final GameDataVariableParser variableParser = new GameDataVariableParser(); private final NodeFinder nodeFinder = new NodeFinder(); @VisibleForTesting GameParser(final GameData gameData, final String mapName) { this(gameData, mapName, new XmlGameElementMapper()); } private GameParser( final GameData gameData, final String mapName, final XmlGameElementMapper xmlGameElementMapper) { data = Preconditions.checkNotNull(gameData); this.mapName = mapName; this.xmlGameElementMapper = xmlGameElementMapper; } /** * Performs a deep parse of the game definition contained in the specified stream. * * @return A complete {@link GameData} instance that can be used to play the game. */ @Nonnull public static GameData parse(final String mapName, final InputStream stream) throws GameParseException, EngineVersionException { return parse(mapName, stream, new XmlGameElementMapper()); } @Nonnull @VisibleForTesting public static GameData parse( final String mapName, final InputStream stream, final XmlGameElementMapper xmlGameElementMapper) throws GameParseException, EngineVersionException { checkNotNull(mapName); checkNotNull(stream); checkNotNull(xmlGameElementMapper); return new GameParser(new GameData(), mapName, xmlGameElementMapper).parse(stream); } @Nonnull private GameData parse(final InputStream stream) throws GameParseException, EngineVersionException { final Element root = XmlReader.parseDom(mapName, stream, errorsSax); parseMapProperties(root); parseMapDetails(root); return data; } private GameParseException newGameParseException(final String message) { return newGameParseException(message, null); } private GameParseException newGameParseException( final String message, final @Nullable Throwable cause) { final String gameName = data.getGameName() != null ? data.getGameName() : "<unknown>"; return new GameParseException( String.format("map name: '%s', game name: '%s', %s", mapName, gameName, message), cause); } /** * Performs a shallow parse of the game definition contained in the specified stream. * * @return A partial {@link GameData} instance that can be used to display metadata about the game * (e.g. when displaying all available maps); it cannot be used to play the game. */ @Nonnull public static GameData parseShallow(final String mapName, final InputStream stream) throws GameParseException, EngineVersionException { checkNotNull(mapName); checkNotNull(stream); return new GameParser(new GameData(), mapName).parseShallow(stream); } @Nonnull private GameData parseShallow(final InputStream stream) throws GameParseException, EngineVersionException { final Element root = XmlReader.parseDom(mapName, stream, errorsSax); parseMapProperties(root); return data; } private void parseMapProperties(final Element root) throws GameParseException, EngineVersionException { // mandatory fields // get the name of the map parseInfo(getSingleChild("info", root)); // test minimum engine version FIRST parseMinimumEngineVersionNumber(getSingleChild("triplea", root, true)); // if we manage to get this far, past the minimum engine version number test, AND we are still // good, then check and // see if we have any SAX errors we need to show if (!errorsSax.isEmpty()) { for (final SAXParseException error : errorsSax) { log.severe( "SAXParseException: game: " + (data.getGameName() == null ? "?" : data.getGameName()) + ", line: " + error.getLineNumber() + ", column: " + error.getColumnNumber() + ", error: " + error.getMessage()); } } parseDiceSides(getSingleChild("diceSides", root, true)); final Element playerListNode = getSingleChild("playerList", root); parsePlayerList(playerListNode); parseAlliances(playerListNode); final Node properties = getSingleChild("propertyList", root, true); if (properties != null) { parseProperties(properties); } } private void parseMapDetails(final Element root) throws GameParseException { final Map<String, List<String>> variables = variableParser.parseVariables(root); parseMap(getSingleChild("map", root)); final Element resourceList = getSingleChild("resourceList", root, true); if (resourceList != null) { parseResources(resourceList); } final Element unitList = getSingleChild("unitList", root, true); if (unitList != null) { parseUnits(unitList); } // Parse all different relationshipTypes that are defined in the xml, for example: War, Allied, // Neutral, NAP final Element relationshipTypes = getSingleChild("relationshipTypes", root, true); if (relationshipTypes != null) { parseRelationshipTypes(relationshipTypes); } final Element territoryEffectList = getSingleChild("territoryEffectList", root, true); if (territoryEffectList != null) { parseTerritoryEffects(territoryEffectList); } parseGamePlay(getSingleChild("gamePlay", root)); final Element production = getSingleChild("production", root, true); if (production != null) { parseProduction(production); } final Element technology = getSingleChild("technology", root, true); if (technology != null) { parseTechnology(technology); } else { TechAdvance.createDefaultTechAdvances(data); } final Element attachmentList = getSingleChild("attachmentList", root, true); if (attachmentList != null) { parseAttachments(attachmentList, variables); } final Node initialization = getSingleChild("initialize", root, true); if (initialization != null) { parseInitialization(initialization); } // set & override default relationships // sets the relationship between all players and the NullPlayer to NullRelation (with archeType // War) data.getRelationshipTracker().setNullPlayerRelations(); // sets the relationship for all players with themselves to the SelfRelation (with archeType // Allied) data.getRelationshipTracker().setSelfRelations(); // set default tech attachments (comes after we parse all technologies, parse all attachments, // and parse all game // options/properties) checkThatAllUnitsHaveAttachments(data); TechAbilityAttachment.setDefaultTechnologyAttachments(data); try { validate(); } catch (final Exception e) { log.log(Level.SEVERE, "Error parsing: " + mapName, e); throw newGameParseException("validation failed", e); } } private void parseDiceSides(final Node diceSides) { if (diceSides == null) { data.setDiceSides(6); } else { data.setDiceSides(Integer.parseInt(((Element) diceSides).getAttribute("value"))); } } private void parseMinimumEngineVersionNumber(final Node minimumVersion) throws EngineVersionException { if (minimumVersion == null) { return; } final Version mapMinimumEngineVersion = new Version(((Element) minimumVersion).getAttribute("minimumVersion")); if (!ClientContext.engineVersion() .isCompatibleWithMapMinimumEngineVersion(mapMinimumEngineVersion)) { throw new EngineVersionException( String.format( "Current engine version: %s, is not compatible with version: %s, required by map: %s", ClientContext.engineVersion(), mapMinimumEngineVersion.toString(), data.getGameName())); } } private void validate() throws GameParseException { // validate unit attachments for (final UnitType u : data.getUnitTypeList()) { validateAttachments(u); } for (final Territory t : data.getMap()) { validateAttachments(t); } for (final Resource r : data.getResourceList().getResources()) { validateAttachments(r); } for (final PlayerId r : data.getPlayerList().getPlayers()) { validateAttachments(r); } for (final RelationshipType r : data.getRelationshipTypeList().getAllRelationshipTypes()) { validateAttachments(r); } for (final TerritoryEffect r : data.getTerritoryEffectList().values()) { validateAttachments(r); } for (final TechAdvance r : data.getTechnologyFrontier().getTechs()) { validateAttachments(r); } // if relationships are used, every player should have a relationship with every other player validateRelationships(); } private void validateRelationships() throws GameParseException { // for every player for (final PlayerId player : data.getPlayerList()) { // in relation to every player for (final PlayerId player2 : data.getPlayerList()) { // See if there is a relationship between them if ((data.getRelationshipTracker().getRelationshipType(player, player2) == null)) { // or else throw an exception! throw newGameParseException( "No relation set for: " + player.getName() + " and " + player2.getName()); } } } } private void validateAttachments(final Attachable attachable) throws GameParseException { for (final IAttachment a : attachable.getAttachments().values()) { a.validate(data); } } private <T> T getValidatedObject( final Element element, final String attribute, final boolean mustFind, final Function<String, T> function, final String errorName) throws GameParseException { final String name = element.getAttribute(attribute); return getValidatedObject(name, mustFind, function, errorName); } private <T> T getValidatedObject( final String name, final boolean mustFind, final Function<String, T> function, final String errorName) throws GameParseException { final T attachable = function.apply(name); if (attachable == null && mustFind) { throw newGameParseException("Could not find " + errorName + ". name:" + name); } return attachable; } private PlayerId getPlayerId(final String name) throws GameParseException { return getValidatedObject(name, true, data.getPlayerList()::getPlayerId, "player"); } /** If mustfind is true and cannot find the player an exception will be thrown. */ private PlayerId getPlayerId( final Element element, final String attribute, final boolean mustFind) throws GameParseException { return getValidatedObject( element, attribute, mustFind, data.getPlayerList()::getPlayerId, "player"); } private RelationshipType getRelationshipType(final String name) throws GameParseException { return getValidatedObject( name, true, data.getRelationshipTypeList()::getRelationshipType, "relation"); } /** * If cannot find the player an exception will be thrown. * * @return a RelationshipType from the relationshipTypeList, at this point all relationshipTypes * should have been declared */ private RelationshipType getRelationshipType(final Element element, final String attribute) throws GameParseException { return getValidatedObject( element, attribute, true, data.getRelationshipTypeList()::getRelationshipType, "relation"); } private TerritoryEffect getTerritoryEffect(final String name) throws GameParseException { return getValidatedObject(name, true, data.getTerritoryEffectList()::get, "territoryEffect"); } /** If cannot find the productionRule an exception will be thrown. */ private ProductionRule getProductionRule(final Element element) throws GameParseException { return getValidatedObject( element, "name", true, data.getProductionRuleList()::getProductionRule, "production rule"); } /** If cannot find the repairRule an exception will be thrown. */ private RepairRule getRepairRule(final Element element) throws GameParseException { return getValidatedObject( element, "name", true, data.getRepairRules()::getRepairRule, "repair rule"); } private Territory getTerritory(final String name) throws GameParseException { return getValidatedObject(name, true, data.getMap()::getTerritory, "territory"); } /** If cannot find the territory an exception will be thrown. */ private Territory getTerritory(final Element element, final String attribute) throws GameParseException { return getValidatedObject(element, attribute, true, data.getMap()::getTerritory, "territory"); } private UnitType getUnitType(final String name) throws GameParseException { return getValidatedObject(name, true, data.getUnitTypeList()::getUnitType, "unitType"); } /** If mustfind is true and cannot find the unitType an exception will be thrown. */ private UnitType getUnitType( final Element element, final String attribute, final boolean mustFind) throws GameParseException { return getValidatedObject( element, attribute, mustFind, data.getUnitTypeList()::getUnitType, "unitType"); } private TechAdvance getTechnology(final String name) throws GameParseException { return getValidatedObject(name, true, this::getTechnologyFromFrontier, "technology"); } private TechAdvance getTechnologyFromFrontier(final String name) { final TechnologyFrontier frontier = data.getTechnologyFrontier(); TechAdvance type = frontier.getAdvanceByName(name); if (type == null) { type = frontier.getAdvanceByProperty(name); } return type; } /** If cannot find the Delegate an exception will be thrown. */ private IDelegate getDelegate(final Element element) throws GameParseException { return getValidatedObject(element, "delegate", true, data::getDelegate, "delegate"); } private Resource getResource(final String name) throws GameParseException { return getValidatedObject(name, true, data.getResourceList()::getResource, "resource"); } /** If mustfind is true and cannot find the Resource an exception will be thrown. */ private Resource getResource( final Element element, final String attribute, final boolean mustFind) throws GameParseException { return getValidatedObject( element, attribute, mustFind, data.getResourceList()::getResource, "resource"); } /** If cannot find the productionRule an exception will be thrown. */ private ProductionFrontier getProductionFrontier(final Element element) throws GameParseException { return getValidatedObject( element, "frontier", true, data.getProductionFrontierList()::getProductionFrontier, "production frontier"); } /** If cannot find the repairFrontier an exception will be thrown. */ private RepairFrontier getRepairFrontier(final Element element) throws GameParseException { return getValidatedObject( element, "frontier", true, data.getRepairFrontierList()::getRepairFrontier, "repair frontier"); } /** Get the given child. If there is not exactly one child throws a GameParseException */ private Element getSingleChild(final String name, final Element node) throws GameParseException { return nodeFinder.getSingleChild(name, node); } /** If optional is true, will not throw an exception if there are 0 children. */ private Element getSingleChild(final String name, final Node node, final boolean optional) throws GameParseException { if (optional) { return nodeFinder.getOptionalSingleChild(name, node); } return nodeFinder.getSingleChild(name, node); } private List<Element> getChildren(final String name, final Node node) { return nodeFinder.getChildren(name, node); } private static List<Node> getNonTextNodesIgnoringValue(final Node node) { final List<Node> nonTextNodes = getNonTextNodes(node); nonTextNodes.removeIf(node1 -> ((Element) node1).getTagName().equals("value")); return nonTextNodes; } private static List<Node> getNonTextNodes(final Node node) { final NodeList children = node.getChildNodes(); return IntStream.range(0, children.getLength()) .mapToObj(children::item) .filter(current -> !(current.getNodeType() == Node.TEXT_NODE)) .collect(Collectors.toList()); } private void parseInfo(final Node info) { final String gameName = ((Element) info).getAttribute("name"); data.setGameName(gameName); final String version = ((Element) info).getAttribute("version"); data.setGameVersion(new Version(version)); } private void parseMap(final Node map) throws GameParseException { final List<Element> grids = getChildren("grid", map); parseGrids(grids); // get the Territories final List<Element> territories = getChildren("territory", map); parseTerritories(territories); final List<Element> connections = getChildren("connection", map); parseConnections(connections); } private void parseGrids(final List<Element> grids) throws GameParseException { for (final Element current : grids) { final String gridType = current.getAttribute("type"); final String name = current.getAttribute("name"); final String xs = current.getAttribute("x"); final String ys = current.getAttribute("y"); final List<Element> waterNodes = getChildren("water", current); final Set<String> water = parseGridWater(waterNodes); final String horizontalConnections = current.getAttribute("horizontal-connections"); final String verticalConnections = current.getAttribute("vertical-connections"); final String diagonalConnections = current.getAttribute("diagonal-connections"); setGrids( data, gridType, name, xs, ys, water, horizontalConnections, verticalConnections, diagonalConnections); } } /** Creates and adds new territories and their connections to their map, based on a grid. */ private void setGrids( final GameData data, final String gridType, final String name, final String xs, final String ys, final Set<String> water, final String horizontalConnections, final String verticalConnections, final String diagonalConnections) throws GameParseException { final GameMap map = data.getMap(); final boolean horizontalConnectionsImplicit; switch (horizontalConnections) { case "implicit": horizontalConnectionsImplicit = true; break; case "explicit": horizontalConnectionsImplicit = false; break; default: throw newGameParseException( "horizontal-connections attribute must be either \"explicit\" or \"implicit\""); } final boolean verticalConnectionsImplicit; switch (verticalConnections) { case "implicit": verticalConnectionsImplicit = true; break; case "explicit": verticalConnectionsImplicit = false; break; default: throw newGameParseException( "vertical-connections attribute must be either \"explicit\" or \"implicit\""); } final boolean diagonalConnectionsImplicit; switch (diagonalConnections) { case "implicit": diagonalConnectionsImplicit = true; break; case "explicit": diagonalConnectionsImplicit = false; break; default: throw newGameParseException( "diagonal-connections attribute must be either \"explicit\" or \"implicit\""); } final int sizeY = (ys != null) ? Integer.parseInt(ys) : 0; final int sizeX = Integer.parseInt(xs); map.setGridDimensions(sizeX, sizeY); if (gridType.equals("square")) { // Add territories for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { final boolean isWater = water.contains(x + "-" + y); map.addTerritory(new Territory(name + "_" + x + "_" + y, isWater, data)); } } // Add any implicit horizontal connections if (horizontalConnectionsImplicit) { for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX - 1; x++) { map.addConnection( map.getTerritoryFromCoordinates(x, y), map.getTerritoryFromCoordinates(x + 1, y)); } } } // Add any implicit vertical connections if (verticalConnectionsImplicit) { for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY - 1; y++) { map.addConnection( map.getTerritoryFromCoordinates(x, y), map.getTerritoryFromCoordinates(x, y + 1)); } } } // Add any implicit acute diagonal connections if (diagonalConnectionsImplicit) { for (int y = 0; y < sizeY - 1; y++) { for (int x = 0; x < sizeX - 1; x++) { map.addConnection( map.getTerritoryFromCoordinates(x, y), map.getTerritoryFromCoordinates(x + 1, y + 1)); } } } // Add any implicit obtuse diagonal connections if (diagonalConnectionsImplicit) { for (int y = 0; y < sizeY - 1; y++) { for (int x = 1; x < sizeX; x++) { map.addConnection( map.getTerritoryFromCoordinates(x, y), map.getTerritoryFromCoordinates(x - 1, y + 1)); } } } // This type is a triangular grid of points and lines, used for in several rail games } else if (gridType.equals("points-and-lines")) { // Add territories for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { if (!water.contains(x + "-" + y)) { final boolean isWater = false; map.addTerritory(new Territory(name + "_" + x + "_" + y, isWater, data)); } } } // Add any implicit horizontal connections if (horizontalConnectionsImplicit) { for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX - 1; x++) { final Territory from = map.getTerritoryFromCoordinates(x, y); final Territory to = map.getTerritoryFromCoordinates(x + 1, y); if (from != null && to != null) { map.addConnection(from, to); } } } } // Add any implicit acute diagonal connections if (diagonalConnectionsImplicit) { for (int y = 1; y < sizeY; y++) { for (int x = 0; x < sizeX - 1; x++) { if (y % 4 == 0 || (y + 1) % 4 == 0) { final Territory from = map.getTerritoryFromCoordinates(x, y); final Territory to = map.getTerritoryFromCoordinates(x, y - 1); if (from != null && to != null) { map.addConnection(from, to); } } else { final Territory from = map.getTerritoryFromCoordinates(x, y); final Territory to = map.getTerritoryFromCoordinates(x + 1, y - 1); if (from != null && to != null) { map.addConnection(from, to); } } } } } // Add any implicit obtuse diagonal connections if (diagonalConnectionsImplicit) { for (int y = 1; y < sizeY; y++) { for (int x = 0; x < sizeX - 1; x++) { if (y % 4 == 0 || (y + 1) % 4 == 0) { final Territory from = map.getTerritoryFromCoordinates(x, y); final Territory to = map.getTerritoryFromCoordinates(x - 1, y - 1); if (from != null && to != null) { map.addConnection(from, to); } } else { final Territory from = map.getTerritoryFromCoordinates(x, y); final Territory to = map.getTerritoryFromCoordinates(x, y - 1); if (from != null && to != null) { map.addConnection(from, to); } } } } } } } private static Set<String> parseGridWater(final List<Element> waterNodes) { final Set<String> set = new HashSet<>(); for (final Element current : waterNodes) { final int x = Integer.parseInt(current.getAttribute("x")); final int y = Integer.parseInt(current.getAttribute("y")); set.add(x + "-" + y); } return set; } private void parseTerritories(final List<Element> territories) { final GameMap map = data.getMap(); for (final Element current : territories) { final boolean water = current.getAttribute("water").trim().equalsIgnoreCase("true"); final String name = current.getAttribute("name"); final Territory newTerritory = new Territory(name, water, data); map.addTerritory(newTerritory); } } private void parseConnections(final List<Element> connections) throws GameParseException { final GameMap map = data.getMap(); for (final Element current : connections) { final Territory t1 = getTerritory(current, "t1"); final Territory t2 = getTerritory(current, "t2"); map.addConnection(t1, t2); } } private void parseResources(final Element root) throws GameParseException { for (final Element element : getChildren("resource", root)) { final String name = element.getAttribute("name"); final String isDisplayedFor = element.getAttribute("isDisplayedFor"); if (isDisplayedFor.isEmpty()) { data.getResourceList() .addResource(new Resource(name, data, data.getPlayerList().getPlayers())); } else if (isDisplayedFor.equalsIgnoreCase(RESOURCE_IS_DISPLAY_FOR_NONE)) { data.getResourceList().addResource(new Resource(name, data)); } else { data.getResourceList() .addResource(new Resource(name, data, parsePlayersFromIsDisplayedFor(isDisplayedFor))); } } } @VisibleForTesting List<PlayerId> parsePlayersFromIsDisplayedFor(final String encodedPlayerNames) throws GameParseException { final List<PlayerId> players = new ArrayList<>(); for (final String playerName : Splitter.on(':').split(encodedPlayerNames)) { final @Nullable PlayerId player = data.getPlayerList().getPlayerId(playerName); if (player == null) { throw newGameParseException("Parse resources could not find player: " + playerName); } players.add(player); } return players; } private void parseRelationshipTypes(final Element root) { getChildren("relationshipType", root).stream() .map(e -> e.getAttribute("name")) .map(name -> new RelationshipType(name, data)) .forEach(data.getRelationshipTypeList()::addRelationshipType); } private void parseTerritoryEffects(final Element root) { getChildren("territoryEffect", root).stream() .map(e -> e.getAttribute("name")) .forEach(name -> data.getTerritoryEffectList().put(name, new TerritoryEffect(name, data))); } private void parseUnits(final Element root) { getChildren("unit", root).stream() .map(e -> e.getAttribute("name")) .map(name -> new UnitType(name, data)) .forEach(data.getUnitTypeList()::addUnitType); } private void parsePlayerList(final Element root) { final PlayerList playerList = data.getPlayerList(); for (final Element current : getChildren("player", root)) { final String name = current.getAttribute("name"); // It appears the commented line ALWAYS returns false regardless of the value of // current.getAttribute("optional") // boolean isOptional = Boolean.getBoolean(current.getAttribute("optional")); final boolean isOptional = current.getAttribute("optional").equals("true"); final boolean canBeDisabled = current.getAttribute("canBeDisabled").equals("true"); final String defaultType = current.getAttribute("defaultType"); final boolean isHidden = current.getAttribute("isHidden").equals("true"); final PlayerId newPlayer = new PlayerId(name, isOptional, canBeDisabled, defaultType, isHidden, data); playerList.addPlayerId(newPlayer); } } private void parseAlliances(final Element root) throws GameParseException { final AllianceTracker allianceTracker = data.getAllianceTracker(); final Collection<PlayerId> players = data.getPlayerList().getPlayers(); for (final Element current : getChildren("alliance", root)) { final PlayerId p1 = getPlayerId(current, "player", true); final String alliance = current.getAttribute("alliance"); allianceTracker.addToAlliance(p1, alliance); } // if relationships aren't initialized based on relationshipInitialize we use the alliances to // set the relationships if (getSingleChild("relationshipInitialize", root, true) == null) { final RelationshipTracker relationshipTracker = data.getRelationshipTracker(); final RelationshipTypeList relationshipTypeList = data.getRelationshipTypeList(); // iterate through all players to get known allies and enemies for (final PlayerId currentPlayer : players) { // start with all players as enemies // start with no players as allies final Set<PlayerId> allies = allianceTracker.getAllies(currentPlayer); final Set<PlayerId> enemies = new HashSet<>(players); enemies.removeAll(allies); // remove self from enemies list (in case of free-for-all) enemies.remove(currentPlayer); // remove self from allies list (in case you are a member of an alliance) allies.remove(currentPlayer); // At this point enemies and allies should be set for this player. for (final PlayerId alliedPLayer : allies) { relationshipTracker.setRelationship( currentPlayer, alliedPLayer, relationshipTypeList.getDefaultAlliedRelationship()); } for (final PlayerId enemyPlayer : enemies) { relationshipTracker.setRelationship( currentPlayer, enemyPlayer, relationshipTypeList.getDefaultWarRelationship()); } } } } private void parseRelationInitialize(final List<Element> relations) throws GameParseException { if (relations.size() > 0) { final RelationshipTracker tracker = data.getRelationshipTracker(); for (final Element current : relations) { final PlayerId p1 = getPlayerId(current, "player1", true); final PlayerId p2 = getPlayerId(current, "player2", true); final RelationshipType r = getRelationshipType(current, "type"); final int roundValue = Integer.parseInt(current.getAttribute("roundValue")); tracker.setRelationship(p1, p2, r, roundValue); } } } private void parseGamePlay(final Element root) throws GameParseException { parseDelegates(getChildren("delegate", root)); parseSequence(getSingleChild("sequence", root)); parseOffset(getSingleChild("offset", root, true)); } private void parseProperties(final Node root) throws GameParseException { final GameProperties properties = data.getProperties(); for (final Element current : getChildren("property", root)) { final String editable = current.getAttribute("editable"); final String property = current.getAttribute("name"); String value = current.getAttribute("value"); if (value == null || value.length() == 0) { final List<Element> valueChildren = getChildren("value", current); if (!valueChildren.isEmpty()) { final Element valueNode = valueChildren.get(0); if (valueNode != null) { value = valueNode.getTextContent(); } } } if (editable != null && editable.equalsIgnoreCase("true")) { parseEditableProperty(current, property, value); } else { final List<Node> children2 = getNonTextNodesIgnoringValue(current); if (children2.size() == 0) { // we don't know what type this property is!!, it appears like only numbers and string may // be represented // without proper type definition try { // test if it is an integer final int integer = Integer.parseInt(value); properties.set(property, integer); } catch (final NumberFormatException e) { // then it must be a string properties.set(property, value); } } else { final String type = children2.get(0).getNodeName(); switch (type) { case "boolean": properties.set(property, Boolean.valueOf(value)); break; case "file": properties.set(property, new File(value)); break; case "number": int intValue = 0; if (value != null) { try { intValue = Integer.parseInt(value); } catch (final NumberFormatException e) { // value already 0 } } properties.set(property, intValue); break; default: properties.set(property, value); break; } } } } data.getPlayerList() .forEach( playerId -> data.getProperties() .addPlayerProperty( new NumberProperty( Constants.getIncomePercentageFor(playerId), null, 999, 0, 100))); data.getPlayerList() .forEach( playerId -> data.getProperties() .addPlayerProperty( new NumberProperty(Constants.getPuIncomeBonus(playerId), null, 999, 0, 0))); } private void parseEditableProperty( final Element property, final String name, final String defaultValue) throws GameParseException { // what type final List<Node> children = getNonTextNodes(property); if (children.size() != 1) { throw newGameParseException( "Editable properties must have exactly 1 child specifying the type. " + "Number of children found:" + children.size() + " for node:" + property.getNodeName()); } final Element child = (Element) children.get(0); final String childName = child.getNodeName(); final IEditableProperty<?> editableProperty; switch (childName) { case "boolean": editableProperty = new BooleanProperty(name, null, Boolean.parseBoolean(defaultValue)); break; case "file": editableProperty = new FileProperty(name, null, defaultValue); break; case "list": case "combo": final List<String> values = Splitter.on(',').omitEmptyStrings().splitToList(child.getAttribute("values")); editableProperty = new ComboProperty<>(name, null, defaultValue, values); break; case "number": final int max = Integer.parseInt(child.getAttribute("max")); final int min = Integer.parseInt(child.getAttribute("min")); final int def = Integer.parseInt(defaultValue); editableProperty = new NumberProperty(name, null, max, min, def); break; case "color": // Parse the value as a hexadecimal number final int defaultColor = Integer.valueOf(defaultValue, 16); editableProperty = new ColorProperty(name, null, defaultColor); break; case "string": editableProperty = new StringProperty(name, null, defaultValue); break; default: throw newGameParseException("Unrecognized property type:" + childName); } data.getProperties().addEditableProperty(editableProperty); } private void parseOffset(final Node offsetAttributes) { if (offsetAttributes == null) { return; } final int roundOffset = Integer.parseInt(((Element) offsetAttributes).getAttribute("round")); data.getSequence().setRoundOffset(roundOffset); } private void parseDelegates(final List<Element> delegateList) throws GameParseException { for (final Element current : delegateList) { // load the class final String className = current.getAttribute("javaClass"); final IDelegate delegate = xmlGameElementMapper .newDelegate(className) .orElseThrow( () -> newGameParseException("Class <" + className + "> is not a delegate.")); final String name = current.getAttribute("name"); String displayName = current.getAttribute("display"); if (displayName == null) { displayName = name; } delegate.initialize(name, displayName); data.addDelegate(delegate); } } private void parseSequence(final Node sequence) throws GameParseException { parseSteps(getChildren("step", sequence)); } private void parseSteps(final List<Element> stepList) throws GameParseException { for (final Element current : stepList) { final IDelegate delegate = getDelegate(current); final PlayerId player = getPlayerId(current, "player", false); final String name = current.getAttribute("name"); String displayName = null; final List<Element> propertyElements = getChildren("stepProperty", current); final Properties stepProperties = parseStepProperties(propertyElements); if (current.hasAttribute("display")) { displayName = current.getAttribute("display"); } final GameStep step = new GameStep(name, displayName, player, delegate, data, stepProperties); if (current.hasAttribute("maxRunCount")) { final int runCount = Integer.parseInt(current.getAttribute("maxRunCount")); if (runCount <= 0) { throw newGameParseException("maxRunCount must be positive"); } step.setMaxRunCount(runCount); } data.getSequence().addStep(step); } } private static Properties parseStepProperties(final List<Element> properties) { final Properties stepProperties = new Properties(); for (final Element stepProperty : properties) { final String name = stepProperty.getAttribute("name"); final String value = stepProperty.getAttribute("value"); stepProperties.setProperty(name, value); } return stepProperties; } private void parseProduction(final Node root) throws GameParseException { parseProductionRules(getChildren("productionRule", root)); parseProductionFrontiers(getChildren("productionFrontier", root)); parsePlayerProduction(getChildren("playerProduction", root)); parseRepairRules(getChildren("repairRule", root)); parseRepairFrontiers(getChildren("repairFrontier", root)); parsePlayerRepair(getChildren("playerRepair", root)); } private void parseTechnology(final Node root) throws GameParseException { parseTechnologies(getSingleChild("technologies", root, true)); parsePlayerTech(getChildren("playerTech", root)); } private void parseProductionRules(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final String name = current.getAttribute("name"); final ProductionRule rule = new ProductionRule(name, data); parseCosts(rule, getChildren("cost", current)); parseResults(rule, getChildren("result", current)); data.getProductionRuleList().addProductionRule(rule); } } private void parseRepairRules(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final String name = current.getAttribute("name"); final RepairRule rule = new RepairRule(name, data); parseRepairCosts(rule, getChildren("cost", current)); parseRepairResults(rule, getChildren("result", current)); data.getRepairRules().addRepairRule(rule); } } private void parseCosts(final ProductionRule rule, final List<Element> elements) throws GameParseException { if (elements.size() == 0) { throw newGameParseException("no costs for rule:" + rule.getName()); } for (final Element current : elements) { final Resource resource = getResource(current, "resource", true); final int quantity = Integer.parseInt(current.getAttribute("quantity")); rule.addCost(resource, quantity); } } private void parseRepairCosts(final RepairRule rule, final List<Element> elements) throws GameParseException { if (elements.size() == 0) { throw newGameParseException("no costs for rule:" + rule.getName()); } for (final Element current : elements) { final Resource resource = getResource(current, "resource", true); final int quantity = Integer.parseInt(current.getAttribute("quantity")); rule.addCost(resource, quantity); } } private void parseResults(final ProductionRule rule, final List<Element> elements) throws GameParseException { if (elements.size() == 0) { throw newGameParseException("no results for rule:" + rule.getName()); } for (final Element current : elements) { // must find either a resource or a unit with the given name NamedAttachable result = getResource(current, "resourceOrUnit", false); if (result == null) { result = getUnitType(current, "resourceOrUnit", false); } if (result == null) { throw newGameParseException( "Could not find resource or unit" + current.getAttribute("resourceOrUnit")); } final int quantity = Integer.parseInt(current.getAttribute("quantity")); rule.addResult(result, quantity); } } private void parseRepairResults(final RepairRule rule, final List<Element> elements) throws GameParseException { if (elements.size() == 0) { throw newGameParseException("no results for rule:" + rule.getName()); } for (final Element current : elements) { // must find either a resource or a unit with the given name NamedAttachable result = getResource(current, "resourceOrUnit", false); if (result == null) { result = getUnitType(current, "resourceOrUnit", false); } if (result == null) { throw newGameParseException( "Could not find resource or unit" + current.getAttribute("resourceOrUnit")); } final int quantity = Integer.parseInt(current.getAttribute("quantity")); rule.addResult(result, quantity); } } private void parseProductionFrontiers(final List<Element> elements) throws GameParseException { final ProductionFrontierList frontiers = data.getProductionFrontierList(); for (final Element current : elements) { final String name = current.getAttribute("name"); final ProductionFrontier frontier = new ProductionFrontier(name, data); parseFrontierRules(getChildren("frontierRules", current), frontier); frontiers.addProductionFrontier(frontier); } } private void parseTechnologies(final Node element) { if (element == null) { return; } final TechnologyFrontier allTechs = data.getTechnologyFrontier(); parseTechs(getChildren("techname", element), allTechs); } private void parsePlayerTech(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final PlayerId player = getPlayerId(current, "player", true); final TechnologyFrontierList categories = player.getTechnologyFrontierList(); parseCategories(getChildren("category", current), categories); } } private void parseCategories( final List<Element> elements, final TechnologyFrontierList categories) throws GameParseException { for (final Element current : elements) { final TechnologyFrontier tf = new TechnologyFrontier(current.getAttribute("name"), data); parseCategoryTechs(getChildren("tech", current), tf); categories.addTechnologyFrontier(tf); } } private void parseRepairFrontiers(final List<Element> elements) throws GameParseException { final RepairFrontierList frontiers = data.getRepairFrontierList(); for (final Element current : elements) { final String name = current.getAttribute("name"); final RepairFrontier frontier = new RepairFrontier(name, data); parseRepairFrontierRules(getChildren("repairRules", current), frontier); frontiers.addRepairFrontier(frontier); } } private void parsePlayerProduction(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final PlayerId player = getPlayerId(current, "player", true); final ProductionFrontier frontier = getProductionFrontier(current); player.setProductionFrontier(frontier); } } private void parsePlayerRepair(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final PlayerId player = getPlayerId(current, "player", true); final RepairFrontier repairFrontier = getRepairFrontier(current); player.setRepairFrontier(repairFrontier); } } private void parseFrontierRules(final List<Element> elements, final ProductionFrontier frontier) throws GameParseException { for (final Element element : elements) { frontier.addRule(getProductionRule(element)); } } private void parseTechs(final List<Element> elements, final TechnologyFrontier allTechsFrontier) { for (final Element current : elements) { final String name = current.getAttribute("name"); final String tech = current.getAttribute("tech"); TechAdvance ta; if (tech.length() > 0) { ta = new GenericTechAdvance( name, TechAdvance.findDefinedAdvanceAndCreateAdvance(tech, data), data); } else { try { ta = TechAdvance.findDefinedAdvanceAndCreateAdvance(name, data); } catch (final IllegalArgumentException e) { ta = new GenericTechAdvance(name, null, data); } } allTechsFrontier.addAdvance(ta); } } private void parseCategoryTechs(final List<Element> elements, final TechnologyFrontier frontier) throws GameParseException { for (final Element current : elements) { TechAdvance ta = data.getTechnologyFrontier().getAdvanceByProperty(current.getAttribute("name")); if (ta == null) { ta = data.getTechnologyFrontier().getAdvanceByName(current.getAttribute("name")); } if (ta == null) { throw newGameParseException("Technology not found :" + current.getAttribute("name")); } frontier.addAdvance(ta); } } private void parseRepairFrontierRules(final List<Element> elements, final RepairFrontier frontier) throws GameParseException { for (final Element element : elements) { frontier.addRule(getRepairRule(element)); } } private void parseAttachments(final Element root, final Map<String, List<String>> variables) throws GameParseException { for (final Element current : getChildren("attachment", root)) { final String foreach = current.getAttribute("foreach"); if (foreach.isEmpty()) { parseAttachment(current, variables, Collections.emptyMap()); } else { final List<String> nestedForeach = Splitter.on("^").splitToList(foreach); if (nestedForeach.isEmpty() || nestedForeach.size() > 2) { throw newGameParseException( "Invalid foreach expression, can only use variables, ':', and at most 1 '^': " + foreach); } final List<String> foreachVariables1 = Splitter.on(":").splitToList(nestedForeach.get(0)); final List<String> foreachVariables2 = nestedForeach.size() == 2 ? Splitter.on(":").splitToList(nestedForeach.get(1)) : Collections.emptyList(); validateForeachVariables(foreachVariables1, variables, foreach); validateForeachVariables(foreachVariables2, variables, foreach); final int length1 = variables.get(foreachVariables1.get(0)).size(); for (int i = 0; i < length1; i++) { final Map<String, String> foreachMap1 = createForeachVariablesMap(foreachVariables1, i, variables); if (foreachVariables2.isEmpty()) { parseAttachment(current, variables, foreachMap1); } else { final int length2 = variables.get(foreachVariables2.get(0)).size(); for (int j = 0; j < length2; j++) { final Map<String, String> foreachMap2 = createForeachVariablesMap(foreachVariables2, j, variables); foreachMap2.putAll(foreachMap1); parseAttachment(current, variables, foreachMap2); } } } } } } private void validateForeachVariables( final List<String> foreachVariables, final Map<String, List<String>> variables, final String foreach) throws GameParseException { if (foreachVariables.isEmpty()) { return; } if (!variables.keySet().containsAll(foreachVariables)) { throw newGameParseException("Attachment has invalid variables in foreach: " + foreach); } final int length = variables.get(foreachVariables.get(0)).size(); for (final String foreachVariable : foreachVariables) { final List<String> foreachValue = variables.get(foreachVariable); if (length != foreachValue.size()) { throw newGameParseException( "Attachment foreach variables must have same number of elements: " + foreach); } } } private static Map<String, String> createForeachVariablesMap( final List<String> foreachVariables, final int currentIndex, final Map<String, List<String>> variables) { final Map<String, String> foreachMap = new HashMap<>(); for (final String foreachVariable : foreachVariables) { final List<String> foreachValue = variables.get(foreachVariable); foreachMap.put("@" + foreachVariable.replace("$", "") + "@", foreachValue.get(currentIndex)); } return foreachMap; } private void parseAttachment( final Element current, final Map<String, List<String>> variables, final Map<String, String> foreach) throws GameParseException { final String className = current.getAttribute("javaClass"); final Attachable attachable = findAttachment(current, current.getAttribute("type"), foreach); final String name = replaceForeachVariables(current.getAttribute("name"), foreach); final IAttachment attachment = xmlGameElementMapper .newAttachment(className, name, attachable, data) .orElseThrow( () -> newGameParseException( "Attachment of type " + className + " could not be instantiated")); attachable.addAttachment(name, attachment); final List<Element> options = getChildren("option", current); final List<Tuple<String, String>> attachmentOptionValues = setOptions(attachment, options, foreach, variables); // keep a list of attachment references in the order they were added data.addToAttachmentOrderAndValues(Tuple.of(attachment, attachmentOptionValues)); } private Attachable findAttachment( final Element element, final String type, final Map<String, String> foreach) throws GameParseException { final String attachTo = replaceForeachVariables(element.getAttribute("attachTo"), foreach); switch (type) { case "unitType": return getUnitType(attachTo); case "territory": return getTerritory(attachTo); case "resource": return getResource(attachTo); case "territoryEffect": return getTerritoryEffect(attachTo); case "player": return getPlayerId(attachTo); case "relationship": return getRelationshipType(attachTo); case "technology": return getTechnology(attachTo); default: throw newGameParseException("Type not found to attach to: " + type); } } private List<Tuple<String, String>> setOptions( final IAttachment attachment, final List<Element> options, final Map<String, String> foreach, final Map<String, List<String>> variables) throws GameParseException { final List<Tuple<String, String>> results = new ArrayList<>(); for (final Element option : options) { // decapitalize the property name for backwards compatibility final String name = decapitalize(option.getAttribute("name")); if (name.isEmpty()) { throw newGameParseException( "Option name with zero length for attachment: " + attachment.getName()); } final String value = option.getAttribute("value"); final String count = option.getAttribute("count"); final String countAndValue = (!count.isEmpty() ? count + ":" : "") + value; if (containsEmptyForeachVariable(countAndValue, foreach)) { continue; // Skip adding option if contains empty foreach variable } final String valueWithForeach = replaceForeachVariables(countAndValue, foreach); final String finalValue = replaceVariables(valueWithForeach, variables); try { attachment .getProperty(name) .orElseThrow( () -> newGameParseException( String.format( "Missing property definition for option '%s' in attachment '%s'", name, attachment.getName()))) .setValue(finalValue); } catch (final GameParseException e) { throw e; } catch (final Exception e) { throw newGameParseException( "Unexpected Exception while setting values for attachment: " + attachment, e); } results.add(Tuple.of(name, finalValue)); } return results; } private String replaceForeachVariables(final String s, final Map<String, String> foreach) { String result = s; for (final Entry<String, String> entry : foreach.entrySet()) { result = result.replace(entry.getKey(), entry.getValue()); } return result; } private boolean containsEmptyForeachVariable(final String s, final Map<String, String> foreach) { for (final Entry<String, String> entry : foreach.entrySet()) { if (entry.getValue().isEmpty() && s.contains(entry.getKey())) { return true; } } return false; } private String replaceVariables(final String s, final Map<String, List<String>> variables) { String result = s; for (final Entry<String, List<String>> entry : variables.entrySet()) { result = result.replace(entry.getKey(), String.join(":", entry.getValue())); } return result; } @VisibleForTesting static String decapitalize(final String value) { return ((value.length() > 0) ? value.substring(0, 1).toLowerCase() : "") + ((value.length() > 1) ? value.substring(1) : ""); } private void parseInitialization(final Node root) throws GameParseException { // parse territory owners final Node owner = getSingleChild("ownerInitialize", root, true); if (owner != null) { parseOwner(getChildren("territoryOwner", owner)); } // parse initial unit placement final Node unit = getSingleChild("unitInitialize", root, true); if (unit != null) { parseUnitPlacement(getChildren("unitPlacement", unit)); parseHeldUnits(getChildren("heldUnits", unit)); } // parse resources given final Node resource = getSingleChild("resourceInitialize", root, true); if (resource != null) { parseResourceInitialization(getChildren("resourceGiven", resource)); } // parse relationships final Node relationInitialize = getSingleChild("relationshipInitialize", root, true); if (relationInitialize != null) { parseRelationInitialize(getChildren("relationship", relationInitialize)); } } private void parseOwner(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final Territory territory = getTerritory(current, "territory"); final PlayerId owner = getPlayerId(current, "owner", true); territory.setOwner(owner); // Set the original owner on startup. // TODO Look into this // The addition of this caused the automated tests to fail as TestAttachment can't be cast to // TerritoryAttachment // The addition of this IF to pass the tests is wrong, but works until a better solution is // found. // Kevin will look into it. if (!territory.getData().getGameName().equals("gameExample") && !territory.getData().getGameName().equals("test")) { // set the original owner final TerritoryAttachment ta = TerritoryAttachment.get(territory); if (ta != null) { // If we already have an original owner set (ie: we set it previously in the attachment // using originalOwner or // occupiedTerrOf), then we DO NOT set the original owner again. // This is how we can have a game start with territories owned by 1 faction but controlled // by a 2nd faction. final PlayerId currentOwner = ta.getOriginalOwner(); if (currentOwner == null) { ta.setOriginalOwner(owner); } } } } } private void parseUnitPlacement(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final Territory territory = getTerritory(current, "territory"); final UnitType type = getUnitType(current, "unitType", true); final String ownerString = current.getAttribute("owner"); final String hitsTakenString = current.getAttribute("hitsTaken"); final String unitDamageString = current.getAttribute("unitDamage"); final PlayerId owner; if (ownerString == null || ownerString.trim().length() == 0) { owner = PlayerId.NULL_PLAYERID; } else { owner = getPlayerId(current, "owner", false); } final int hits; if (hitsTakenString != null && hitsTakenString.trim().length() > 0) { hits = Integer.parseInt(hitsTakenString); if (hits < 0 || hits > UnitAttachment.get(type).getHitPoints() - 1) { throw newGameParseException( "hitsTaken cannot be less than zero or greater than one less than total hitPoints"); } } else { hits = 0; } final int unitDamage; if (unitDamageString != null && unitDamageString.trim().length() > 0) { unitDamage = Integer.parseInt(unitDamageString); if (unitDamage < 0) { throw newGameParseException("unitDamage cannot be less than zero"); } } else { unitDamage = 0; } final int quantity = Integer.parseInt(current.getAttribute("quantity")); territory.getUnitCollection().addAll(type.create(quantity, owner, false, hits, unitDamage)); } } private void parseHeldUnits(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final PlayerId player = getPlayerId(current, "player", true); final UnitType type = getUnitType(current, "unitType", true); final int quantity = Integer.parseInt(current.getAttribute("quantity")); player.getUnitCollection().addAll(type.create(quantity, player)); } } private void parseResourceInitialization(final List<Element> elements) throws GameParseException { for (final Element current : elements) { final PlayerId player = getPlayerId(current, "player", true); final Resource resource = getResource(current, "resource", true); final int quantity = Integer.parseInt(current.getAttribute("quantity")); player.getResources().addResource(resource, quantity); } } private void checkThatAllUnitsHaveAttachments(final GameData data) throws GameParseException { final Collection<UnitType> errors = new ArrayList<>(); for (final UnitType ut : data.getUnitTypeList().getAllUnitTypes()) { final UnitAttachment ua = UnitAttachment.get(ut); if (ua == null) { errors.add(ut); } } if (!errors.isEmpty()) { throw newGameParseException( data.getGameName() + " does not have unit attachments for: " + MyFormatter.defaultNamedToTextList(errors)); } } }
gpl-3.0
CCAFS/MARLO
marlo-web/src/main/java/org/cgiar/ccafs/marlo/ocs/ws/client/GetMarloServiceStatus.java
798
package org.cgiar.ccafs.marlo.ocs.ws.client; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for getMarloServiceStatus complex type. * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getMarloServiceStatus"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getMarloServiceStatus") public class GetMarloServiceStatus { }
gpl-3.0
zooqi/wuliu
src/main/java/org/lanqiao/wuliu/servlet/emp/EmpInfor.java
1423
package org.lanqiao.wuliu.servlet.emp; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; import org.lanqiao.wuliu.bean.Emp; import org.lanqiao.wuliu.dao.impl.HrDaoImpl; @WebServlet(name = "empInfor", urlPatterns = { "/empInfor" }) public class EmpInfor extends HttpServlet { private static final long serialVersionUID = -3344382381426516870L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HrDaoImpl hd = new HrDaoImpl(); response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); ArrayList<Emp> emps = hd.empInfor(); JSONArray array = new JSONArray(); for (Emp emp : emps) { JSONObject row = new JSONObject(); row.put("empId", emp.getEmpId()); row.put("empName", emp.getEmpName()); row.put("empDepart", emp.getEmpDepart()); row.put("empNum", emp.getEmpNum()); array.put(row); } out.println(array); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
gpl-3.0
CommandoDuck/MinecraftTest
src/main/java/com/commandoduck/modTest/proxy/IProxy.java
70
package com.commandoduck.modTest.proxy; public interface IProxy { }
gpl-3.0
zhangyf/ObjectStorage
src/main/java/cn/zyf/protocols/impl/DefaultClusterManager.java
4091
/* Copyright 2016,2017 Yufeng Zhang This file is part of ObjectStorageServer. ObjectStorageServer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ObjectStorageServer 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 ObjectStorageServer. If not, see <http://www.gnu.org/licenses/>. */ package cn.zyf.protocols.impl; import cn.zyf.protocols.Cluster; import cn.zyf.protocols.ClusterManager; import cn.zyf.protocols.ClusterType; import cn.zyf.protocols.impl.cluster.CassandraClusterImpl; import com.zyf.utils.conf.ConfigTree; import com.zyf.utils.conf.ConfigTreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Created by zhangyufeng on 2016/10/28. */ public class DefaultClusterManager extends ClusterManager { private static Logger LOG = LoggerFactory.getLogger(DefaultClusterManager.class); private Map<String, Cluster> clusters; private Map<String, String> metaOption; private Cluster metaCluster; private void init(ConfigTree config) { Set<Object> subClusterNode = config.getRoot().getValue(); for (Object obj : subClusterNode) { ConfigTreeNode ctn = (ConfigTreeNode) obj; ClusterType type; switch (ctn.getAttributes().get("type").toLowerCase()) { case "cassandra": LOG.info("add cassandra cluster " + ctn.getName() +" into ClusterManager"); Cluster cluster = new CassandraClusterImpl(); cluster.setName(ctn.getName()); type = ClusterType.CASSANDRA; for (ConfigTreeNode subCtn : ctn.getByName("node")) { String[] entries = subCtn.getStringValue().split("\\."); if (entries.length == 2) { cluster.addHost(entries[0], Integer.parseInt(entries[1])); } else { cluster.addHost(subCtn.getStringValue(), 9160); } } cluster.setType(type); clusters.put(cluster.getName(), cluster); break; case "hbase": type = ClusterType.HBASE; break; case "hdfs": type = ClusterType.HDFS; break; case "mysql": type = ClusterType.MYSQL; break; case "oracle": type = ClusterType.ORACLE; break; case "redis": type = ClusterType.REDIS; break; case "memcached": type = ClusterType.MEMCACHED; break; default: break; } } } public DefaultClusterManager(ConfigTree configTree) { clusters = new ConcurrentHashMap<>(); init(configTree); } @Override public void setMetaCluster(String name) { metaCluster = clusters.get(name); } @Override public Cluster getMetaCluster() { return metaCluster; } @Override public void setMetaOption(Map<String, String> option) { assert option != null; metaOption = option; } @Override public Map<String, String> getMetaOption() { return metaOption; } @Override public Cluster getClusterByName(String name) { return clusters.get(name); } }
gpl-3.0
johnkingjk/LowPolyEngine
src/main/java/engine/LowPolyEngine.java
2789
package engine; import engine.input.InputManager; import engine.math.Quaternion; import engine.rendering.OpenGLLoader; import engine.math.Vector3f; import engine.rendering.Renderer; import engine.rendering.mesh.Mesh; import engine.rendering.mesh.MeshLoader; import engine.rendering.shader.DefaultShader; import engine.transform.Camera; import engine.transform.Transform; import org.lwjgl.opengl.*; /** * Created by Marco on 22.12.2014. */ public class LowPolyEngine { public static void main(String[] args) { DisplayManager.create( new Window("LowPolyEngine Test", 960, 600, false, true, 60 ) ); new TestListener(); OpenGLLoader loader = new OpenGLLoader(); Camera camera = new Camera(new Vector3f(0, 10, -10), Quaternion.IDENTITY, Display.getWidth(), Display.getHeight(), 70, 0.1f, 1000.0f); Renderer renderer = new Renderer(camera.getProjectionMatrix()); MeshLoader meshLoader = new MeshLoader(); Mesh mountain = meshLoader.readObjectFile("src/main/resources/models/mountain.obj", loader); Transform transform_mountain = new Transform(); transform_mountain.setTranslation(new Vector3f(0, 0, 0)); Mesh bigvalley = meshLoader.readObjectFile("src/main/resources/models/bigvalley2.obj", loader); Transform transform_bigvalley = new Transform(); transform_bigvalley.setTranslation(new Vector3f(0, 0, 0)); InputManager.init(); DefaultShader shader = new DefaultShader(); renderer.registerShader(shader); //Terrain terrain = new Terrain(loader); //Material mat = new Material("test", Vector3f.zero(), Vector3f.fromColor(227, 212, 118), Vector3f.zero(), (byte) 0, 0f, 1f, new Texture(0)); //GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); while(!Display.isCloseRequested()) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); InputManager.update(); renderer.processModel(mountain, transform_mountain); renderer.processModel(bigvalley, transform_bigvalley); /* shader.start(); shader.setTransformationMatrix(new Matrix4f()); shader.setupViewMatrix(camera.getViewMatrix()); shader.setupMaterial(mat); terrain.render(); shader.stop(); */ camera.update(); renderer.render(camera); DisplayManager.update(); } loader.cleanUp(); renderer.cleanUp(); DisplayManager.destroy(); InputManager.destroy(); } }
gpl-3.0
kriztan/Pix-Art-Messenger
src/main/java/eu/siacs/conversations/ui/ShareViaAccountActivity.java
3110
package eu.siacs.conversations.ui; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import eu.siacs.conversations.R; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.ui.adapter.AccountAdapter; import eu.siacs.conversations.xmpp.Jid; public class ShareViaAccountActivity extends XmppActivity { public static final String EXTRA_CONTACT = "contact"; public static final String EXTRA_BODY = "body"; protected final List<Account> accountList = new ArrayList<>(); protected ListView accountListView; protected AccountAdapter mAccountAdapter; @Override protected void refreshUiReal() { synchronized (this.accountList) { accountList.clear(); accountList.addAll(xmppConnectionService.getAccounts()); } mAccountAdapter.notifyDataSetChanged(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_accounts); setSupportActionBar(findViewById(R.id.toolbar)); configureActionBar(getSupportActionBar()); accountListView = findViewById(R.id.account_list); this.mAccountAdapter = new AccountAdapter(this, accountList, false); accountListView.setAdapter(this.mAccountAdapter); accountListView.setOnItemClickListener((arg0, view, position, arg3) -> { final Account account = accountList.get(position); final String body = getIntent().getStringExtra(EXTRA_BODY); try { final Jid contact = Jid.of(getIntent().getStringExtra(EXTRA_CONTACT)); final Conversation conversation = xmppConnectionService.findOrCreateConversation( account, contact, false, false); switchToConversation(conversation, body); } catch (IllegalArgumentException e) { // ignore error } finish(); }); } @Override protected void onStart() { super.onStart(); final int theme = findTheme(); if (this.mTheme != theme) { recreate(); } } @Override void onBackendConnected() { final int numAccounts = xmppConnectionService.getAccounts().size(); if (numAccounts == 1) { final String body = getIntent().getStringExtra(EXTRA_BODY); final Account account = xmppConnectionService.getAccounts().get(0); try { final Jid contact = Jid.of(getIntent().getStringExtra(EXTRA_CONTACT)); final Conversation conversation = xmppConnectionService.findOrCreateConversation( account, contact, false, false); switchToConversation(conversation, body); } catch (IllegalArgumentException e) { // ignore error } finish(); } else { refreshUiReal(); } } }
gpl-3.0
gluster/gmc
src/org.gluster.storage.management.core/src/org/gluster/storage/management/core/model/Event.java
1809
/******************************************************************************* * Copyright (c) 2006-2011 Gluster, Inc. <http://www.gluster.com> * This file is part of Gluster Management Console. * * Gluster Management Console is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Gluster Management Console is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.gluster.storage.management.core.model; public class Event { public enum EVENT_TYPE { BRICKS_ADDED, BRICKS_REMOVED, BRICKS_CHANGED, VOLUME_STATUS_CHANGED, ALERT_CREATED, ALERT_REMOVED, VOLUME_OPTIONS_RESET, VOLUME_OPTION_SET, VOLUME_CHANGED, GLUSTER_SERVER_CHANGED, DEVICES_ADDED, DEVICES_REMOVED, DEVICES_CHANGED, DISCOVERED_SERVER_CHANGED } private EVENT_TYPE eventType; private Object eventData; public Event(EVENT_TYPE eventType, Object eventData) { this.eventType = eventType; this.eventData = eventData; } public EVENT_TYPE getEventType() { return eventType; } public void setEventType(EVENT_TYPE eventType) { this.eventType = eventType; } public Object getEventData() { return eventData; } public void setEventData(Object eventData) { this.eventData = eventData; } }
gpl-3.0
burukuru/grakn
grakn-graql/src/test/java/ai/grakn/graql/internal/gremlin/sets/RolePlayerFragmentSetTest.java
5660
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graql.internal.gremlin.sets; import ai.grakn.concept.Label; import ai.grakn.graql.Graql; import ai.grakn.graql.Var; import ai.grakn.graql.internal.gremlin.EquivalentFragmentSet; import ai.grakn.test.SampleKBContext; import ai.grakn.test.kbs.MovieKB; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import org.junit.ClassRule; import org.junit.Test; import java.util.Collection; import java.util.HashSet; import static org.junit.Assert.assertEquals; /** * @author Felix Chapman */ public class RolePlayerFragmentSetTest { @ClassRule public static final SampleKBContext sampleKB = SampleKBContext.preLoad(MovieKB.get()); private final Var a = Graql.var("a"), b = Graql.var("b"), c = Graql.var("c"), d = Graql.var("d"); @Test public void whenApplyingRoleOptimisation_ExpandRoleToAllSubs() { Label author = Label.of("author"); Label director = Label.of("director"); EquivalentFragmentSet authorLabelFragmentSet = EquivalentFragmentSets.label(null, d, ImmutableSet.of(author)); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, d), authorLabelFragmentSet ); RolePlayerFragmentSet.ROLE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); HashSet<EquivalentFragmentSet> expected = Sets.newHashSet( RolePlayerFragmentSet.of(null, a, b, c, null, ImmutableSet.of(author, director), null), authorLabelFragmentSet ); assertEquals(expected, fragmentSets); } @Test public void whenRoleIsNotInGraph_DoNotApplyRoleOptimisation() { Label magician = Label.of("magician"); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, d), EquivalentFragmentSets.label(null, d, ImmutableSet.of(magician)) ); Collection<EquivalentFragmentSet> expected = Sets.newHashSet(fragmentSets); RolePlayerFragmentSet.ROLE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); assertEquals(expected, fragmentSets); } @Test public void whenLabelDoesNotReferToARole_DoNotApplyRoleOptimisation() { Label movie = Label.of("movie"); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, d), EquivalentFragmentSets.label(null, d, ImmutableSet.of(movie)) ); Collection<EquivalentFragmentSet> expected = Sets.newHashSet(fragmentSets); RolePlayerFragmentSet.ROLE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); assertEquals(expected, fragmentSets); } @Test public void whenApplyingRoleOptimisationToMetaRole_DoNotExpandRoleToAllSubs() { Label role = Label.of("role"); EquivalentFragmentSet authorLabelFragmentSet = EquivalentFragmentSets.label(null, d, ImmutableSet.of(role)); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, d), authorLabelFragmentSet ); RolePlayerFragmentSet.ROLE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); HashSet<EquivalentFragmentSet> expected = Sets.newHashSet( RolePlayerFragmentSet.of(null, a, b, c, null, null, null), authorLabelFragmentSet ); assertEquals(expected, fragmentSets); } @Test public void whenRelationTypeIsNotInGraph_DoNotApplyRelationTypeOptimisation() { Label magician = Label.of("magician"); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, null), EquivalentFragmentSets.isa(null, a, d, true), EquivalentFragmentSets.label(null, d, ImmutableSet.of(magician)) ); Collection<EquivalentFragmentSet> expected = Sets.newHashSet(fragmentSets); RolePlayerFragmentSet.RELATION_TYPE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); assertEquals(expected, fragmentSets); } @Test public void whenLabelDoesNotReferToARelationType_DoNotApplyRelationTypeOptimisation() { Label movie = Label.of("movie"); Collection<EquivalentFragmentSet> fragmentSets = Sets.newHashSet( EquivalentFragmentSets.rolePlayer(null, a, b, c, null), EquivalentFragmentSets.isa(null, a, d, true), EquivalentFragmentSets.label(null, d, ImmutableSet.of(movie)) ); Collection<EquivalentFragmentSet> expected = Sets.newHashSet(fragmentSets); RolePlayerFragmentSet.RELATION_TYPE_OPTIMISATION.apply(fragmentSets, sampleKB.tx()); assertEquals(expected, fragmentSets); } }
gpl-3.0
vdveer/SMSSecure
src/org/smssecure/smssecure/mms/LegacyMmsConnection.java
11350
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.smssecure.smssecure.mms; import android.content.Context; import android.net.ConnectivityManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import org.apache.http.Header; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.NoConnectionReuseStrategyHC4; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.smssecure.smssecure.database.ApnDatabase; import org.smssecure.smssecure.util.Conversions; import org.smssecure.smssecure.util.ServiceUtil; import org.smssecure.smssecure.util.TelephonyUtil; import org.smssecure.smssecure.util.SMSSecurePreferences; import org.smssecure.smssecure.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URL; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; @SuppressWarnings("deprecation") public abstract class LegacyMmsConnection { public static final String USER_AGENT = "Android-Mms/2.0"; private static final String TAG = LegacyMmsConnection.class.getSimpleName(); protected final Context context; protected final Apn apn; protected LegacyMmsConnection(Context context) throws ApnUnavailableException { this.context = context; this.apn = getApn(context); } public static Apn getApn(Context context) throws ApnUnavailableException { try { Optional<Apn> params = ApnDatabase.getInstance(context) .getMmsConnectionParameters(TelephonyUtil.getMccMnc(context), TelephonyUtil.getApn(context)); if (!params.isPresent()) { throw new ApnUnavailableException("No parameters available from ApnDefaults."); } return params.get(); } catch (IOException ioe) { throw new ApnUnavailableException("ApnDatabase threw an IOException", ioe); } } protected boolean isDirectConnect() { // We think Sprint supports direct connection over wifi/data, but not Verizon Set<String> sprintMccMncs = new HashSet<String>() {{ add("312530"); add("311880"); add("311870"); add("311490"); add("310120"); add("316010"); add("312190"); }}; return ServiceUtil.getTelephonyManager(context).getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA && sprintMccMncs.contains(TelephonyUtil.getMccMnc(context)); } @SuppressWarnings("TryWithIdenticalCatches") protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio) throws IOException { InetAddress inetAddress = InetAddress.getByName(host); if (!usingMmsRadio) { if (inetAddress.isSiteLocalAddress()) { throw new IOException("RFC1918 address in non-MMS radio situation!"); } Log.w(TAG, "returning vacuous success since MMS radio is not in use"); return true; } if (inetAddress == null) { throw new IOException("Unable to lookup host: InetAddress.getByName() returned null."); } byte[] ipAddressBytes = inetAddress.getAddress(); if (ipAddressBytes == null) { Log.w(TAG, "resolved IP address bytes are null, returning true to attempt a connection anyway."); return true; } Log.w(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress()); ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); try { final Method requestRouteMethod = manager.getClass().getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class); final boolean routeToHostObtained = (Boolean) requestRouteMethod.invoke(manager, MmsRadio.TYPE_MOBILE_MMS, inetAddress); Log.w(TAG, "requestRouteToHostAddress(" + inetAddress + ") -> " + routeToHostObtained); return routeToHostObtained; } catch (NoSuchMethodException nsme) { Log.w(TAG, nsme); } catch (IllegalAccessException iae) { Log.w(TAG, iae); } catch (InvocationTargetException ite) { Log.w(TAG, ite); } final int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0); final boolean routeToHostObtained = manager.requestRouteToHost(MmsRadio.TYPE_MOBILE_MMS, ipAddress); Log.w(TAG, "requestRouteToHost(" + ipAddress + ") -> " + routeToHostObtained); return routeToHostObtained; } protected static byte[] parseResponse(InputStream is) throws IOException { InputStream in = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Util.copy(in, baos); Log.w(TAG, "Received full server response, " + baos.size() + " bytes"); return baos.toByteArray(); } protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(SMSSecurePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); } protected byte[] execute(HttpUriRequest request) throws IOException { Log.w(TAG, "connecting to " + apn.getMmsc()); CloseableHttpClient client = null; CloseableHttpResponse response = null; try { client = constructHttpClient(); response = client.execute(request); Log.w(TAG, "* response code: " + response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { return parseResponse(response.getEntity().getContent()); } } catch (NullPointerException npe) { // TODO determine root cause // see: https://github.com/WhisperSystems/Signal-Android/issues/4379 throw new IOException(npe); } finally { if (response != null) response.close(); if (client != null) client.close(); } throw new IOException("unhandled response code"); } protected List<Header> getBaseHeaders() { final String number = TelephonyUtil.getManager(context).getLine1Number(); ; return new LinkedList<Header>() {{ add(new BasicHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic")); add(new BasicHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml")); add(new BasicHeader("Content-Type", "application/vnd.wap.mms-message")); add(new BasicHeader("x-carrier-magic", "http://magic.google.com")); if (!TextUtils.isEmpty(number)) { add(new BasicHeader("x-up-calling-line-id", number)); add(new BasicHeader("X-MDN", number)); } }}; } public static class Apn { public static Apn EMPTY = new Apn("", "", "", "", ""); private final String mmsc; private final String proxy; private final String port; private final String username; private final String password; public Apn(String mmsc, String proxy, String port, String username, String password) { this.mmsc = mmsc; this.proxy = proxy; this.port = port; this.username = username; this.password = password; } public Apn(Apn customApn, Apn defaultApn, boolean useCustomMmsc, boolean useCustomProxy, boolean useCustomProxyPort, boolean useCustomUsername, boolean useCustomPassword) { this.mmsc = useCustomMmsc ? customApn.mmsc : defaultApn.mmsc; this.proxy = useCustomProxy ? customApn.proxy : defaultApn.proxy; this.port = useCustomProxyPort ? customApn.port : defaultApn.port; this.username = useCustomUsername ? customApn.username : defaultApn.username; this.password = useCustomPassword ? customApn.password : defaultApn.password; } public boolean hasProxy() { return !TextUtils.isEmpty(proxy); } public String getMmsc() { return mmsc; } public String getProxy() { return hasProxy() ? proxy : null; } public int getPort() { return TextUtils.isEmpty(port) ? 80 : Integer.parseInt(port); } public boolean hasAuthentication() { return !TextUtils.isEmpty(username); } public String getUsername() { return username; } public String getPassword() { return password; } @Override public String toString() { return Apn.class.getSimpleName() + "{ mmsc: \"" + mmsc + "\"" + ", proxy: " + (proxy == null ? "none" : '"' + proxy + '"') + ", port: " + (port == null ? "(none)" : port) + ", user: " + (username == null ? "none" : '"' + username + '"') + ", pass: " + (password == null ? "none" : '"' + password + '"') + " }"; } } }
gpl-3.0
cruxic/calcpass
Android-App/CalcPass/app/src/main/java/com/calcpass/bytewords/ByteWordsDecoder.java
1443
package com.calcpass.bytewords; import java.util.HashMap; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ByteWordsDecoder { private HashMap<String, Integer> wordMap; public ByteWordsDecoder() { //Create map of word to byte value wordMap = new HashMap<String, Integer>(350); //.75 loadfactor int i = 0; for (String word: Words.loadWordList()) { wordMap.put(word, i++); } } /** Decode a list of words into bytes. White space between words is allowed but not mandatory. */ public byte[] decode(String text) throws ByteWordsDecodeEx { ByteArrayOutputStream buf = new ByteArrayOutputStream(); char c; String word; int lineNum = 1; int i = 0; Integer byteVal; //for each character... int slen = text.length(); while (i < slen) { //Skip white space (optional) while (i < slen) { c = text.charAt(i); //count lines if (c == '\n') lineNum++; else if (c != ' ' && c != '\t' && c != '\r') break; //not white i++; } //Read 3 characters if (i == slen) break; else if (i + 3 > slen) throw new ByteWordsDecodeEx("Incomplete word at end", lineNum); word = text.substring(i, i+3); byteVal = wordMap.get(word); if (byteVal == null) { throw new ByteWordsDecodeEx("\"" + word + "\" is not a valid word", lineNum); } buf.write(byteVal.intValue()); i += 3; } return buf.toByteArray(); } }
gpl-3.0
Shurgent/TFCTech
src/main/java/ua/pp/shurgent/tfctech/render/RenderWireDrawBench.java
3462
package ua.pp.shurgent.tfctech.render; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import ua.pp.shurgent.tfctech.api.crafting.WireDrawBenchManager; import ua.pp.shurgent.tfctech.api.interfaces.IDrawable; import ua.pp.shurgent.tfctech.tileentities.TEWireDrawBench; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class RenderWireDrawBench implements ISimpleBlockRenderingHandler { private static final float P = 0.0625f; private static final float MIN_X = 9 * P; private static final float MAX_X = 10 * P; private static final float MIN_Y = 8 * P; private static final float MAX_Y = 9 * P; private static final float MIN_Z = 23 * P; private static final float MAX_Z = 31 * P; @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { TileEntity te = world.getTileEntity(x, y, z); if (te == null || !(te instanceof TEWireDrawBench)) return false; TEWireDrawBench tewd = (TEWireDrawBench) world.getTileEntity(x, y, z); if (tewd == null || !tewd.isHeadBlock) return false; tewd = tewd.getMainTileEntity(); renderer.renderAllFaces = true; GL11.glPushMatrix(); if (tewd.recipe != null) { Item wire = tewd.recipe.getInItem().getItem(); String metal = ((IDrawable) wire).getWireMetalName(); IIcon ico = WireDrawBenchManager.getInstance().getWireIcon(metal); byte progr = tewd.progress; float offZ; float offY = 0F; if (progr > 99 || tewd.isFinished()) { offZ = 8F * P; offY = 1F * P; } else { offZ = 7F * P * (progr / 99f); } setRotatedRenderBounds(renderer, tewd.rotation, MIN_X, MIN_Y - offY, MIN_Z - offZ, MAX_X, MAX_Y - offY, MAX_Z - offZ); renderer.setOverrideBlockTexture(ico); //rotate(renderer, tewd.rotation); //renderer.renderStandardBlockWithColorMultiplier(Blocks.iron_block, x, y, z, 255, 255, 255); renderer.renderStandardBlock(Blocks.iron_block, x, y, z); renderer.clearOverrideBlockTexture(); } rotate(renderer, 0); renderer.renderAllFaces = false; GL11.glPopMatrix(); return true; } private void rotate(RenderBlocks renderer, int i) { renderer.uvRotateEast = i; renderer.uvRotateWest = i; renderer.uvRotateNorth = i; renderer.uvRotateSouth = i; } private void setRotatedRenderBounds(RenderBlocks renderer, byte rotation, float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { switch (rotation) { case 0: renderer.setRenderBounds(minX, minY, minZ, maxX, maxY, maxZ); break; case 1: renderer.setRenderBounds(MAX_Z - maxZ - 1F + P, minY, minX, MAX_Z - minZ - 1F + P, maxY, maxX); break; case 2: renderer.setRenderBounds(1F - maxX, minY, MAX_Z - maxZ - 1F + P, 1F - minX, maxY, MAX_Z - minZ - 1F + P); break; case 3: renderer.setRenderBounds(minZ, minY, 1F - maxX, maxZ, maxY, 1F - minX); break; default: break; } } @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { } @Override public boolean shouldRender3DInInventory(int modelId) { return false; } @Override public int getRenderId() { return 0; } }
gpl-3.0
geralddejong/darwinathome
dah-server/src/main/java/org/darwinathome/server/email/RegistrationEmailSender.java
3376
// ========= Copyright (C) 2009, 2010 Gerald de Jong ================= // This file is part of the Darwin at Home project, distributed // under the GNU General Public License, version 3. // You should have received a copy of this license in "license.txt", // but if not, see http://www.gnu.org/licenses/gpl-3.0.txt. // =================================================================== package org.darwinathome.server.email; import freemarker.template.TemplateException; import org.darwinathome.server.persistence.Player; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; /** * Handle registration email sending * * @author Gerald de Jong <geralddejong@gmail.com> */ public class RegistrationEmailSender { private static final int TOKEN_LENGTH = 32; private static final long MAX_TOKEN_AGE = 1000L * 60 * 60 * 24; private static Map<String, Invitation> LIVE_TOKENS = new ConcurrentHashMap<String, Invitation>(); private EmailSender emailSender; private String from, subject; public void setEmailSender(EmailSender emailSender) { this.emailSender = emailSender; } public void setFrom(String from) { this.from = from; } public void setSubject(String subject) { this.subject = subject; } public String sendRegistrationEmail(Player player, String emailAddress, String confirmationUrl) throws IOException, TemplateException { Invitation invitation = new Invitation(player, emailAddress); Map<String, Object> model = new TreeMap<String, Object>(); model.put("player", player); model.put("uniqueToken", invitation.getUnique()); model.put("confirmationUrl", confirmationUrl); emailSender.sendEmail(emailAddress, from, subject, model); LIVE_TOKENS.put(invitation.getUnique(), invitation); return invitation.getUnique(); } public Invitation getInvitation(String tokenString) { Invitation invitation = LIVE_TOKENS.get(tokenString); Iterator<Map.Entry<String, Invitation>> walk = LIVE_TOKENS.entrySet().iterator(); while (walk.hasNext()) { Map.Entry<String, Invitation> entry = walk.next(); if (entry.getValue().isOlderThan(MAX_TOKEN_AGE)) { walk.remove(); } } return invitation; } public class Invitation { private Player player; private String email; private String unique; private long created; private Invitation(Player player, String email) { this.player = player; this.email = email; StringBuilder out = new StringBuilder(TOKEN_LENGTH); for (int walk = 0; walk < TOKEN_LENGTH; walk++) { out.append((char) ('A' + ((int) (Math.random() * 26)))); } this.unique = out.toString(); this.created = System.currentTimeMillis(); } public String getEmail() { return email; } public String getUnique() { return unique; } public Player getPlayer() { return player; } public boolean isOlderThan(long time) { return (System.currentTimeMillis() - created) > time; } } }
gpl-3.0
marvin-we/steem-java-api-wrapper
core/src/test/java/eu/bittrade/libs/steemj/base/models/operations/VoteOperationParsingIT.java
3038
/* * This file is part of SteemJ (formerly known as 'Steem-Java-Api-Wrapper') * * SteemJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SteemJ 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 SteemJ. If not, see <http://www.gnu.org/licenses/>. */ package eu.bittrade.libs.steemj.base.models.operations; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import eu.bittrade.libs.steemj.BaseITForOperationParsing; import eu.bittrade.libs.steemj.IntegrationTest; import eu.bittrade.libs.steemj.exceptions.SteemCommunicationException; import eu.bittrade.libs.steemj.exceptions.SteemResponseException; import eu.bittrade.libs.steemj.plugins.apis.block.models.ExtendedSignedBlock; import eu.bittrade.libs.steemj.protocol.operations.Operation; import eu.bittrade.libs.steemj.protocol.operations.VoteOperation; /** * This class tests if the {@link VoteOperation} can be parsed successfully. * * @author <a href="http://steemit.com/@dez1337">dez1337</a> */ public class VoteOperationParsingIT extends BaseITForOperationParsing { private static final long BLOCK_NUMBER_CONTAINING_OPERATION = 5681456; private static final int TRANSACTION_INDEX = 0; private static final int OPERATION_INDEX = 0; private static final String EXPECTED_AUTHOR = "sarita"; private static final String EXPECTED_VOTER = "ned"; /** * Prepare all required fields used by this test class. * * @throws Exception * If something went wrong. */ @BeforeClass() public static void prepareTestClass() throws Exception { setupIntegrationTestEnvironment(); } @Override @Test @Category({ IntegrationTest.class }) public void testOperationParsing() throws SteemCommunicationException, SteemResponseException { ExtendedSignedBlock blockContainingVoteOperation = steemJ.getBlock(BLOCK_NUMBER_CONTAINING_OPERATION).get(); Operation voteOperation = blockContainingVoteOperation.getTransactions().get(TRANSACTION_INDEX).getOperations() .get(OPERATION_INDEX); assertThat(voteOperation, instanceOf(VoteOperation.class)); assertThat(((VoteOperation) voteOperation).getAuthor().getName(), equalTo(EXPECTED_AUTHOR)); assertThat(((VoteOperation) voteOperation).getVoter().getName(), equalTo(EXPECTED_VOTER)); } }
gpl-3.0
remybaranx/qtaste
plugins_src/javagui/src/main/java/com/qspin/qtaste/javagui/server/TextGetter.java
1482
/* Copyright 2007-2012 QSpin - www.qspin.be This file is part of QTaste framework. QTaste is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QTaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with QTaste. If not, see <http://www.gnu.org/licenses/>. */ package com.qspin.qtaste.javagui.server; import java.awt.Component; import javax.swing.AbstractButton; import javax.swing.JLabel; import javax.swing.text.JTextComponent; import com.qspin.qtaste.testsuite.QTasteException; class TextGetter extends ComponentCommander { @Override public String executeCommand(int timeout, String componentName, Object... data) throws QTasteException { Component c = getComponentByName(componentName); if (c != null) { if (c instanceof JLabel) { return ((JLabel) c).getText(); } else if (c instanceof JTextComponent) { return ((JTextComponent) c).getText(); } else if (c instanceof AbstractButton) { return ((AbstractButton) c).getText(); } } return null; } }
gpl-3.0
yangyunfei/V_Recruitment
src/main/java/com/lianjia/model/Agent.java
1712
package com.lianjia.model; import com.jfinal.plugin.activerecord.Model; public class Agent extends Model<Agent> { private static final long serialVersionUID = -6080960523096072292L; public static final Agent dao = new Agent(); /** * 跟新经纪人信息 * @param agentElement 数据库中的信息 * @param agent 新查出来的信息 * @author yangyunfei * @created 2015年11月8日 下午5:11:12 */ public static void updateInfo(Agent agentElement, Agent agent) { //属性 mail name title department sAMAccountName mobile //是否需要更新属性 boolean flag = false; //mail if(!agentElement.getStr("mail").equals(agent.getStr("mail"))) { flag = flag||true; agentElement.set("mail", agent.getStr("mail")); } //name if(!agentElement.getStr("name").equals(agent.getStr("name"))) { flag = flag||true; agentElement.set("name", agent.getStr("name")); } //title if(!agentElement.getStr("title").equals(agent.getStr("title"))) { flag = flag||true; agentElement.set("title", agent.getStr("title")); } //department if(!agentElement.getStr("department").equals(agent.getStr("department"))) { flag = flag||true; agentElement.set("department", agent.getStr("department")); } //sAMAccountName if(!agentElement.getStr("sAMAccountName").equals(agent.getStr("sAMAccountName"))) { flag = flag||true; agentElement.set("sAMAccountName", agent.getStr("sAMAccountName")); } //mobile if(!agentElement.getStr("mobile").equals(agent.getStr("mobile"))) { flag = flag||true; agentElement.set("mobile", agent.getStr("mobile")); } //是否需要更新 if(flag) { agentElement.update(); } } }
gpl-3.0
hurdad/shipstation-api
src/main/java/com/apex/shipstation/model/ListOrders.java
726
package com.apex.shipstation.model; import java.util.List; public class ListOrders { private List<Order> orders; private int total; private int page; private int pages; public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } }
gpl-3.0
jottyfan/JottysMod
src/main/java/de/jotty/mymod/trader/TraderEvent.java
2439
package de.jotty.mymod.trader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import de.jotty.mymod.Name; import de.jotty.mymod.ProxyInterface; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.village.MerchantRecipe; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * * @author jotty * */ public class TraderEvent { private ProxyInterface proxyInterface; public TraderEvent(ProxyInterface proxyInterface) { this.proxyInterface = proxyInterface; } /** * @param event */ @SubscribeEvent public void onTrade(PlayerInteractEvent.EntityInteract event) { if (proxyInterface.isServerSide()) { if (event.getTarget() instanceof EntityVillager) { EntityVillager villager = (EntityVillager) event.getTarget(); Iterator<MerchantRecipe> iterator = villager.getRecipes(villager.getCustomer()).iterator(); List<MerchantRecipe> newRecipes = new ArrayList<MerchantRecipe>(); while (iterator.hasNext()) { MerchantRecipe oldRecipe = iterator.next(); MerchantRecipe newRecipe = oldRecipe; iterator.remove(); // with a chance of 20%, change emerald to silver coin if (oldRecipe.getItemToBuy().getItem().equals(Items.EMERALD)) { if (new Random().nextInt(10) < 2) { newRecipe = new MerchantRecipe(oldRecipe.getItemToBuy(), Name.SILVERCOIN.asItem()); } } else if (oldRecipe.getItemToSell().getItem().equals(Items.EMERALD)) { if (new Random().nextInt(10) < 2) { newRecipe = new MerchantRecipe(new ItemStack(Name.SILVERCOIN.asItem()), oldRecipe.getItemToSell().getItem()); } } // with a chance of 50%, change emerald to gold coin if (oldRecipe.getItemToBuy().getItem().equals(Items.EMERALD)) { if (new Random().nextInt(10) < 5) { newRecipe = new MerchantRecipe(oldRecipe.getItemToBuy(), Name.COIN.asItem()); } } else if (oldRecipe.getItemToSell().getItem().equals(Items.EMERALD)) { if (new Random().nextInt(10) < 5) { newRecipe = new MerchantRecipe(new ItemStack(Name.COIN.asItem()), oldRecipe.getItemToSell().getItem()); } } newRecipes.add(newRecipe); } villager.getRecipes(villager.getCustomer()).addAll(newRecipes); } } } }
gpl-3.0
b3dgs/lionengine
lionengine-game/src/test/java/com/b3dgs/lionengine/game/feature/tile/map/collision/MapTileCollisionModelTest.java
11923
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionengine.game.feature.tile.map.collision; import static com.b3dgs.lionengine.UtilAssert.assertEquals; import static com.b3dgs.lionengine.UtilAssert.assertFalse; import static com.b3dgs.lionengine.UtilAssert.assertNull; import static com.b3dgs.lionengine.UtilAssert.assertThrows; import static com.b3dgs.lionengine.UtilAssert.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.Optional; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.b3dgs.lionengine.Media; import com.b3dgs.lionengine.Medias; import com.b3dgs.lionengine.game.feature.FeaturableModel; import com.b3dgs.lionengine.game.feature.Services; import com.b3dgs.lionengine.game.feature.Setup; import com.b3dgs.lionengine.game.feature.Transformable; import com.b3dgs.lionengine.game.feature.TransformableModel; import com.b3dgs.lionengine.game.feature.UtilSetup; import com.b3dgs.lionengine.game.feature.tile.map.MapTileGame; import com.b3dgs.lionengine.game.feature.tile.map.MapTileGroupModel; import com.b3dgs.lionengine.game.feature.tile.map.UtilMap; /** * Test {@link MapTileCollisionModel}. */ final class MapTileCollisionModelTest { /** Test configuration. */ private static Media config; /** * Prepare test. */ @BeforeAll public static void beforeTests() { Medias.setResourcesDirectory(System.getProperty("java.io.tmpdir")); config = UtilSetup.createConfig(MapTileCollisionModelTest.class); } /** * Clean up test. */ @AfterAll public static void afterTests() { assertTrue(config.getFile().delete()); Medias.setResourcesDirectory(null); } private final CollisionFormula formulaV = new CollisionFormula("y", new CollisionRange(Axis.Y, 0, 1, 0, 1), new CollisionFunctionLinear(0.0, 0.0), new CollisionConstraint()); private final CollisionFormula formulaH = new CollisionFormula("x", new CollisionRange(Axis.X, 0, 1, 0, 1), new CollisionFunctionLinear(0.0, 0.0), new CollisionConstraint()); private final CollisionGroup group = new CollisionGroup(UtilMap.GROUND, Arrays.asList(formulaV, formulaH)); private final CollisionCategory categoryY = new CollisionCategory("y", Axis.Y, 0, 0, true, Arrays.asList(group)); private final CollisionCategory categoryX = new CollisionCategory("x", Axis.X, 0, 0, true, Arrays.asList(group)); private final Services services = new Services(); private final MapTileGame map = services.add(new MapTileGame()); private Transformable transformable; private MapTileCollision mapCollision; private Media formulasConfig; private Media groupsConfig; /** * Prepare test. */ @BeforeEach public void prepare() { map.addFeature(new MapTileGroupModel()); map.create(1, 1, 3, 3); UtilMap.setGroups(map); UtilMap.fill(map, UtilMap.TILE_GROUND); mapCollision = map.addFeatureAndGet(new MapTileCollisionModel()); mapCollision.prepare(map); formulasConfig = UtilConfig.createFormulaConfig(formulaV, formulaH); groupsConfig = UtilConfig.createGroupsConfig(group); mapCollision.loadCollisions(formulasConfig, groupsConfig); transformable = createObject(); } /** * Clean test. */ @AfterEach public void clean() { assertTrue(formulasConfig.getFile().delete()); assertTrue(groupsConfig.getFile().delete()); } /** * Test the map tile collision from top. */ @Test void testFromTop() { transformable.teleport(1.0, 3.0); transformable.moveLocation(1.0, 0.0, -2.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryY); assertNull(result.getX()); assertEquals(Double.valueOf(2.0), result.getY()); } /** * Test the map tile collision from top wit fast speed. */ @Test void testFromTopFast() { transformable.teleport(1.0, 3.0); transformable.moveLocation(1.0, 0.0, -20.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryY); assertNull(result.getX()); assertEquals(Double.valueOf(2.0), result.getY()); } /** * Test the map tile collision from bottom. */ @Test void testFromBottom() { transformable.teleport(1.0, -1.0); transformable.moveLocation(1.0, 0.0, 3.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryY); assertNull(result.getX()); assertEquals(Double.valueOf(0.0), result.getY()); } /** * Test the map tile collision from bottom with fast speed. */ @Test void testFromBottomFast() { transformable.teleport(1.0, -1.0); transformable.moveLocation(1.0, 0.0, 20.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryY); assertNull(result.getX()); assertEquals(Double.valueOf(0.0), result.getY()); } /** * Test the map tile collision from left. */ @Test void testFromLeft() { transformable.teleport(-1.0, 0.0); transformable.moveLocation(1.0, 2.0, 0.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result.getY()); assertEquals(Double.valueOf(0.0), result.getX()); } /** * Test the map tile collision from left with fast speed. */ @Test void testFromLeftFast() { transformable.teleport(-1.0, 0.0); transformable.moveLocation(1.0, 20.0, 0.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result.getY()); assertEquals(Double.valueOf(0.0), result.getX()); } /** * Test the map tile collision from right. */ @Test void testFromRight() { transformable.teleport(2.0, 0.0); transformable.moveLocation(1.0, -1.0, 0.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result.getY()); assertEquals(Double.valueOf(2.0), result.getX()); } /** * Test the map tile collision from right with fast speed. */ @Test void testFromRightFast() { transformable.teleport(2.0, 0.0); transformable.moveLocation(1.0, -20.0, 0.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result.getY()); assertEquals(Double.valueOf(2.0), result.getX()); } /** * Test the map tile no collision. */ @Test void testNoCollision() { transformable.teleport(6.0, 6.0); transformable.moveLocation(1.0, 1.0, 1.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result); } /** * Test the map tile no collision formula defined. */ @Test void testNoCollisionFormula() { mapCollision.loadCollisions(new CollisionFormulaConfig(Collections.emptyMap()), new CollisionGroupConfig(Collections.emptyMap())); transformable.teleport(6.0, 0.0); transformable.moveLocation(1.0, -5.0, 0.0); final CollisionResult result = mapCollision.computeCollision(transformable, categoryX); assertNull(result); } /** * Test the map tile collision getters. */ @Test void testGetter() { assertEquals(formulaV, mapCollision.getCollisionFormula("y")); assertEquals(formulaH, mapCollision.getCollisionFormula("x")); assertEquals(Optional.of(group), mapCollision.getCollisionGroup(UtilMap.GROUND)); assertTrue(mapCollision.getCollisionFormulas().containsAll(Arrays.asList(formulaV, formulaH))); assertTrue(mapCollision.getCollisionGroups().containsAll(Arrays.asList(group))); assertEquals(formulasConfig, mapCollision.getFormulasConfig()); assertEquals(groupsConfig, mapCollision.getCollisionsConfig()); } /** * Test the map tile collision saving. */ @Test void testSaveCollision() { mapCollision.saveCollisions(); mapCollision.loadCollisions(formulasConfig, groupsConfig); assertTrue(mapCollision.getCollisionFormulas().containsAll(Arrays.asList(formulaV, formulaH))); assertTrue(mapCollision.getCollisionGroups().containsAll(Arrays.asList(group))); } /** * Test the map tile collision loading without configuration. */ @Test void testLoadCollisionWithout() { final MapTileCollision mapTileCollision = new MapTileCollisionModel(); mapTileCollision.prepare(map); mapTileCollision.loadCollisions(Medias.create("void"), Medias.create("void2")); assertTrue(mapTileCollision.getCollisionFormulas().isEmpty()); assertTrue(mapTileCollision.getCollisionGroups().isEmpty()); } /** * Test the map tile collision unknown formula. */ @Test void testUnknownFormula() { assertThrows(() -> mapCollision.getCollisionFormula("void"), MapTileCollisionLoader.ERROR_FORMULA + "void"); } /** * Test the map tile collision unknown group. */ @Test void testUnknownGroup() { assertFalse(mapCollision.getCollisionGroup("void").isPresent()); } /** * Create object test. * * @return The object test. */ private Transformable createObject() { final Setup setup = new Setup(config); CollisionCategoryConfig.exports(setup.getRoot(), categoryY); CollisionCategoryConfig.exports(setup.getRoot(), categoryX); final FeaturableModel object = new FeaturableModel(services, setup); final Transformable transformable = object.addFeatureAndGet(new TransformableModel(services, setup)); transformable.setSize(1, 1); final TileCollidable collidable = object.addFeatureAndGet(new TileCollidableModel(services, setup)); collidable.setEnabled(true); return transformable; } }
gpl-3.0
huby/java-se8-oca-study-guide
src/main/java/manning/mockExam/mockExamQuestion72/manning/chapter04/period/manipulatingLocalDateAndLocalDateTimeUsingPeriod/Main.java
1155
package manning.mockExam.mockExamQuestion72.manning.chapter04.period.manipulatingLocalDateAndLocalDateTimeUsingPeriod; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; /** * Created by Hector Huby on 19/04/2017. */ public class Main { public static void main(String[] args) { LocalDate date = LocalDate.of(2052, 01, 31); System.out.println(date.minus(Period.ofDays(1))); // Because Period instances can represent positive or negative periods // (like 15 days and -15 days), you can subtract days from a LocalDate or // LocalDateTime by calling the method plus System.out.println(date.plus(Period.ofDays(-1))); // Similarly, the method minus() with the classes LocalDate and LocalDateTime // to subtract a period of years, month, weeks, or days LocalDateTime dateTime = LocalDateTime.parse("2020-01-31T14:18:36"); System.out.println(dateTime.minus(Period.ofYears(2))); LocalDate localDate = LocalDate.of(2052, 01, 31); System.out.println(localDate.minus(Period.ofWeeks(4))); } }
gpl-3.0
LexMinecraft/Launcher
src/main/java/com/atlauncher/gui/dialogs/ViewModsDialog.java
4490
/* * ATLauncher - https://github.com/ATLauncher/ATLauncher * Copyright (C) 2013 ATLauncher * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.atlauncher.gui.dialogs; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import com.atlauncher.App; import com.atlauncher.data.Language; import com.atlauncher.data.Mod; import com.atlauncher.data.Pack; import com.atlauncher.gui.card.ModCard; import com.atlauncher.utils.Utils; public final class ViewModsDialog extends JDialog { private final Pack pack; private final JPanel contentPanel = new JPanel(new GridBagLayout()); private final JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); private final JTextField searchField = new JTextField(16); private final List<ModCard> cards = new LinkedList<ModCard>(); public ViewModsDialog(Pack pack) { super(App.settings.getParent(), Language.INSTANCE.localizeWithReplace("pack.mods", pack.getName()), ModalityType.APPLICATION_MODAL); this.pack = pack; this.setIconImage(Utils.getImage("/assets/image/Icon.png")); this.setPreferredSize(new Dimension(550, 450)); this.setResizable(false); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.topPanel.add(new JLabel(Language.INSTANCE.localize("common.search") + ": ")); this.topPanel.add(this.searchField); this.add(this.topPanel, BorderLayout.NORTH); this.add(new JScrollPane(this.contentPanel) { { this.getVerticalScrollBar().setUnitIncrement(16); } }, BorderLayout.CENTER); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.BOTH; gbc.insets.set(2, 2, 2, 2); this.searchField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { reload(); } }); List<Mod> mods = this.pack.getMods(this.pack.getLatestVersion().getVersion(), false); Collections.sort(mods, new Comparator<Mod>() { @Override public int compare(Mod o1, Mod o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); for (Mod mod : mods) { ModCard card = new ModCard(mod); cards.add(card); contentPanel.add(card, gbc); gbc.gridy++; } this.pack(); this.setLocationRelativeTo(App.settings.getParent()); } private void reload() { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.BOTH; gbc.insets.set(2, 2, 2, 2); this.contentPanel.removeAll(); for (ModCard card : this.cards) { boolean show = true; if (!this.searchField.getText().isEmpty()) { if (!Pattern.compile(Pattern.quote(this.searchField.getText()), Pattern.CASE_INSENSITIVE).matcher (card.mod.getName()).find()) { show = false; } } if (show) { this.contentPanel.add(card, gbc); gbc.gridy++; } } revalidate(); repaint(); } }
gpl-3.0
Zowja/New-Frontier-Craft
src/minecraft/net/minecraft/src/RenderPlayer.java
13397
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode package net.minecraft.src; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.imageio.ImageIO; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; // Referenced classes of package net.minecraft.src: // RenderLiving, ModelBiped, EntityPlayer, InventoryPlayer, // ItemStack, ItemArmor, ModelRenderer, EntityPlayerSP, // RenderManager, Tessellator, FontRenderer, Item, // Block, RenderBlocks, ItemRenderer, MathHelper, // EntityLiving, Entity public class RenderPlayer extends RenderLiving { public RenderPlayer() { super(new ModelPlayer(0.0F), 0.5F); modelBipedMain = (ModelPlayer) mainModel; modelArmorChestplate = new ModelBiped(1.0F); modelArmor = new ModelBiped(0.5F); modelAlex = new ModelPlayerAlex(0.0F); modelSteve = new ModelPlayer(0.0F); } protected boolean setArmorModel(EntityPlayer entityplayer, int i, float f) { ItemStack itemstack = entityplayer.inventory.armorItemInSlot(3 - i); if (itemstack != null) { Item item = itemstack.getItem(); if (item instanceof ItemArmor) { ItemArmor itemarmor = (ItemArmor) item; loadTexture((new StringBuilder()).append("/armor/") .append(armorFilenamePrefix[itemarmor.renderIndex]) .append("_").append(i != 2 ? 1 : 2).append(".png") .toString()); ModelBiped modelbiped = (i != 2 ? modelArmorChestplate : modelArmor); modelbiped.bipedHead.showModel = i == 0; modelbiped.bipedHeadwear.showModel = i == 0; modelbiped.bipedBody.showModel = i == 1 || i == 2; modelbiped.bipedRightArm.showModel = i == 1; modelbiped.bipedLeftArm.showModel = i == 1; modelbiped.bipedRightLeg.showModel = i == 2 || i == 3; modelbiped.bipedLeftLeg.showModel = i == 2 || i == 3; setRenderPassModel(modelbiped); return true; } } return false; } public void renderPlayer(EntityPlayer entityplayer, double d, double d1, double d2, float f, float f1) { // Temporary? Solution to alex model if(entityplayer.modelAlex){ mainModel = modelAlex; modelBipedMain = modelAlex; } else { mainModel = modelSteve; modelBipedMain = modelSteve; } ItemStack itemstack = entityplayer.inventory.getCurrentItem(); modelArmorChestplate.field_1278_i = modelArmor.field_1278_i = modelBipedMain.field_1278_i = itemstack != null; modelArmorChestplate.isSneak = modelArmor.isSneak = modelBipedMain.isSneak = entityplayer .isSneaking(); double d3 = d1 - (double) entityplayer.yOffset; if (entityplayer.isSneaking() && !(entityplayer instanceof EntityPlayerSP)) { d3 -= 0.125D; } super.doRenderLiving(entityplayer, d, d3, d2, f, f1); modelArmorChestplate.isSneak = modelArmor.isSneak = modelBipedMain.isSneak = false; modelArmorChestplate.field_1278_i = modelArmor.field_1278_i = modelBipedMain.field_1278_i = false; } protected void renderName(EntityPlayer entityplayer, double d, double d1, double d2) { if (Minecraft.isGuiEnabled() && entityplayer != renderManager.livingPlayer) { float f = 1.6F; float f1 = 0.01666667F * f; float f2 = entityplayer .getDistanceToEntity(renderManager.livingPlayer); float f3 = entityplayer.isSneaking() ? 32F : 64F; if (f2 < f3) { String s = entityplayer.username; if (!entityplayer.isSneaking()) { if (entityplayer.isPlayerSleeping()) { renderLivingLabel(entityplayer, s, d, d1 - 1.5D, d2, 64); } else { renderLivingLabel(entityplayer, s, d, d1, d2, 64); } } else { FontRenderer fontrenderer = getFontRendererFromRenderManager(); GL11.glPushMatrix(); GL11.glTranslatef((float) d + 0.0F, (float) d1 + 2.3F, (float) d2); GL11.glNormal3f(0.0F, 1.0F, 0.0F); GL11.glRotatef(-renderManager.playerViewY, 0.0F, 1.0F, 0.0F); GL11.glRotatef(renderManager.playerViewX, 1.0F, 0.0F, 0.0F); GL11.glScalef(-f1, -f1, f1); GL11.glDisable(2896 /* GL_LIGHTING */); GL11.glTranslatef(0.0F, 0.25F / f1, 0.0F); GL11.glDepthMask(false); GL11.glEnable(3042 /* GL_BLEND */); GL11.glBlendFunc(770, 771); Tessellator tessellator = Tessellator.instance; GL11.glDisable(3553 /* GL_TEXTURE_2D */); tessellator.startDrawingQuads(); int i = fontrenderer.getStringWidth(s) / 2; tessellator.setColorRGBA_F(0.0F, 0.0F, 0.0F, 0.25F); tessellator.addVertex(-i - 1, -1D, 0.0D); tessellator.addVertex(-i - 1, 8D, 0.0D); tessellator.addVertex(i + 1, 8D, 0.0D); tessellator.addVertex(i + 1, -1D, 0.0D); tessellator.draw(); GL11.glEnable(3553 /* GL_TEXTURE_2D */); GL11.glDepthMask(true); fontrenderer.drawString(s, -fontrenderer.getStringWidth(s) / 2, 0, 0x20ffffff); GL11.glEnable(2896 /* GL_LIGHTING */); GL11.glDisable(3042 /* GL_BLEND */); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glPopMatrix(); } } } } protected void renderSpecials(EntityPlayer entityplayer, float f) { ItemStack itemstack = entityplayer.inventory.armorItemInSlot(3); if (itemstack != null && itemstack.getItem().shiftedIndex < 256) { GL11.glPushMatrix(); modelBipedMain.bipedHead.postRender(0.0625F); if (RenderBlocks.renderItemIn3d(Block.blocksList[itemstack.itemID] .getRenderType())) { float f1 = 0.625F; GL11.glTranslatef(0.0F, -0.25F, 0.0F); GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F); GL11.glScalef(f1, -f1, f1); } renderManager.itemRenderer.renderItem(entityplayer, itemstack); GL11.glPopMatrix(); } if (entityplayer.username.equals("deadmau5") && loadDownloadableImageTexture(entityplayer.skinUrl, null)) { for (int i = 0; i < 2; i++) { float f2 = (entityplayer.prevRotationYaw + (entityplayer.rotationYaw - entityplayer.prevRotationYaw) * f) - (entityplayer.prevRenderYawOffset + (entityplayer.renderYawOffset - entityplayer.prevRenderYawOffset) * f); float f6 = entityplayer.prevRotationPitch + (entityplayer.rotationPitch - entityplayer.prevRotationPitch) * f; GL11.glPushMatrix(); GL11.glRotatef(f2, 0.0F, 1.0F, 0.0F); GL11.glRotatef(f6, 1.0F, 0.0F, 0.0F); GL11.glTranslatef(0.375F * (float) (i * 2 - 1), 0.0F, 0.0F); GL11.glTranslatef(0.0F, -0.375F, 0.0F); GL11.glRotatef(-f6, 1.0F, 0.0F, 0.0F); GL11.glRotatef(-f2, 0.0F, 1.0F, 0.0F); float f7 = 1.333333F; GL11.glScalef(f7, f7, f7); modelBipedMain.renderEars(0.0625F); GL11.glPopMatrix(); } } if (loadDownloadableImageTexture(entityplayer.playerCloakUrl, null)) { GL11.glPushMatrix(); GL11.glTranslatef(0.0F, 0.0F, 0.125F); double d = (entityplayer.field_20066_r + (entityplayer.field_20063_u - entityplayer.field_20066_r) * (double) f) - (entityplayer.prevPosX + (entityplayer.posX - entityplayer.prevPosX) * (double) f); double d1 = (entityplayer.field_20065_s + (entityplayer.field_20062_v - entityplayer.field_20065_s) * (double) f) - (entityplayer.prevPosY + (entityplayer.posY - entityplayer.prevPosY) * (double) f); double d2 = (entityplayer.field_20064_t + (entityplayer.field_20061_w - entityplayer.field_20064_t) * (double) f) - (entityplayer.prevPosZ + (entityplayer.posZ - entityplayer.prevPosZ) * (double) f); float f8 = entityplayer.prevRenderYawOffset + (entityplayer.renderYawOffset - entityplayer.prevRenderYawOffset) * f; double d3 = MathHelper.sin((f8 * 3.141593F) / 180F); double d4 = -MathHelper.cos((f8 * 3.141593F) / 180F); float f9 = (float) d1 * 10F; if (f9 < -6F) { f9 = -6F; } if (f9 > 32F) { f9 = 32F; } float f10 = (float) (d * d3 + d2 * d4) * 100F; float f11 = (float) (d * d4 - d2 * d3) * 100F; if (f10 < 0.0F) { f10 = 0.0F; } float f12 = entityplayer.field_775_e + (entityplayer.field_774_f - entityplayer.field_775_e) * f; f9 += MathHelper .sin((entityplayer.prevDistanceWalkedModified + (entityplayer.distanceWalkedModified - entityplayer.prevDistanceWalkedModified) * f) * 6F) * 32F * f12; if (entityplayer.isSneaking()) { f9 += 25F; } GL11.glRotatef(6F + f10 / 2.0F + f9, 1.0F, 0.0F, 0.0F); GL11.glRotatef(f11 / 2.0F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(-f11 / 2.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F); modelBipedMain.renderCloak(0.0625F); GL11.glPopMatrix(); } ItemStack itemstack1 = entityplayer.inventory.getCurrentItem(); if (itemstack1 != null) { GL11.glPushMatrix(); modelBipedMain.bipedRightArm.postRender(0.0625F); GL11.glTranslatef(-0.0625F, 0.4375F, 0.0625F); if (entityplayer.fishEntity != null) { itemstack1 = new ItemStack(Item.stick); } if (itemstack1.itemID < 256 && RenderBlocks .renderItemIn3d(Block.blocksList[itemstack1.itemID] .getRenderType())) { float f3 = 0.5F; GL11.glTranslatef(0.0F, 0.1875F, -0.3125F); f3 *= 0.75F; GL11.glRotatef(20F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45F, 0.0F, 1.0F, 0.0F); GL11.glScalef(f3, -f3, f3); } else if (Item.itemsList[itemstack1.itemID].isFull3D()) { float f4 = 0.625F; if (Item.itemsList[itemstack1.itemID] .shouldRotateAroundWhenRendering()) { GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(0.0F, -0.125F, 0.0F); } GL11.glTranslatef(0.0F, 0.1875F, 0.0F); GL11.glScalef(f4, -f4, f4); GL11.glRotatef(-100F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45F, 0.0F, 1.0F, 0.0F); } else { float f5 = 0.375F; GL11.glTranslatef(0.25F, 0.1875F, -0.1875F); GL11.glScalef(f5, f5, f5); GL11.glRotatef(60F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(-90F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(20F, 0.0F, 0.0F, 1.0F); } renderManager.itemRenderer.renderItem(entityplayer, itemstack1); GL11.glPopMatrix(); } } protected void func_186_b(EntityPlayer entityplayer, float f) { float f1 = 0.9375F; GL11.glScalef(f1, f1, f1); } public void drawFirstPersonHand(boolean alex) { if(alex){ mainModel = modelAlex; modelBipedMain = modelAlex; } modelBipedMain.onGround = 0.0F; modelBipedMain.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F); modelBipedMain.bipedRightArm.render(0.0625F); modelBipedMain.field_178732_b.render(0.0625F); } protected void func_22016_b(EntityPlayer entityplayer, double d, double d1, double d2) { if (entityplayer.isEntityAlive() && entityplayer.isPlayerSleeping()) { super.func_22012_b(entityplayer, d + (double) entityplayer.field_22063_x, d1 + (double) entityplayer.field_22062_y, d2 + (double) entityplayer.field_22061_z); } else { super.func_22012_b(entityplayer, d, d1, d2); } } protected void func_22017_a(EntityPlayer entityplayer, float f, float f1, float f2) { if (entityplayer.isEntityAlive() && entityplayer.isPlayerSleeping()) { GL11.glRotatef(entityplayer.getBedOrientationInDegrees(), 0.0F, 1.0F, 0.0F); GL11.glRotatef(getDeathMaxRotation(entityplayer), 0.0F, 0.0F, 1.0F); GL11.glRotatef(270F, 0.0F, 1.0F, 0.0F); } else { super.rotateCorpse(entityplayer, f, f1, f2); } } protected void passSpecialRender(EntityLiving entityliving, double d, double d1, double d2) { renderName((EntityPlayer) entityliving, d, d1, d2); } protected void preRenderCallback(EntityLiving entityliving, float f) { func_186_b((EntityPlayer) entityliving, f); } protected boolean shouldRenderPass(EntityLiving entityliving, int i, float f) { return setArmorModel((EntityPlayer) entityliving, i, f); } protected void renderEquippedItems(EntityLiving entityliving, float f) { renderSpecials((EntityPlayer) entityliving, f); } protected void rotateCorpse(EntityLiving entityliving, float f, float f1, float f2) { func_22017_a((EntityPlayer) entityliving, f, f1, f2); } protected void func_22012_b(EntityLiving entityliving, double d, double d1, double d2) { func_22016_b((EntityPlayer) entityliving, d, d1, d2); } public void doRenderLiving(EntityLiving entityliving, double d, double d1, double d2, float f, float f1) { renderPlayer((EntityPlayer) entityliving, d, d1, d2, f, f1); } public void doRender(Entity entity, double d, double d1, double d2, float f, float f1) { renderPlayer((EntityPlayer) entity, d, d1, d2, f, f1); } private ModelPlayer modelBipedMain; private ModelBiped modelArmorChestplate; private ModelBiped modelArmor; private ModelPlayerAlex modelAlex; private ModelPlayer modelSteve; private static final String armorFilenamePrefix[] = { "cloth", "chain", "iron", "diamond", "gold", "aluminum", "bismuth", "boron", "brass", "bronze", "chrome", "cobalt", "copper", "nickel", "platinum", "silicon", "silver", "steel", "tin", "titanium", "tungsten", "zinc", "osmium", "ruby", "sapphire", "emerald" }; }
gpl-3.0
legomolina/Clothy-app
src/models/SaleLine.java
2645
package models; import javafx.beans.binding.Bindings; import javafx.beans.property.*; public class SaleLine { private IntegerProperty id; private ObjectProperty<Article> article; private Sale sale; private FloatProperty discount; private IntegerProperty quantity; private FloatProperty total; private BooleanProperty checked; public SaleLine(int id, Article article, Sale sale, float discount, int quantity) { this.id = new SimpleIntegerProperty(id); this.article = new SimpleObjectProperty<>(article); this.sale = sale; this.discount = new SimpleFloatProperty(discount); this.quantity = new SimpleIntegerProperty(quantity); this.checked = new SimpleBooleanProperty(false); this.total = new SimpleFloatProperty(); this.total.bind(Bindings.multiply(Bindings.subtract(Bindings.selectFloat(this.article, "price"), Bindings.multiply(Bindings.selectFloat(this.article, "price"), this.discount)), this.quantity)); } public int getId() { return id.get(); } public IntegerProperty idProperty() { return id; } public void setId(int id) { this.id.set(id); } public Article getArticle() { return article.get(); } public ObjectProperty<Article> articleProperty() { return article; } public void setArticle(Article article) { this.article.set(article); } public Sale getSale() { return sale; } public void setSale(Sale sale) { this.sale = sale; } public float getDiscount() { return discount.get(); } public FloatProperty discountProperty() { return discount; } public void setDiscount(float discount) { this.discount.set(discount); } public int getQuantity() { return quantity.get(); } public IntegerProperty quantityProperty() { return quantity; } public void setQuantity(int quantity) { this.quantity.set(quantity); } public boolean isChecked() { return checked.get(); } public BooleanProperty checkedProperty() { return checked; } public void setChecked(boolean checked) { this.checked.set(checked); } public float getTotal() { return total.get(); } public FloatProperty totalProperty() { return total; } @Override public boolean equals(Object object) { return object instanceof SaleLine && (this.id.get() == ((SaleLine) object).getId() && this.sale.getId() == ((SaleLine) object).getSale().getId()); } }
gpl-3.0
Booksonic-Server/madsonic-main
src/main/java/org/madsonic/service/MediaFileService.java
54379
/* This file is part of Madsonic. Madsonic is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Madsonic 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 Madsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009-2016 (C) Sindre Mehus, Martin Karel */ package org.madsonic.service; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.madsonic.Logger; import org.madsonic.dao.AlbumDao; import org.madsonic.dao.ArtistDao; import org.madsonic.dao.MediaFileDao; import org.madsonic.dao.MusicFolderDao; import org.madsonic.domain.Album; import org.madsonic.domain.Artist; import org.madsonic.domain.Genre; import org.madsonic.domain.MediaFile; import org.madsonic.domain.MediaFileComparator; import org.madsonic.domain.MediaFile.MediaType; import org.madsonic.domain.MusicFolder; import org.madsonic.service.metadata.FFmpegParser; import org.madsonic.service.metadata.JaudiotaggerParser; import org.madsonic.service.metadata.MetaData; import org.madsonic.service.metadata.MetaDataParser; import org.madsonic.service.metadata.MetaDataParserFactory; import org.madsonic.util.FileUtil; import org.madsonic.util.StringUtil; import org.madsonic.util.UrlFile; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.WordUtils; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.madsonic.domain.MediaFile.MediaType.*; /**MediaFileService * Provides services for instantiating and caching media files and cover art. * * @author Sindre Mehus, Martin Karel */ public class MediaFileService { private static final Logger LOG = Logger.getLogger(MediaFileService.class); private static final Pattern CHANNEL_PATTERN = Pattern.compile(".*http://.*/(.*)", Pattern.DOTALL); private Ehcache mediaFileMemoryCache; private SecurityService securityService; private SettingsService settingsService; private TranscodingService transcodingService; private MediaFileDao mediaFileDao; private MusicFolderDao musicFolderDao; private AlbumDao albumDao; private ArtistDao artistDao; private MetaDataParserFactory metaDataParserFactory; private boolean memoryCacheEnabled = true; /** * Returns a media file instance for the given file. If possible, a cached value is returned. * * @param file A file on the local file system. * @return A media file instance, or null if not found. * @throws SecurityException If access is denied to the given file. */ public MediaFile getMediaFile(File file) { return getMediaFile(file, settingsService.isFastCacheEnabled()); } /** * Returns a media file instance for the given file. If possible, a cached value is returned. * * @param file A file on the local file system. * @return A media file instance, or null if not found. * @throws SecurityException If access is denied to the given file. */ public MediaFile getMediaFile(File file, boolean useFastCache) { // Look in fast memory cache first. MediaFile result = getFromMemoryCache(file); if (result != null) { return result; } if (!securityService.isReadAllowed(file)) { throw new SecurityException("Access denied to file " + file); } // Secondly, look in database. result = mediaFileDao.getMediaFile(file.getPath()); if (result != null) { result = checkLastModified(result, useFastCache); putInMemoryCache(file, result); return result; } if (!FileUtil.exists(file)) { return null; } // Not found in database, must read from disk. result = createMediaFile(file); // Put in cache and database. putInMemoryCache(file, result); mediaFileDao.createOrUpdateMediaFile(result); return result; } public MediaFile getPodcastFile(File file) { return mediaFileDao.getPodcastFile(file.getPath()); } public void createOrUpdateMediaFile(MediaFile mediaFile) { mediaFileDao.createOrUpdateMediaFile(mediaFile); } public void createOrUpdateArtist(Artist artist) { artistDao.createOrUpdateArtist(artist); } public Artist getLowerArtist(String artistName) { return artistDao.getLowerArtist(artistName); } public Artist getArtistforName(String artistName){ if (artistName == null) { return null; } Artist a = new Artist(); a = artistDao.getArtist(artistName); if (a == null) { a = artistDao.getArtistFolder(artistName); } return a; } public Integer getIdForTrack(String Artist, String TrackName){ return mediaFileDao.getIdForTrack(Artist, TrackName); } public Integer getIdsForAlbums(String albumName){ return mediaFileDao.getIdsForAlbums(albumName); } public Integer getIdsForAlbums(String artistName, String albumName){ return mediaFileDao.getIdsForAlbums(artistName, albumName); } public Integer getIDfromArtistname(String artistName){ return mediaFileDao.getIDfromArtistname(artistName); } public MediaFile getMediaFile(String artist, String title){ return mediaFileDao.getMediaFile(artist, title); } @Deprecated public MediaFile getMediaFile(String artist, String alternate, String title){ return mediaFileDao.getMediaFile(artist, alternate, title); } @Deprecated public MediaFile getMediaFileTitle(String title){ return mediaFileDao.getMediaFileTitle(title); } public List<Artist> getAllArtists(){ return artistDao.getAllArtists(); } public MediaFile getMediaFileIfExists(File file) { return mediaFileDao.getMediaFile(file.getPath()); } private MediaFile checkLastModified(MediaFile mediaFile, boolean useFastCache) { if (useFastCache || mediaFile.getChanged().getTime() >= FileUtil.lastModified(mediaFile.getFile())) { return mediaFile; } mediaFile = createMediaFile(mediaFile.getFile()); mediaFileDao.createOrUpdateMediaFile(mediaFile); return mediaFile; } /** * Returns a media file instance for the given path name. If possible, a cached value is returned. * * @param pathName A path name for a file on the local file system. * @return A media file instance. * @throws SecurityException If access is denied to the given file. */ public MediaFile getMediaFile(String pathName) { return getMediaFile(new File(pathName)); } // TODO: Optimize with memory caching. public MediaFile getMediaFile(int id, int user_group_id) { MediaFile mediaFile = mediaFileDao.getMediaFile(id); if (mediaFile == null) { return null; } if (securityService.isAccessAllowed(mediaFile.getFile(), user_group_id) == false ) { return null; } else { if (!securityService.isReadAllowed(mediaFile.getFile(), user_group_id )) { throw new SecurityException("Access denied to file " + mediaFile); } } return checkLastModified(mediaFile, settingsService.isFastCacheEnabled()); } public MediaFile getMediaFile(int id) { MediaFile mediaFile = mediaFileDao.getMediaFile(id); if (mediaFile == null) { return null; } if (!mediaFile.getPath().startsWith("http")) { if (!securityService.isReadAllowed(mediaFile.getFile())) { throw new SecurityException("Access denied to file " + mediaFile); } } return checkLastModified(mediaFile, settingsService.isFastCacheEnabled()); } public MediaFile getParentOf(MediaFile mediaFile) { if (mediaFile.getParentPath() == null) { return null; } return getMediaFile(mediaFile.getParentPath()); } public List<MediaFile> getChildrenOf(String parentPath, boolean includeFiles, boolean includeDirectories, boolean sort) { return getChildrenOf(new File(parentPath), includeFiles, includeDirectories, sort); } public List<MediaFile> getChildrenOf(List<MediaFile> children, boolean includeFiles, boolean includeDirectories, boolean sort) { List<MediaFile> result = new ArrayList<MediaFile>(); for (MediaFile child : children) { if (child.isDirectory() && includeDirectories) { result.add(child); } if (child.isFile() && includeFiles) { result.add(child); } } return result; } public List<MediaFile> getChildrenOf(File parent, boolean includeFiles, boolean includeDirectories, boolean sort) { return getChildrenOf(getMediaFile(parent), includeFiles, includeDirectories, sort); } /** * Returns all media files that are children of a given media file. * * @param includeFiles Whether files should be included in the result. * @param includeDirectories Whether directories should be included in the result. * @param sort Whether to sort files in the same directory. * @return All children media files. */ public List<MediaFile> getChildrenOf(MediaFile parent, boolean includeFiles, boolean includeDirectories, boolean sort) { return getChildrenOf(parent, includeFiles, includeDirectories, sort, settingsService.isFastCacheEnabled()); } /** * Returns all media files that are children of a given media file. * * @param includeFiles Whether files should be included in the result. * @param includeDirectories Whether directories should be included in the result. * @param sort Whether to sort files in the same directory. * @return All children media files. */ public List<MediaFile> getChildrenOf(MediaFile parent, boolean includeFiles, boolean includeDirectories, boolean sort, boolean useFastCache) { if (!parent.isDirectory()) { return Collections.emptyList(); } // Make sure children are stored and up-to-date in the database. if (parent != null && !useFastCache) { updateChildren(parent); } List<MediaFile> result = new ArrayList<MediaFile>(); for (MediaFile child : mediaFileDao.getChildrenOf(parent.getPath())) { child = checkLastModified(child, useFastCache); if (child.isDirectory() && includeDirectories) { settingsService.getNewaddedTimespan(); if (isNewAdded(child, settingsService.getNewaddedTimespan())) { child.setNewAdded(true); } result.add(child); } if (child.isFile() && includeFiles) { result.add(child); } } if (sort) { Comparator<MediaFile> comparator = new MediaFileComparator(settingsService.isSortAlbumsByFolder()); // settingsService.isSortFilesByFilename() // Note: Intentionally not using Collections.sort() since it can be problematic on Java 7. // http://www.oracle.com/technetwork/java/javase/compatibility-417013.html#jdk7 Set<MediaFile> set = new TreeSet<MediaFile>(comparator); set.addAll(result); result = new ArrayList<MediaFile>(set); } return result; } public List<MediaFile> getChildrenSorted(List<MediaFile> result, boolean sort) { if (sort) { Comparator<MediaFile> comparator = new MediaFileComparator(settingsService.isSortAlbumsByFolder()); // settingsService.isSortFilesByFilename() Set<MediaFile> set = new TreeSet<MediaFile>(comparator); set.addAll(result); result = new ArrayList<MediaFile>(set); } return result; } public List<MediaFile> getTopTracks(String artist, int userGroupId) { return mediaFileDao.getTopTracks(artist, userGroupId); } public List<MediaFile> getTopTracks(int count, String artist, int userGroupId) { return mediaFileDao.getTopTracks(count, artist, userGroupId); } /** * Returns whether the given file is the root of a media folder. * * @see MusicFolder */ public boolean isRoot(MediaFile mediaFile) { for (MusicFolder musicFolder : settingsService.getAllMusicFolders(false, true)) { if (mediaFile.getPath().equals(musicFolder.getPath().getPath())) { return true; } } return false; } /** * Returns all genres in the music collection. * * @return Sorted list of genres. */ public List<String> getGenres(int user_group_id) { return mediaFileDao.getGenres(user_group_id); } public List<Genre> getGenres(boolean sortByAlbum) { return mediaFileDao.getGenres(sortByAlbum); } public List<String> getGenres() { return mediaFileDao.getGenre(); } public List<Genre> getGenreSongList() { return mediaFileDao.getGenreSongList(); } public List<Genre> getGenreArtistList() { return mediaFileDao.getGenreArtistList(); } public List<Genre> getGenreAlbumList() { return mediaFileDao.getGenreAlbumList(); } public List<String> getArtistGenres() { return mediaFileDao.getArtistGenres(); } public int getGenreSongCount() { return mediaFileDao.getGenreSongCount(); } public int getGenreArtistCount() { return mediaFileDao.getGenreArtistCount(); } public int getGenreAlbumCount() { return mediaFileDao.getGenreAlbumCount(); } public List<String> getArtistGenresforFolder(List<MusicFolder> musicFoldersToUse, int userGroupId) { List<String> tempList = new ArrayList<String>(); for (MusicFolder mf : musicFoldersToUse) { tempList.addAll(mediaFileDao.getArtistGenresforFolder(mf.getId(), userGroupId)); } // capitalize and filter out duplicates HashSet<String> hs = new HashSet<String>(); for (String genre : tempList) { genre = WordUtils.capitalize(genre); hs.add(genre); } tempList.clear(); tempList.addAll(hs); Collections.sort(tempList); return tempList; } public List<String> getMoods() { return mediaFileDao.getMoods(); } public List<String> getLowerMoods() { return mediaFileDao.getLowerMoods(); } /** * Returns the most frequently played albums. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @return The most frequently played albums. */ public List<MediaFile> getMostFrequentlyPlayedAlbums(int offset, int count, int user_group_id) { return mediaFileDao.getMostFrequentlyPlayedAlbums(offset, count, user_group_id); } public List<MediaFile> getMostFrequentlyPlayedAlbums(List<MusicFolder> musicFolders, int offset, int count) { return mediaFileDao.getMostFrequentlyPlayedAlbums(musicFolders, offset, count); } /** * Returns the most recently played albums. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @return The most recently played albums. */ public List<MediaFile> getMostRecentlyPlayedAlbums(int offset, int count, int user_group_id) { return mediaFileDao.getMostRecentlyPlayedAlbums(offset, count, user_group_id); } public List<MediaFile> getMostRecentlyPlayedAlbums(List<MusicFolder> musicFolders, int offset, int count) { return mediaFileDao.getMostRecentlyPlayedAlbums(musicFolders, offset, count); } /** * Returns the most recently added albums. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @return The most recently added albums. */ public List<MediaFile> getNewestAlbums(int offset, int count, int user_group_id) { return mediaFileDao.getNewestAlbums(offset, count, user_group_id); } /** * Returns the most recently added albums. * * @param musicFolder List of musicFolder to use. * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param user_group_id Returns albums for this group. * @return The most recently added albums for this group. */ public List<MediaFile> getNewestAlbums(MusicFolder musicFolder, int offset, int count, int user_group_id) { return mediaFileDao.getNewestAlbums(musicFolder, offset, count, user_group_id); } /** * Returns the most recently added albums. * * @param musicFolderToUse List of musicFolder to use. * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param user_group_id Returns albums for this group. * @return */ public List<MediaFile> getNewestAlbums(List<MusicFolder> musicFolderToUse, int offset, int count, int user_group_id) { List<MusicFolder> musicFolders = new ArrayList<MusicFolder>(); for (MusicFolder folder : musicFolderToUse) { for (MusicFolder accessibleFolder : musicFolderDao.getAllMusicFoldders(user_group_id)) { if (folder.equals(accessibleFolder)) { musicFolders.add(folder); } } } return mediaFileDao.getNewestAlbums(musicFolders, offset, count, user_group_id); } /** * Returns the most recently starred albums. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param username Returns albums starred by this user. * @return The most recently starred albums for this user. */ public List<MediaFile> getStarredAlbums(int offset, int count, String username) { return mediaFileDao.getStarredAlbums(offset, count, username); } public List<MediaFile> getStarredAlbums(List<MusicFolder> musicFolders, int offset, int count, String username) { return mediaFileDao.getStarredAlbums(musicFolders, offset, count, username); } public List<MediaFile> getArtists(int offset, int count, String username, int user_group_id) { return mediaFileDao.getArtists(offset, count, username, user_group_id); } public List<MediaFile> getArtists(List<MusicFolder> musicFolders, int offset, int count, String username, int user_group_id) { return mediaFileDao.getArtists(musicFolders, offset, count, username, user_group_id); } public List<MediaFile> getStarredArtists(List<MusicFolder> musicFolders, int offset, int count, String username) { return mediaFileDao.getStarredArtists(musicFolders, offset, count, username); } public List<MediaFile> getStarredArtists(int offset, int count, String username) { return mediaFileDao.getStarredArtists(offset, count, username); } /** * Returns albums in alphabetial order. * * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param byArtist Whether to sort by artist name * @return Albums in alphabetical order. */ public List<MediaFile> getAlphabeticalAlbums(List<MusicFolder> musicFolders, int offset, int count, boolean byArtist) { return mediaFileDao.getAlphabeticalAlbums(musicFolders, offset, count, byArtist); } /** * Returns albums in alphabetial order. * * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param byArtist Whether to sort by artist name * @return Albums in alphabetical order. */ public List<MediaFile> getAlphabeticalAlbums(int offset, int count, boolean byArtist, int user_group_id) { return mediaFileDao.getAlphabeticalAlbums(offset, count, byArtist, user_group_id); } /** * Returns albums within a year range. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param fromYear The first year in the range. * @param toYear The last year in the range. * @return Albums in the year range. */ public List<MediaFile> getAlbumsByYear(int offset, int count, int fromYear, int toYear, int user_group_id ) { return mediaFileDao.getAlbumsByYear(offset, count, fromYear, toYear, user_group_id); } /** * Returns albums in a genre. * * @param offset Number of albums to skip. * @param count Maximum number of albums to return. * @param genre The genre name. * @return Albums in the genre. */ public List<MediaFile> getAlbumsByGenre(int offset, int count, String genre, int user_group_id) { return mediaFileDao.getAlbumsByGenre(offset, count, genre, user_group_id); } public List<MediaFile> getArtistsByGenre(int offset, int count, String genre, int user_group_id) { return mediaFileDao.getArtistsByGenre(genre, offset, count, user_group_id); } /** * Returns random songs for the give parent. * * @param parent The parent. * @param count Max number of songs to return. * @return Random songs. */ public List<MediaFile> getRandomSongsForParent(MediaFile parent, int count) throws IOException { List<MediaFile> children = getDescendantsOf(parent, false); removeVideoFiles(children); if (children.isEmpty()) { return children; } Collections.shuffle(children); return children.subList(0, Math.min(count, children.size())); } /** * Removes video files from the given list. */ public void removeVideoFiles(List<MediaFile> files) { Iterator<MediaFile> iterator = files.iterator(); while (iterator.hasNext()) { MediaFile file = iterator.next(); if (file.isVideo()) { iterator.remove(); } } } public int getMediaFileBookmarkPosition(int id, String username) { return mediaFileDao.getMediaFileBookmarkPosition(id, username); } public Date getMediaFileStarredDate(int id, String username) { return mediaFileDao.getMediaFileStarredDate(id, username); } public Date getMediaFileLovedDate(int id, String username) { return mediaFileDao.getMediaFileLovedDate(id, username); } public List<MediaFile> getLovedFiles(String username) { return mediaFileDao.getLovedFiles(username); } public void populateLovedDate(List<MediaFile> mediaFiles, String username) { for (MediaFile mediaFile : mediaFiles) { populateLovedDate(mediaFile, username); } } public void populateLovedDate(MediaFile mediaFile, String username) { Date lovedDate = mediaFileDao.getMediaFileLovedDate(mediaFile.getId(), username); mediaFile.setLovedDate(lovedDate); } public void populateStarredDate(List<MediaFile> mediaFiles, String username) { for (MediaFile mediaFile : mediaFiles) { populateStarredDate(mediaFile, username); } } public void populateStarredDate(MediaFile mediaFile, String username) { Date starredDate = mediaFileDao.getMediaFileStarredDate(mediaFile.getId(), username); mediaFile.setStarredDate(starredDate); } public void populateBookmarkPosition(MediaFile mediaFile, String username) { int bookmarkPosition = mediaFileDao.getMediaFileBookmarkPosition(mediaFile.getId(), username); mediaFile.setBookmarkPosition(new Long(bookmarkPosition)); } public void populateBookmarkPosition(List<MediaFile> mediaFiles, String username) { for (MediaFile mediaFile : mediaFiles) { populateBookmarkPosition(mediaFile, username); } } private void updateChildren(MediaFile parent) { // Check timestamps. if (parent.getChildrenLastUpdated().getTime() >= parent.getChanged().getTime()) { return; } List<MediaFile> storedChildren = mediaFileDao.getChildrenOf(parent.getPath()); Map<String, MediaFile> storedChildrenMap = new HashMap<String, MediaFile>(); for (MediaFile child : storedChildren) { storedChildrenMap.put(child.getPath(), child); } List<File> children = filterMediaFiles(FileUtil.listFiles(parent.getFile())); for (File child : children) { if (storedChildrenMap.remove(child.getPath()) == null) { // Add children that are not already stored. mediaFileDao.createOrUpdateMediaFile(createMediaFile(child)); } } // List<File> images = filterImagesFiles(FileUtil.listFiles(parent.getFile())); // for (File image : images) { // if (storedChildrenMap.remove(image.getPath()) == null) { // // Add children that are not already stored. // mediaFileDao.createOrUpdateMediaFile(createMediaFile(image)); // } // } // Delete children that no longer exist on disk. for (String path : storedChildrenMap.keySet()) { mediaFileDao.deleteMediaFile(path); } // Update timestamp in parent. parent.setChildrenLastUpdated(parent.getChanged()); parent.setPresent(true); mediaFileDao.createOrUpdateMediaFile(parent); } public List<File> filterMediaFiles(File[] candidates) { List<File> result = new ArrayList<File>(); for (File candidate : candidates) { String suffix = FilenameUtils.getExtension(candidate.getName()).toLowerCase(); try { if (!isExcluded(candidate) && (FileUtil.isDirectory(candidate) || isAudioFile(suffix) || isVideoFile(suffix) )) { result.add(candidate); } } catch (IOException e) { LOG.error("## filterMediaFiles: " + e, e); } } return result; } public List<File> filterImagesFiles(File[] candidates) { List<File> result = new ArrayList<File>(); for (File candidate : candidates) { String suffix = FilenameUtils.getExtension(candidate.getName()).toLowerCase(); if (isImageFile(suffix)) { result.add(candidate); } } return result; } private boolean isAudioFile(String suffix) { for (String s : settingsService.getMusicFileTypesAsArray()) { if (suffix.equals(s.toLowerCase())) { return true; } } for (String s : settingsService.getModFileTypesAsArray()) { if (suffix.equals(s.toLowerCase())) { return true; } } return false; } private boolean isVideoFile(String suffix) { for (String s : settingsService.getVideoFileTypesAsArray()) { if (suffix.equals(s.toLowerCase())) { return true; } } return false; } private boolean isImageFile(String suffix) { for (String s : settingsService.getImageFileTypesAsArray()) { if (suffix.equals(s.toLowerCase())) { return true; } } return false; } private Set<String> excludes; /** * Returns whether the given file is excluded, i.e., whether it is listed in 'madsonic_exclude.txt' in * the current directory. * * @param file The child file in question. * @return Whether the child file is excluded. */ private boolean isExcluded(File file) throws IOException { if (file.getName().startsWith(".") || file.getName().startsWith("@eaDir") || file.getName().toLowerCase().equals("thumbs.db") || file.getName().toLowerCase().equals("extrafanart") ) { return true; } File excludeFile = new File(file.getParentFile().getPath(), "madsonic_exclude.txt"); if (excludeFile.exists()) { excludes = new HashSet<String>(); LOG.debug("## excludeFile found: " + excludeFile); String[] lines = StringUtil.readLines(new FileInputStream(excludeFile)); for (String line : lines) { excludes.add(line.toLowerCase()); } return excludes.contains(file.getName().toLowerCase()); } return false; } private MediaFile createMediaFile(File file) { MediaFile existingFile = mediaFileDao.getMediaFile(file.getPath()); MediaFile mediaFile = new MediaFile(); Date lastModified = new Date(FileUtil.lastModified(file)); mediaFile.setPath(file.getPath()); mediaFile.setFolder(securityService.getRootFolderForFile(file)); mediaFile.setParentPath(file.getParent()); mediaFile.setChanged(lastModified); mediaFile.setLastScanned(new Date()); mediaFile.setPlayCount(existingFile == null ? 0 : existingFile.getPlayCount()); mediaFile.setLastPlayed(existingFile == null ? null : existingFile.getLastPlayed()); mediaFile.setComment(existingFile == null ? null : existingFile.getComment()); mediaFile.setChildrenLastUpdated(new Date(0)); mediaFile.setCreated(lastModified); // mediaFile.setMediaType(ALBUM); mediaFile.setMediaType(DIRECTORY); // ######### Read Comment.txt file #### String comment = null; comment = checkForCommentFile(file); if (checkForCommentFile(file) != null) { mediaFile.setComment(comment); } Boolean folderParsing = settingsService.isFolderParsingEnabled(); Boolean albumSetParsing = settingsService.isAlbumSetParsingEnabled(); // #### Scan Foldernamer for Year ##### if (StringUtil.truncatedYear(file.getName()) != null && StringUtil.truncatedYear(file.getName()) > 10){ mediaFile.setYear(StringUtil.truncatedYear(file.getName())); } //TODO:SCAN ALBUMS try{ if (isRoot(mediaFile)) { mediaFile.setMediaType(DIRECTORY); } } catch (Exception x) { LOG.error("Failed to get parent", x); } mediaFile.setPresent(true); // ################# Look for cover art. ################## try { FilenameFilter PictureFilter = new FilenameFilter() { public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith("png")) { return true; } else if (lowercaseName.endsWith("jpg")) { return true; } else if (lowercaseName.endsWith("jpeg")) { return true; } else if (lowercaseName.endsWith("gif")) { return true; } else if (lowercaseName.endsWith("bmp")) { return true; } else { return false;} }}; File[] Albumchildren = FileUtil.listFiles(file, PictureFilter, true); File coverArt = findCoverArt(Albumchildren); if (coverArt != null) { mediaFile.setCoverArtPath(coverArt.getPath()); } } catch (IOException x) { LOG.error("Failed to find cover art for DIRECTORY ", x); } // ################# MEDIA_TYPE MUSIC ##################### if (file.isFile()) { MetaDataParser parser = metaDataParserFactory.getParser(file); if (parser != null) { MetaData metaData = parser.getMetaData(file); mediaFile.setArtist(metaData.getArtist()); mediaFile.setAlbumArtist(metaData.getAlbumArtist()); mediaFile.setAlbumName(metaData.getAlbumName()); mediaFile.setTitle(metaData.getTitle()); mediaFile.setDiscNumber(metaData.getDiscNumber()); mediaFile.setTrackNumber(metaData.getTrackNumber()); mediaFile.setGenre(metaData.getGenre()); mediaFile.setMood(metaData.getMood()); mediaFile.setBpm(metaData.getBpm()); mediaFile.setComposer(metaData.getComposer()); mediaFile.setYear(metaData.getYear()); mediaFile.setDurationSeconds(metaData.getDurationSeconds()); mediaFile.setBitRate(metaData.getBitRate()); mediaFile.setVariableBitRate(metaData.getVariableBitRate()); mediaFile.setHeight(metaData.getHeight()); mediaFile.setWidth(metaData.getWidth()); } String format = StringUtils.trimToNull(StringUtils.lowerCase(FilenameUtils.getExtension(mediaFile.getPath()))); mediaFile.setFormat(format); mediaFile.setFileSize(FileUtil.length(file)); mediaFile.setMediaType(getMediaType(mediaFile)); //TODO: FINSIH!!!! if ("MIXED".equalsIgnoreCase(settingsService.getScanMode())) { // ### fix duration/bitrate on special formats if (Arrays.asList("aac", "aiff", "dff", "dsf", "opus", "ogg", "flac", "mod", "mid", "it", "s3m", "xm").contains(StringUtils.lowerCase(mediaFile.getFormat()))) { FFmpegParser fparser = new FFmpegParser(); fparser.setTranscodingService(transcodingService); if (fparser != null) { MetaData fmetaData = fparser.getRawMetaData(file); mediaFile.setDurationSeconds(fmetaData.getDurationSeconds()); mediaFile.setBitRate(fmetaData.getBitRate()); if (!"flac".contains(StringUtils.lowerCase(mediaFile.getFormat()))) { if (fmetaData.getTitle() != null) mediaFile.setTitle(fmetaData.getTitle()); if (fmetaData.getArtist() != null) mediaFile.setArtist(fmetaData.getArtist()); if (fmetaData.getAlbumName() != null) mediaFile.setAlbumName(fmetaData.getAlbumName()); if (fmetaData.getYear() != null) mediaFile.setYear(fmetaData.getYear()); } } } } // #### set Image path ##### if (mediaFile.getMediaType() == MediaType.IMAGE) { mediaFile.setCoverArtPath(file.getPath()); } // #### Scan for YouTube url ##### if (file.getPath().toLowerCase().endsWith("url")) { mediaFile.setMediaType(URL); UrlFile urlFile = null; String YoutubeId = null; try { urlFile = new UrlFile(file.getPath()); YoutubeId = StringUtil.getYoutubeVideoId(urlFile.getString("InternetShortcut", "URL", null)); } catch (IOException e) { } mediaFile.setData(YoutubeId); mediaFile.setDurationSeconds(0); } // #### Scan for Tuner tv ##### if (file.getPath().toLowerCase().endsWith(".tv")) { mediaFile.setMediaType(VIDEO); try { //Build stream URL from Dreambox File channelFile = new File(mediaFile.getFile().getAbsolutePath()); String channel = FileUtils.readFileToString(channelFile); Matcher matcher = CHANNEL_PATTERN.matcher(channel); if (matcher.matches()) { if (matcher.group(1).length() > 10) { mediaFile.setData(matcher.group(1)); mediaFile.setDurationSeconds(0); } } } catch (IOException e) { LOG.warn("failed to parse file " + mediaFile.getFile().getAbsolutePath()); } } } else { // ############## Is this an album? ######################## if (!isRoot(mediaFile)) { File[] children = FileUtil.listFiles(file); File firstChild = null; for (File child : filterMediaFiles(children)) { if (FileUtil.isFile(child)) { firstChild = child; break; } } if (firstChild != null) { mediaFile.setMediaType(ALBUM); try { Integer FOLDER_TYPE = musicFolderDao.getMusicFolder(mediaFile.getFolder()).getType(); switch (FOLDER_TYPE) { case 1: mediaFile.setMediaType(ALBUM); break; case 2: mediaFile.setMediaType(ALBUM); break; case 3: mediaFile.setMediaType(ALBUM); break; case 4: mediaFile.setMediaType(ALBUM); break; case 7: mediaFile.setMediaType(VIDEOSET); break; case 8: mediaFile.setMediaType(VIDEOSET); break; case 9: mediaFile.setMediaType(VIDEOSET); break; case 10: mediaFile.setMediaType(VIDEOSET); break; case 11: mediaFile.setMediaType(DIRECTORY); break; case 12: mediaFile.setMediaType(DIRECTORY); break; default : mediaFile.setMediaType(ALBUM); break; } } catch (Exception e) { LOG.warn("failed to get folder "); } // ######### Read Comment.txt file #### comment = checkForCommentFile(file); if (checkForCommentFile(file) != null && mediaFile.getComment() == null) { mediaFile.setComment(comment); } // ######### Guess artist/album name and year. ####### MetaDataParser parser = metaDataParserFactory.getParser(firstChild); if (parser != null) { MetaData metaData = parser.getMetaData(firstChild); // mediaFile.setArtist(metaData.getArtist()); mediaFile.setArtist(StringUtils.isBlank(metaData.getAlbumArtist()) ? metaData.getArtist() : metaData.getAlbumArtist()); // ########## SET Genre & Yeas for album ######### mediaFile.setGenre(metaData.getGenre()); if (metaData.getYear() != null) { mediaFile.setYear(metaData.getYear()); mediaFile.setYear(metaData.getYear()); } // ########## BETTER Albumset Detection ######### String _albumName; String _albumSetName; if (albumSetParsing) { String AlbumSetName = parser.guessAlbum(firstChild, mediaFile.getArtist()); if (folderParsing) { AlbumSetName = StringUtil.truncateYear(AlbumSetName); } String parentAlbumSetName = parser.guessArtist(firstChild); // mediaFile.setArtist(parser.guessArtist(mediaFile.getFile())); String searchAlbum = searchforAlbumSetName(AlbumSetName, AlbumSetName); if ( AlbumSetName == searchAlbum ) { _albumName = metaData.getAlbumName(); _albumSetName = AlbumSetName; if (folderParsing) { _albumName = StringUtil.truncateYear(_albumName); _albumSetName = StringUtil.truncateYear(_albumSetName); } mediaFile.setAlbumName(_albumName); mediaFile.setAlbumSetName(_albumSetName); } else { _albumName = metaData.getAlbumName(); _albumSetName = metaData.getAlbumName(); if (folderParsing) { _albumName = StringUtil.truncateYear(_albumName); _albumSetName = searchforAlbumSetName(StringUtil.truncateYear(AlbumSetName), StringUtil.truncateYear(parentAlbumSetName)); } else { _albumSetName = searchforAlbumSetName(AlbumSetName, parentAlbumSetName); } } } else { _albumName = metaData.getAlbumName(); _albumSetName = metaData.getAlbumName(); } mediaFile.setAlbumName(_albumName); mediaFile.setAlbumSetName(_albumSetName); // LOG.debug("## MediaType ALBUMSET: " + _albumSetName); } // ####### Look for cover art. ######## try { File coverArt = findCoverArt(children); if (coverArt != null) { mediaFile.setCoverArtPath(coverArt.getPath()); } } catch (IOException x) { LOG.error("Failed to find cover art.", x); } } else { // ##### Look for child type ####### File firstAudioChild = null; File firstFolderChild = null; for (File child : filterMediaFiles(children)) { if (FileUtil.isDirectory(child)) { firstFolderChild = child; } if (FileUtil.isFile(child)) { firstAudioChild = child; break; } } if (firstFolderChild != null) { File[] firstAlbumChild = FileUtil.listFiles(firstFolderChild); for (File child : filterMediaFiles(firstAlbumChild)) { if (FileUtil.isFile(child)) { MetaDataParser ChildParser = metaDataParserFactory.getParser(child); if (ChildParser != null) { MetaData metaDataChild = ChildParser.getMetaData(child); mediaFile.setGenre(metaDataChild.getGenre()); if (metaDataChild.getYear() != null) { mediaFile.setYear(metaDataChild.getYear()); } } break; } else if (FileUtil.isDirectory(child)) { for (File subchild : filterMediaFiles(FileUtil.listFiles(child))) { if (FileUtil.isFile(subchild)) { MetaDataParser ChildParser = metaDataParserFactory.getParser(subchild); if (ChildParser != null) { MetaData metaDataChild = ChildParser.getMetaData(subchild); if (metaDataChild.getGenre() != null) { if (mediaFile.getGenre() != metaDataChild.getGenre()) mediaFile.setGenre(metaDataChild.getGenre()); } if (metaDataChild.getYear() != null) { mediaFile.setYear(metaDataChild.getYear()); } } break; } } } } } if (firstAudioChild != null) { MetaDataParser ChildParser = metaDataParserFactory.getParser(firstAudioChild); if (ChildParser != null) { MetaData metaDataChild = ChildParser.getMetaData(firstAudioChild); mediaFile.setGenre(metaDataChild.getGenre()); if (metaDataChild.getYear() != null) { mediaFile.setYear(metaDataChild.getYear()); } } } // ######## ALBUMSET ############### if (firstAudioChild == null) { try { // mediaFile.setMediaType(ALBUMSET); Integer FOLDER_TYPE = musicFolderDao.getMusicFolder(mediaFile.getFolder()).getType(); switch (FOLDER_TYPE) { case 1: mediaFile.setMediaType(ALBUM); break; case 2: mediaFile.setMediaType(ALBUM); break; case 3: mediaFile.setMediaType(ALBUM); break; case 4: mediaFile.setMediaType(ALBUM); break; case 7: mediaFile.setMediaType(VIDEOSET); break; case 8: mediaFile.setMediaType(VIDEOSET); break; case 9: mediaFile.setMediaType(VIDEOSET); break; case 10: mediaFile.setMediaType(VIDEOSET); break; case 11: mediaFile.setMediaType(DIRECTORY); break; case 12: mediaFile.setMediaType(DIRECTORY); break; default : mediaFile.setMediaType(ALBUM); break; } String _artist = new File(file.getParent()).getName(); String _albumName = file.getName(); String _albumSetName = file.getName(); if (folderParsing) { _artist = StringUtil.truncateYear(_artist); _albumName = StringUtil.truncateYear(_albumName); _albumSetName = StringUtil.truncateYear(_albumSetName); } //TODO:FIX ARTIST TAG mediaFile.setArtist(_artist); mediaFile.setAlbumName(_albumName); mediaFile.setAlbumSetName(_albumSetName); } catch (Exception ex) { LOG.error(ex); } } else { String _artist = file.getName(); if (folderParsing) { _artist = StringUtil.truncateYear(_artist); } mediaFile.setArtist(_artist); } if (mediaFile.getArtist() != null) { if (mediaFile.getParentPath().contains(mediaFile.getArtist())) { mediaFile.setMediaType(ALBUMSET); String _artist = new File(file.getParent()).getName(); if (folderParsing) { _artist = StringUtil.truncateYear(_artist); } mediaFile.setArtist(_artist); // LOG.info("## MediaType ALBUMSET: " + _artist ); } // ######## ARTIST ############### if (mediaFile.getCoverArtPath() == null) { mediaFile.setMediaType(ARTIST); String _artist = file.getName(); if (folderParsing) { _artist = StringUtil.truncateYear(_artist); } mediaFile.setArtist(_artist); // LOG.debug("## MediaType ARTIST: " + _artist ); } } // ######## ARTIST ############### if (mediaFile.getCoverArtPath() != null) { String lowercaseName = (mediaFile.getCoverArtPath().toLowerCase()); if (lowercaseName.contains("artist.")) { mediaFile.setMediaType(ARTIST); String _artist = file.getName(); if (folderParsing) { _artist = StringUtil.truncateYear(_artist); } mediaFile.setArtist(_artist); // LOG.debug("## MediaType ARTIST: " + _artist ); } } // ######## VIDEOSET ############### if (mediaFile.getCoverArtPath() != null) { String lowercaseName = (mediaFile.getCoverArtPath().toLowerCase()); if (lowercaseName.contains("video.") || lowercaseName.contains("sesson") ) { mediaFile.setMediaType(VIDEOSET); // LOG.debug("## MediaType VIDEOSET: " + file.getName() ); } } // ################## Look for Artist flag ############### setMediaTypeFlag (mediaFile, file, "MULTI.TAG", MULTIARTIST); setMediaTypeFlag (mediaFile, file, "ARTIST.TAG", ARTIST); setMediaTypeFlag (mediaFile, file, "DIR.TAG", DIRECTORY); setMediaTypeFlag (mediaFile, file, "SET.TAG", ALBUMSET); setMediaTypeFlag (mediaFile, file, "ALBUM.TAG", ALBUM); setMediaTypeFlag (mediaFile, file, "VIDEO.TAG", VIDEOSET); setMediaTypeFlag (mediaFile, file, "IMAGE.TAG", IMAGESET); } } } return mediaFile; } private boolean isNewAdded(MediaFile mediafile, String TimeSpan){ try { Date LastSystemScan = null; Integer timespan = 0; if (TimeSpan.contains("OneHour")) { timespan = 1;}; if (TimeSpan.contains("OneDay")) { timespan = 2;}; if (TimeSpan.contains("OneWeek")) { timespan = 3;}; if (TimeSpan.contains("OneMonth")) { timespan = 4;}; if (TimeSpan.contains("TwoMonth")) { timespan = 5;}; if (TimeSpan.contains("ThreeMonth")) { timespan = 6;}; if (TimeSpan.contains("SixMonth")) { timespan = 7;}; if (TimeSpan.contains("OneYear")) { timespan = 8;}; switch(timespan) { case 1: LastSystemScan = new Date(System.currentTimeMillis() - 3600 * 1000); break; case 2: LastSystemScan = new Date(System.currentTimeMillis() - 24 * 3600 * 1000); break; case 3: LastSystemScan = new Date(System.currentTimeMillis() - 7L * 24 * 3600 * 1000); break; case 4: LastSystemScan = new Date(System.currentTimeMillis() - 30L * 24 * 3600 * 1000); break; case 5: LastSystemScan = new Date(System.currentTimeMillis() - 60L * 24 * 3600 * 1000); break; case 6: LastSystemScan = new Date(System.currentTimeMillis() - 90L * 24 * 3600 * 1000); break; case 7: LastSystemScan = new Date(System.currentTimeMillis() - 182L * 24 * 3600 * 1000); break; case 8: LastSystemScan = new Date(System.currentTimeMillis() - 365L * 24 * 3600 * 1000); break; default: LastSystemScan = new Date(System.currentTimeMillis() - 90L * 24 * 3600 * 1000); break; } Date LastMediaScan = mediafile.getCreated(); Calendar calLastSystemScan = Calendar.getInstance(); Calendar calLastMediaScan = Calendar.getInstance(); calLastMediaScan.setTime(LastMediaScan); calLastSystemScan.setTime(LastSystemScan); if(calLastSystemScan.before(calLastMediaScan)) { return true; } return false; } catch (Exception x) { LOG.error("Failed to get TimeSpan.", x); } return false; } /** * Set MediaType if File TAG Flag is found */ private boolean setMediaTypeFlag(MediaFile mediaFile, File file, final String flagname, MediaType mediaType){ FilenameFilter FlagFilter = new FilenameFilter() { public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.contains(flagname.toLowerCase())) { return true; } else { return false; } }}; File[] FlagChildren = FileUtil.listFiles(file, FlagFilter, true); for (File candidate : FlagChildren) { if (candidate.isFile()) { mediaFile.setMediaType(mediaType); LOG.debug("## Found FileTag " + mediaType + ": " + file.getName() ); return true; }} return false; } /** * Returns a converted Albumsetname for the given parent folder. */ private String searchforAlbumSetName(String albumname, String parentalbumname ) { int i = 1; boolean AlbumSetFound; while(i<16) { String[] strArray = {"CD"+i,"CD "+i, "DISC"+i,"DISC "+i, "DISK"+i,"DISK "+i, "TEIL"+i,"TEIL "+i, "PART"+i,"PART "+i}; AlbumSetFound = false; for (String searchTerm : strArray) { if (albumname.toLowerCase().contains(searchTerm.toLowerCase())) { AlbumSetFound = true; } } if (AlbumSetFound == true) { parentalbumname = parentalbumname + " - Disk"+i; } i++; } return parentalbumname; } private String checkForCommentFile(File file) { File commentFile = new File(file.getPath(), "comment.txt"); if (commentFile.exists()) { LOG.info("## CommentFile found: " + commentFile); Path path = Paths.get(commentFile.getPath()); List<String> lines = null; String listString = ""; try { lines = Files.readAllLines(path, StandardCharsets.UTF_8); } catch (IOException e) { LOG.warn("## error reading commentfile: " + commentFile); // e.printStackTrace(); } if (lines == null){ try { lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1); } catch (IOException e) { LOG.warn("## error reading commentfile: " + commentFile); // e.printStackTrace(); } } for (String s : lines) { s = s.replace("’", "'"); listString += s + " \\\\"; } return listString; } return null; } private MediaFile.MediaType getMediaType(MediaFile mediaFile) { String path = mediaFile.getPath().toLowerCase(); if (path.toLowerCase().endsWith(".tv")|| path.toLowerCase().endsWith(".hdrun")) { return VIDEO; } if (path.toLowerCase().endsWith(".url")) { return VIDEO; } if (isVideoFile(mediaFile.getFormat())) { return VIDEO; } if (isImageFile(mediaFile.getFormat())) { return IMAGE; } String genre = StringUtils.trimToEmpty(mediaFile.getGenre()).toLowerCase(); if (path.toLowerCase().contains("podcast") || genre.toLowerCase().contains("podcast")) { return PODCAST; } if (path.toLowerCase().replace(" ","").contains("music") || path.toLowerCase().replace(" ","").contains("musik")) { return MUSIC; } return AUDIOBOOK; } @Deprecated // refreshMediaFileRank -> refreshMediaFile public void refreshMediaFileRank(MediaFile mediaFile) { mediaFileDao.createOrUpdateMediaFile(mediaFile); mediaFileMemoryCache.remove(mediaFile.getFile()); mediaFileMemoryCache.put(new Element(mediaFile.getFile(), mediaFile )); } public void refreshMediaFile(MediaFile mediaFile) { MediaFile newMediaFile = new MediaFile(); newMediaFile = createMediaFile(mediaFile.getFile()); newMediaFile.setRank(mediaFile.getRank()); newMediaFile.setBpm(mediaFile.getBpm()); newMediaFile.setComposer(mediaFile.getComposer()); mediaFileDao.createOrUpdateMediaFile(newMediaFile); mediaFileMemoryCache.remove(newMediaFile.getFile()); } private void putInMemoryCache(File file, MediaFile mediaFile) { if (memoryCacheEnabled) { mediaFileMemoryCache.put(new Element(file, mediaFile)); } } private MediaFile getFromMemoryCache(File file) { if (!memoryCacheEnabled) { return null; } Element element = mediaFileMemoryCache.get(file); return element == null ? null : (MediaFile) element.getObjectValue(); } public void setMemoryCacheEnabled(boolean memoryCacheEnabled) { this.memoryCacheEnabled = memoryCacheEnabled; if (!memoryCacheEnabled) { mediaFileMemoryCache.removeAll(); } } /** * Returns a cover art image for the given media file. */ public File getCoverArt(MediaFile mediaFile) { if (mediaFile.getCoverArtFile() != null) { return mediaFile.getCoverArtFile(); } MediaFile parent = getParentOf(mediaFile); return parent == null ? null : parent.getCoverArtFile(); } /** * Finds a cover art image for the given directory, by looking for it on the disk. */ private File findCoverArt(File[] candidates) throws IOException { for (String mask : settingsService.getCoverArtFileTypesAsArray()) { for (File candidate : candidates) { if (candidate.isFile() && candidate.getName().toUpperCase().endsWith(mask.toUpperCase()) && !candidate.getName().startsWith(".")) { return candidate; } } } // Look for embedded images in audiofiles. (Only check first audio file encountered). JaudiotaggerParser parser = new JaudiotaggerParser(); for (File candidate : candidates) { if (parser.isApplicable(candidate)) { if (parser.isImageAvailable(getMediaFile(candidate))) { return candidate; } else { return null; } } } return null; } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } public void setSettingsService(SettingsService settingsService) { this.settingsService = settingsService; } public void setTranscodingService(TranscodingService transcodingService) { this.transcodingService = transcodingService; } public void setMediaFileMemoryCache(Ehcache mediaFileMemoryCache) { this.mediaFileMemoryCache = mediaFileMemoryCache; } public void setMediaFileDao(MediaFileDao mediaFileDao) { this.mediaFileDao = mediaFileDao; } public void setMusicFolderDao(MusicFolderDao musicFolderDao) { this.musicFolderDao = musicFolderDao; } /** * Returns all media files that are children, grand-children etc of a given media file. * Directories are not included in the result. * * @param sort Whether to sort files in the same directory. * @return All descendant music files. */ public List<MediaFile> getDescendantsOf(MediaFile ancestor, boolean sort) { if (ancestor.isFile()) { return Arrays.asList(ancestor); } List<MediaFile> result = new ArrayList<MediaFile>(); for (MediaFile child : getChildrenOf(ancestor, true, true, sort)) { if (child.isDirectory()) { result.addAll(getDescendantsOf(child, sort)); } else { result.add(child); } } return result; } public List<MediaFile> getAncestorsOf(MediaFile dir) { LinkedList<MediaFile> result = new LinkedList<MediaFile>(); try { MediaFile parent = getParentOf(dir); while (parent != null && !isRoot(parent)) { result.addFirst(parent); parent = getParentOf(parent); } } catch (SecurityException x) { // Happens if Podcast directory is outside music folder. } return result; } public void setMetaDataParserFactory(MetaDataParserFactory metaDataParserFactory) { this.metaDataParserFactory = metaDataParserFactory; } public void updateMediaFile(MediaFile mediaFile) { mediaFileDao.createOrUpdateMediaFile(mediaFile); } /** * Increments the play count and last played date for the given media file */ public void updateStatisticsUser(String username, MediaFile mediaFile) { mediaFileDao.setPlayCountForUser(username, mediaFile); } /** * Increments the play count and last played date for the given media file and its * directory and album. */ public void incrementPlayCount(MediaFile file) { Date now = new Date(); file.setLastPlayed(now); file.setPlayCount(file.getPlayCount() + 1); updateMediaFile(file); MediaFile parent = getParentOf(file); if (!isRoot(parent)) { parent.setLastPlayed(now); parent.setPlayCount(parent.getPlayCount() + 1); updateMediaFile(parent); } Album album = albumDao.getAlbum(file.getAlbumArtist(), parent.getAlbumSetName()); if (album != null) { album.setLastPlayed(now); album.setPlayCount(album.getPlayCount() + 1); albumDao.createOrUpdateAlbum(album); } } public int getAlbumCount(List<MusicFolder> musicFolders) { return mediaFileDao.getAlbumCount(musicFolders); } public int getPlayedAlbumCount(List<MusicFolder> musicFolders) { return mediaFileDao.getPlayedAlbumCount(musicFolders); } public int getStarredAlbumCount(String username, List<MusicFolder> musicFolders) { return mediaFileDao.getStarredAlbumCount(username, musicFolders); } public void clearMemoryCache() { mediaFileMemoryCache.removeAll(); } public List<Album> getAlbumsForArtist(String artist) { return albumDao.getAlbumsForArtist(artist); } public List<Album> getAllAlbums() { return albumDao.getAllAlbums(); } public void setAlbumDao(AlbumDao albumDao) { this.albumDao = albumDao; } public void setArtistDao(ArtistDao artistDao) { this.artistDao = artistDao; } public List<String> getArtistFolder(String sortableName) { return artistDao.getArtistsForFolder(sortableName); } }
gpl-3.0
VLisnevskiy/LiVEZer.Medicine
src/LiVEZer/Medicine/WebApp/Services/JSONResponse/Common/MainMenu.java
548
package LiVEZer.Medicine.WebApp.Services.JSONResponse.Common; import java.util.List; import LiVEZer.Medicine.WebApp.Models.MenuItem; import LiVEZer.Medicine.WebApp.Services.JSONResponse.JSONResponse; public class MainMenu extends JSONResponse { /** * */ private static final long serialVersionUID = 1L; private List<MenuItem> items; public List<MenuItem> getItems() { return items; } public void setItems(List<MenuItem> items) { this.items = items; } }
gpl-3.0
Crash7600/Peliculas
src/main/java/net/cine/operaciones/DirectorGetprettycolumns.java
859
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.cine.operaciones; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Crash */ public class DirectorGetprettycolumns implements GenericOperation { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { try { String data = "{\"data\": [\"id\", \"nombre\", \"nacionalidad\", \"año inicio\", \"año fin\"]}"; return data; } catch (Exception e) { throw new ServletException("DirectorGetpagesJson: View Error: " + e.getMessage()); } } }
gpl-3.0
reviczky/6ccs3prj
src/cube.java
2175
/* * Cube, an interactive text-based adventure game * Copyright (C) 2009 Adam Janos Reviczky * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.*; import java.util.regex.Pattern; class cube { public static void main(String[] args) { try { System.out.println("Cube Copyright (C) 2009 Adam Janos Reviczky"); System.out.println("This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'."); System.out.println("This is free software, and you are welcome to redistribute it"); System.out.println("under certain conditions; type `show c' for details."); System.out.println(""); System.out.print("proto> "); String input = ""; BufferedReader ir = new BufferedReader(new InputStreamReader(System.in)); input = ir.readLine(); Pattern p = Pattern.compile("[,\\s]"); String[] word; word = p.split(input); while (!input.contentEquals("exit")) { if (input.contentEquals("inventory")) { System.out.println("Hello World!"); } if (input.contentEquals("look")) { System.out.println("room1"); } if (input.contentEquals("go")) { System.out.println("go somewhere"); } if (input.contentEquals("help")) { System.out.println("commands: help"); } System.out.print("proto> "); input = ir.readLine(); } System.exit(0); } catch (IOException ioe) { System.out.println("IOException: " + ioe.getMessage()); } } }
gpl-3.0
edoz90/PAP-Assignment
src/pap/ass08/GOL/ControllerActor.java
4432
package pap.ass08.GOL; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import pap.ass08.GOL.msg.*; import scala.concurrent.duration.Duration; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author edoardo */ public class ControllerActor extends UntypedActor { private final Flag stop; private final int period; private final CellGrid grid; private final ActorRef view; private final ActorSystem sys; private final ArrayList<Point> live; private int countWorker; private List<ActorRef> worker; private long timeNano; private long time; public ControllerActor(int rate, List<ActorRef> w, CellGrid g, ActorRef v) { // convert to nanosecond this.period = (int) (rate * Math.pow(10, 6)); this.worker = w; this.grid = g; this.view = v; this.stop = new Flag(); this.sys = ActorSystem.create("system"); this.live = new ArrayList<>(); } @Override public void preStart() { // Creates and configures a worker for each row this.worker = new ArrayList<>(); ActorRef up; ActorRef bo; int height = this.grid.getHeight(); this.countWorker = height; for (int i = 0; i < height; i++) { this.worker.add(getContext().actorOf(Props.create(Worker.class, i), "Worker" + i)); } // Setting up the initial values of each row cell // for the first row (0) up = this.worker.get(height - 1); bo = this.worker.get(1); this.worker.get(0).tell(new ConfigWorker(this.grid.getRow(0), up, bo), getSelf()); // for each row from 1 to n-2 for (int i = 1; i < (height - 1); i++) { up = this.worker.get(i - 1); bo = this.worker.get(i + 1); this.worker.get(i).tell(new ConfigWorker(grid.getRow(i), up, bo), getSelf()); } // for the last row (n-1) up = this.worker.get(height - 2); bo = this.worker.get(0); this.worker.get(height - 1).tell(new ConfigWorker(this.grid.getRow(height - 1), up, bo), getSelf()); } @Override public void onReceive(Object msg) throws Exception { if (msg instanceof WorkDone && "config".equals(((WorkDone) msg).type)) { // response from ConfigWorker message this.countWorker--; if (this.countWorker == 0) { this.countWorker = this.worker.size(); this.view.tell(new ShowGUI(), getSelf()); } } else if (msg instanceof StartGame) { this.stop.reset(); getSelf().tell(new NextTurn(), getSelf()); } else if (msg instanceof WorkDone && "turn".equals(((WorkDone) msg).type)) { // response from DoTurn message this.countWorker--; this.live.addAll(((ArrayList<Point>) ((WorkDone) msg).result)); if (this.countWorker == 0) { this.countWorker = this.worker.size(); this.updateView(); } } else if (msg instanceof StopGame) { this.stop.set(); } else if (msg instanceof NextTurn) { this.nextTurn(); } } private void nextTurn() { // time start this.time = System.currentTimeMillis(); // for more precision this.timeNano = System.nanoTime(); this.live.clear(); // lunch the computation this.worker.stream().forEach(w -> w.tell(new DoTurn(), getSelf())); } // WARNING: CHECK THE REFRESH PERIOD private void updateView() { // time stop long computeTimeNano = (System.nanoTime() - this.timeNano); // Update the model this.grid.setLive(this.live); this.view.tell(new UpdateGUI(this.live.size(), computeTimeNano), getSelf()); if (!this.stop.isSet()) { if (computeTimeNano < period) { // wait until the correct frame rate this.sys.scheduler().scheduleOnce(Duration.create(period - computeTimeNano, TimeUnit.NANOSECONDS), () -> { getSelf().tell(new NextTurn(), getSelf()); }, this.sys.dispatcher()); } else { getSelf().tell(new NextTurn(), getSelf()); } } } }
gpl-3.0
maochen/NLP
CoreNLP-NLP/src/test/java/org/maochen/nlp/ml/classifier/perceptron/PerceptronTest.java
2373
package org.maochen.nlp.ml.classifier.perceptron; import org.junit.Before; import org.junit.Test; import org.maochen.nlp.ml.Tuple; import org.maochen.nlp.ml.vector.DenseVector; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; /** * Created by Maochen on 8/9/15. */ public class PerceptronTest { private PerceptronClassifier perceptronClassifier; @Before public void setUp() { perceptronClassifier = new PerceptronClassifier(); } @Test public void test() throws IOException { List<Tuple> data = new ArrayList<>(); data.add(new Tuple(1, new DenseVector(new double[]{1, 0, 0}), String.valueOf(1))); data.add(new Tuple(2, new DenseVector(new double[]{1, 0, 1}), String.valueOf(1))); data.add(new Tuple(3, new DenseVector(new double[]{1, 1, 0}), String.valueOf(1))); data.add(new Tuple(4, new DenseVector(new double[]{1, 1, 1}), String.valueOf(0))); perceptronClassifier.train(data); String modelPath = PerceptronClassifier.class.getResource("/").getPath() + "/temp_perceptron_model.dat"; perceptronClassifier.persistModel(modelPath); perceptronClassifier = new PerceptronClassifier(); perceptronClassifier.loadModel(new FileInputStream(modelPath)); Tuple test = new Tuple(5, new DenseVector(new double[]{1, 1, 1}), null); Map<String, Double> actualMap = perceptronClassifier.predict(test); String actualLabel = actualMap.entrySet().stream() .max((e1, e2) -> e1.getValue().compareTo(e2.getValue())) .map(Map.Entry::getKey) .orElse(null); String expectedLabel = "0"; assertEquals(expectedLabel, actualLabel); } @Test public void testModel() { PerceptronModel model = new PerceptronModel(); model.threshold = 0.5; model.bias = new double[]{1.3}; model.learningRate = 0.03; model.weights = new double[3][9]; PerceptronModel cloneModel = new PerceptronModel(model); assertEquals(0.5, cloneModel.threshold, Double.MIN_NORMAL); assertEquals(0.03, cloneModel.learningRate, Double.MIN_NORMAL); assertEquals(1.3, cloneModel.bias[0], Double.MIN_NORMAL); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java
871
package com.baeldung.web.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import com.baeldung.model.NewUserForm; @Controller public class NewUserController { @GetMapping("/user") public String loadFormPage(Model model) { model.addAttribute("newUserForm", new NewUserForm()); return "userHome"; } @PostMapping("/user") public String submitForm(@Valid NewUserForm newUserForm, BindingResult result, Model model) { if (result.hasErrors()) { return "userHome"; } model.addAttribute("message", "Valid form"); return "userHome"; } }
gpl-3.0
nickbattle/vdmj
dbgp/src/main/java/com/fujitsu/vdmj/dbgp/DBGPBreakpointType.java
1584
/******************************************************************************* * * Copyright (c) 2016 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * SPDX-License-Identifier: GPL-3.0-or-later * ******************************************************************************/ package com.fujitsu.vdmj.dbgp; public enum DBGPBreakpointType { LINE("line"), CALL("call"), RETURN("return"), EXCEPTION("exception"), CONDITIONAL("conditional"), WATCH("watch"); public String value; DBGPBreakpointType(String value) { this.value = value; } public static DBGPBreakpointType lookup(String string) throws DBGPException { for (DBGPBreakpointType cmd: values()) { if (cmd.value.equals(string)) { return cmd; } } throw new DBGPException(DBGPErrorCode.PARSE, string); } @Override public String toString() { return value; } }
gpl-3.0
SeqWare/seqware
seqware-common/src/main/java/net/sourceforge/seqware/common/dao/hibernate/FileReportDAOHibernate.java
5603
package net.sourceforge.seqware.common.dao.hibernate; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import net.sourceforge.seqware.common.dao.FileReportDAO; import net.sourceforge.seqware.common.model.FileReportRow; import net.sourceforge.seqware.common.model.SequencerRun; import net.sourceforge.seqware.common.model.Study; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; /** * <p> * FileReportDAOHibernate class. * </p> * * @author boconnor * @version $Id: $Id */ public class FileReportDAOHibernate extends HibernateDaoSupport implements FileReportDAO { /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public List<FileReportRow> getReportForStudy(Study study) { String query = "from FileReportRow as row where row.study.studyId = ?"; List<FileReportRow> fileReport = new ArrayList<>(); Object[] parameters = { study.getStudyId() }; List list = this.getHibernateTemplate().find(query, parameters); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public List<FileReportRow> getReportForStudy(Study study, String orderField, String sortOrder, int offset, int limit) { String query = "from FileReportRow as row where row.study.studyId = ? order by row." + orderField + " " + sortOrder; List<FileReportRow> fileReport = new ArrayList<>(); List list = this.currentSession().createQuery(query).setFirstResult(offset).setMaxResults(limit).setInteger(0, study.getStudyId()) .list(); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public List<FileReportRow> getReportForSequencerRun(SequencerRun seqRun, String orderField, String sortOrder, int offset, int limit) { String query = "from FileReportRow as row where row.lane.sequencerRun.sequencerRunId = ? order by row." + orderField + " " + sortOrder; List<FileReportRow> fileReport = new ArrayList<>(); List list = this.currentSession().createQuery(query).setFirstResult(offset).setMaxResults(limit) .setInteger(0, seqRun.getSequencerRunId()).list(); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public List<FileReportRow> getReportForSequencerRuns(String orderField, String sortOrder, int offset, int limit) { String query = "from FileReportRow as row where row.lane.sequencerRun.sequencerRunId != null order by row." + orderField + " " + sortOrder; List<FileReportRow> fileReport = new ArrayList<>(); List list = this.currentSession().createQuery(query).setFirstResult(offset).setMaxResults(limit).list(); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public List<FileReportRow> getReportForSequencerRun(SequencerRun seqRun) { if (seqRun == null) { String query = "from FileReportRow as row where row.lane.sequencerRun.sequencerRunId != null "; List<FileReportRow> fileReport = new ArrayList<>(); List list = this.currentSession().createQuery(query).list(); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } else { String query = "from FileReportRow as row where row.lane.sequencerRun.sequencerRunId = ? "; List<FileReportRow> fileReport = new ArrayList<>(); List list = this.currentSession().createQuery(query).setInteger(0, seqRun.getSequencerRunId()).list(); for (Object obj : list) { fileReport.add((FileReportRow) obj); } return fileReport; } } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public int countOfRows(Study study) { String query = "select count(*) from file_report where study_id = ?"; List result = this.currentSession().createSQLQuery(query).setInteger(0, study.getStudyId()).list(); int count = 0; if (result.size() > 0) { count = ((BigInteger) result.get(0)).intValue(); } return count; } /** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public int countOfRows(SequencerRun sr) { String query = null; List result = null; if (sr != null) { query = "select count(*) from file_report as fr cross join lane as la " + "where fr.lane_id=la.lane_id and (la.sequencer_run_id = ?)"; result = this.currentSession().createSQLQuery(query).setInteger(0, sr.getSequencerRunId()).list(); } else { query = "select count(*) from file_report as fr cross join lane as la " + "where fr.lane_id=la.lane_id and (la.sequencer_run_id is not null)"; result = this.currentSession().createSQLQuery(query).list(); } int count = 0; if (result.size() > 0) { count = ((BigInteger) result.get(0)).intValue(); } return count; } }
gpl-3.0
RonsDev/BlueCtrl
src/org/ronsdev/bluectrl/KeyEventFuture.java
6585
/* * Copyright (C) 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ronsdev.bluectrl; /** * Backported constants that aren't available yet in the current android.view.KeyEvent class * (API level 10). */ public class KeyEventFuture { public static final int FLAG_FALLBACK = 1024; public static final int KEYCODE_3D_MODE = 206; public static final int KEYCODE_APP_SWITCH = 187; public static final int KEYCODE_AVR_INPUT = 182; public static final int KEYCODE_AVR_POWER = 181; public static final int KEYCODE_BOOKMARK = 174; public static final int KEYCODE_BREAK = 121; public static final int KEYCODE_BUTTON_1 = 188; public static final int KEYCODE_BUTTON_10 = 197; public static final int KEYCODE_BUTTON_11 = 198; public static final int KEYCODE_BUTTON_12 = 199; public static final int KEYCODE_BUTTON_13 = 200; public static final int KEYCODE_BUTTON_14 = 201; public static final int KEYCODE_BUTTON_15 = 202; public static final int KEYCODE_BUTTON_16 = 203; public static final int KEYCODE_BUTTON_2 = 189; public static final int KEYCODE_BUTTON_3 = 190; public static final int KEYCODE_BUTTON_4 = 191; public static final int KEYCODE_BUTTON_5 = 192; public static final int KEYCODE_BUTTON_6 = 193; public static final int KEYCODE_BUTTON_7 = 194; public static final int KEYCODE_BUTTON_8 = 195; public static final int KEYCODE_BUTTON_9 = 196; public static final int KEYCODE_CAPS_LOCK = 115; public static final int KEYCODE_CAPTIONS = 175; public static final int KEYCODE_CHANNEL_DOWN = 167; public static final int KEYCODE_CHANNEL_UP = 166; public static final int KEYCODE_CTRL_LEFT = 113; public static final int KEYCODE_CTRL_RIGHT = 114; public static final int KEYCODE_DVR = 173; public static final int KEYCODE_ESCAPE = 111; public static final int KEYCODE_F1 = 131; public static final int KEYCODE_F10 = 140; public static final int KEYCODE_F11 = 141; public static final int KEYCODE_F12 = 142; public static final int KEYCODE_F2 = 132; public static final int KEYCODE_F3 = 133; public static final int KEYCODE_F4 = 134; public static final int KEYCODE_F5 = 135; public static final int KEYCODE_F6 = 136; public static final int KEYCODE_F7 = 137; public static final int KEYCODE_F8 = 138; public static final int KEYCODE_F9 = 139; public static final int KEYCODE_FORWARD = 125; public static final int KEYCODE_FORWARD_DEL = 112; public static final int KEYCODE_FUNCTION = 119; public static final int KEYCODE_GUIDE = 172; public static final int KEYCODE_INFO = 165; public static final int KEYCODE_INSERT = 124; public static final int KEYCODE_LANGUAGE_SWITCH = 204; public static final int KEYCODE_MANNER_MODE = 205; public static final int KEYCODE_MEDIA_CLOSE = 128; public static final int KEYCODE_MEDIA_EJECT = 129; public static final int KEYCODE_MEDIA_PAUSE = 127; public static final int KEYCODE_MEDIA_PLAY = 126; public static final int KEYCODE_MEDIA_RECORD = 130; public static final int KEYCODE_META_LEFT = 117; public static final int KEYCODE_META_RIGHT = 118; public static final int KEYCODE_MOVE_END = 123; public static final int KEYCODE_MOVE_HOME = 122; public static final int KEYCODE_NUMPAD_0 = 144; public static final int KEYCODE_NUMPAD_1 = 145; public static final int KEYCODE_NUMPAD_2 = 146; public static final int KEYCODE_NUMPAD_3 = 147; public static final int KEYCODE_NUMPAD_4 = 148; public static final int KEYCODE_NUMPAD_5 = 149; public static final int KEYCODE_NUMPAD_6 = 150; public static final int KEYCODE_NUMPAD_7 = 151; public static final int KEYCODE_NUMPAD_8 = 152; public static final int KEYCODE_NUMPAD_9 = 153; public static final int KEYCODE_NUMPAD_ADD = 157; public static final int KEYCODE_NUMPAD_COMMA = 159; public static final int KEYCODE_NUMPAD_DIVIDE = 154; public static final int KEYCODE_NUMPAD_DOT = 158; public static final int KEYCODE_NUMPAD_ENTER = 160; public static final int KEYCODE_NUMPAD_EQUALS = 161; public static final int KEYCODE_NUMPAD_LEFT_PAREN = 162; public static final int KEYCODE_NUMPAD_MULTIPLY = 155; public static final int KEYCODE_NUMPAD_RIGHT_PAREN = 163; public static final int KEYCODE_NUMPAD_SUBTRACT = 156; public static final int KEYCODE_NUM_LOCK = 143; public static final int KEYCODE_PROG_BLUE = 186; public static final int KEYCODE_PROG_GREEN = 184; public static final int KEYCODE_PROG_RED = 183; public static final int KEYCODE_PROG_YELLOW = 185; public static final int KEYCODE_SCROLL_LOCK = 116; public static final int KEYCODE_SETTINGS = 176; public static final int KEYCODE_STB_INPUT = 180; public static final int KEYCODE_STB_POWER = 179; public static final int KEYCODE_SYSRQ = 120; public static final int KEYCODE_TV = 170; public static final int KEYCODE_TV_INPUT = 178; public static final int KEYCODE_TV_POWER = 177; public static final int KEYCODE_VOLUME_MUTE = 164; public static final int KEYCODE_WINDOW = 171; public static final int KEYCODE_ZOOM_IN = 168; public static final int KEYCODE_ZOOM_OUT = 169; public static final int META_ALT_MASK = 50; public static final int META_CAPS_LOCK_ON = 1048576; public static final int META_CTRL_LEFT_ON = 8192; public static final int META_CTRL_MASK = 28672; public static final int META_CTRL_ON = 4096; public static final int META_CTRL_RIGHT_ON = 16384; public static final int META_FUNCTION_ON = 8; public static final int META_META_LEFT_ON = 131072; public static final int META_META_MASK = 458752; public static final int META_META_ON = 65536; public static final int META_META_RIGHT_ON = 262144; public static final int META_NUM_LOCK_ON = 2097152; public static final int META_SCROLL_LOCK_ON = 4194304; public static final int META_SHIFT_MASK = 193; }
gpl-3.0
crisis-economics/CRISIS
CRISIS/src/eu/crisis_economics/abm/markets/clearing/EraseAndReplaceShareDisributionAlgorithm.java
4904
/* * This file is part of CRISIS, an economics simulator. * * Copyright (C) 2015 John Kieran Phillips * * CRISIS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>. */ package eu.crisis_economics.abm.markets.clearing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import eu.crisis_economics.abm.contracts.stocks.UniqueStockExchange; import eu.crisis_economics.abm.contracts.stocks.StockHolder; import eu.crisis_economics.abm.contracts.stocks.StockReleaser; import eu.crisis_economics.abm.markets.clearing.heterogeneous.ResourceDistributionAlgorithm; import eu.crisis_economics.utilities.Pair; /** * @author phillips */ final public class EraseAndReplaceShareDisributionAlgorithm implements ResourceDistributionAlgorithm<StockHolder, StockReleaser> { public EraseAndReplaceShareDisributionAlgorithm() { } // Stateless /** * A share distribution algorithm based on competitive * investment. This algorithm distributes shares to * investors according to the size of their own stock * investment as compared to all others. The final ratio * of distributed shares is as close as possible to the * ratio of shareholder investments. * * This algorithm will operate if marketSuppliers.size()>1, * however, it is expected that the market should consist * of one distinguished supplier only. If marketSuppliers. * size()>1, the first supplier will be treated as the sole * StockReleaser entity in the distribution system. All * other suppliers will be ignored. * * This distribution algorithm returns a Pair<Double, * Double> consisting of: * (a) the total investment in shares, summed over all * shareholders, and * (b) the clearing share price, * in that order. * @see ResourceDistributionAlgorithm.distributeResources */ @Override public Pair<Double, Double> distributeResources( final Map<String, StockHolder> marketConsumers, final Map<String, StockReleaser> marketSuppliers, final Map<Pair<String, String>, Pair<Double, Double>> desiredResourceExchanges ) { if(marketSuppliers.size() > 1 || marketSuppliers.isEmpty()) throw new IllegalArgumentException( "EraseAndReplaceShareDisributionAlgorithm.distributeResources: the caller " + "indicated that the stock does not have a unique releaser. This operating " + "mode is not supported." ); final StockReleaser stockReleaser = marketSuppliers.values().iterator().next(); final double pricePerShare = UniqueStockExchange.Instance.getStockPrice(stockReleaser); double totalAggregateInvestment = 0.; Map<String, Double> desiredStockHolderInvestments = new HashMap<String, Double>(); for(Entry<Pair<String, String>, Pair<Double, Double>> record : desiredResourceExchanges.entrySet()) { final StockHolder stockHolder = marketConsumers.get(record.getKey().getFirst()); final String holderName = stockHolder.getUniqueName(); final double additionalInvestment = record.getValue().getFirst(); if(desiredStockHolderInvestments.containsKey(holderName)) { double position = desiredStockHolderInvestments.get(holderName); desiredStockHolderInvestments.put(holderName, position + additionalInvestment); } else desiredStockHolderInvestments.put(holderName, additionalInvestment); totalAggregateInvestment += additionalInvestment; } List<Pair<StockHolder, Double>> investments = new ArrayList<Pair<StockHolder,Double>>(); for(Entry<String, Double> record : desiredStockHolderInvestments.entrySet()) investments.add(Pair.create(marketConsumers.get(record.getKey()), record.getValue()/totalAggregateInvestment)); System.out.println("resource distribution algorithm:"); System.out.println(investments); UniqueStockExchange.Instance.eraseAndReplaceStockWithoutCompensation( stockReleaser.getUniqueName(), investments, pricePerShare ); return Pair.create(totalAggregateInvestment, pricePerShare); } }
gpl-3.0
lecousin/net.lecousin.neufbox-0.1
net.lecousin.neufbox.mediacenter/src/net/lecousin/neufbox/mediacenter/eclipse/NeufBoxMediaCenter.java
367
package net.lecousin.neufbox.mediacenter.eclipse; import net.lecousin.framework.ui.eclipse.EclipseImages; import net.lecousin.neufbox.mediacenter.eclipse.internal.EclipsePlugin; import org.eclipse.swt.graphics.Image; public class NeufBoxMediaCenter { public static Image getIcon() { return EclipseImages.getImage(EclipsePlugin.ID, "images/icon.bmp"); } }
gpl-3.0
richsmith/sexytopo
app/src/main/java/org/hwyl/sexytopo/control/activity/SettingsActivity.java
752
package org.hwyl.sexytopo.control.activity; import android.os.Bundle; import android.preference.PreferenceFragment; import org.hwyl.sexytopo.R; public class SettingsActivity extends SexyTopoActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.general_preferences); } } }
gpl-3.0
sapia-oss/corus
modules/server/src/main/java/org/sapia/corus/deployer/FileManagerImpl.java
4341
package org.sapia.corus.deployer; import java.io.File; import java.io.FileNotFoundException; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import org.sapia.corus.client.annotations.Bind; import org.sapia.corus.client.common.FilePath; import org.sapia.corus.client.common.ProgressQueue; import org.sapia.corus.client.common.ProgressQueueImpl; import org.sapia.corus.client.services.deployer.DeployerConfiguration; import org.sapia.corus.client.services.deployer.FileCriteria; import org.sapia.corus.client.services.deployer.FileInfo; import org.sapia.corus.client.services.deployer.FileManager; import org.sapia.corus.client.services.file.FileSystemModule; import org.sapia.corus.core.ModuleHelper; import org.sapia.corus.util.IteratorFilter; import org.sapia.corus.util.Matcher; import org.sapia.ubik.rmi.Remote; import org.sapia.ubik.util.Collects; import org.sapia.ubik.util.Func; import org.springframework.beans.factory.annotation.Autowired; /** * Implements the {@link FileManager} interface. * * @author yduchesne * */ @Bind(moduleInterface = { FileManager.class, InternalFileManager.class }) @Remote(interfaces = { FileManager.class }) public class FileManagerImpl extends ModuleHelper implements InternalFileManager { @Autowired private FileSystemModule fileSystem; @Autowired private DeployerConfiguration deployerConfig; private File baseDir; // -------------------------------------------------------------------------- // Provided for testing. public final void setFileSystem(FileSystemModule fileSystem) { this.fileSystem = fileSystem; } public final void setDeployerConfig(DeployerConfiguration deployerConfig) { this.deployerConfig = deployerConfig; } // -------------------------------------------------------------------------- // Module interface @Override public String getRoleName() { return FileManager.ROLE; } // -------------------------------------------------------------------------- // Lifecycle @Override public void init() throws Exception { } @Override public void start() throws Exception { baseDir = FilePath.newInstance().addDir(deployerConfig.getUploadDir()).createFile(); } @Override public void dispose() throws Exception { } // -------------------------------------------------------------------------- // FileManager interface @Override public ProgressQueue deleteFiles(final FileCriteria criteria) { ProgressQueue progress = new ProgressQueueImpl(); List<File> toDelete = IteratorFilter.newFilter(new Matcher<File>() { @Override public boolean matches(File file) { return criteria.getName().matches(file.getName()); } }).filter(fileSystem.listFiles(baseDir).iterator()).get(); for (File f : toDelete) { if (!f.delete()) { progress.info("Could not delete: " + f.getName()); } else { progress.info("Deleted: " + f.getName()); } } progress.close(); return progress; } @Override public List<FileInfo> getFiles() { List<FileInfo> files = Collects.convertAsList(fileSystem.listFiles(baseDir), new Func<FileInfo, File>() { public FileInfo call(File file) { return new FileInfo(file.getName(), file.length(), new Date(file.lastModified())); } }); Collections.sort(files, new FileInfoComparator()); return files; } @Override public List<FileInfo> getFiles(final FileCriteria criteria) { return IteratorFilter.newFilter(new Matcher<FileInfo>() { @Override public boolean matches(FileInfo file) { return criteria.getName().matches(file.getName()); } }).filter(getFiles().iterator()).get(); } @Override public File getFile(FileInfo info) throws FileNotFoundException { File toReturn = new File(baseDir, info.getName()); if (!fileSystem.exists(toReturn)) { throw new FileNotFoundException("File not found: " + toReturn.getAbsolutePath()); } return toReturn; } // ========================================================================== private static class FileInfoComparator implements Comparator<FileInfo> { @Override public int compare(FileInfo o1, FileInfo o2) { return o1.getName().compareTo(o2.getName()); } } }
gpl-3.0
donaldhwong/1Sheeld
oneSheeld/src/main/java/com/integreight/onesheeld/MainActivity.java
27333
package com.integreight.onesheeld; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Process; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.google.android.gms.analytics.HitBuilders; import com.integreight.firmatabluetooth.ArduinoLibraryVersionChangeHandler; import com.integreight.firmatabluetooth.FirmwareVersionQueryHandler; import com.integreight.onesheeld.appFragments.SheeldsList; import com.integreight.onesheeld.popup.ArduinoConnectivityPopup; import com.integreight.onesheeld.popup.ArduinoConnectivityPopup.onConnectedToBluetooth; import com.integreight.onesheeld.popup.FirmwareUpdatingPopup; import com.integreight.onesheeld.popup.ValidationPopup; import com.integreight.onesheeld.services.OneSheeldService; import com.integreight.onesheeld.utils.Log; import com.integreight.onesheeld.utils.customviews.AppSlidingLeftMenu; import com.integreight.onesheeld.utils.customviews.MultiDirectionSlidingDrawer; import org.json.JSONException; import org.json.JSONObject; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Enumeration; import java.util.List; import java.util.concurrent.TimeUnit; public class MainActivity extends FragmentActivity { public AppSlidingLeftMenu appSlidingMenu; public boolean isForground = false; private onConnectedToBluetooth onConnectToBlueTooth = null; public static String currentShieldTag = null; public static MainActivity thisInstance; private boolean isBackPressed = false; public OneSheeldApplication getThisApplication() { return (OneSheeldApplication) getApplication(); } @Override public void onCreate(Bundle arg0) { super.onCreate(arg0); initCrashlyticsAndUncaughtThreadHandler(); setContentView(R.layout.one_sheeld_main); initLooperThread(); replaceCurrentFragment(R.id.appTransitionsContainer, SheeldsList.getInstance(), "base", true, false); resetSlidingMenu(); if (getThisApplication().getAppFirmata() != null) { getThisApplication().getAppFirmata() .addFirmwareVersionQueryHandler(versionChangingHandler); getThisApplication().getAppFirmata() .addArduinoLibraryVersionQueryHandler( arduinoLibraryVersionHandler); } if (getThisApplication().getShowTutAgain() && getThisApplication().getTutShownTimes() < 6) startActivity(new Intent(this, Tutorial.class)); } public Thread looperThread; public Handler backgroundThreadHandler; private Looper backgroundHandlerLooper; private void stopLooperThread() { if (looperThread != null && looperThread.isAlive()) { looperThread.interrupt(); backgroundHandlerLooper.quit(); looperThread = null; } } public void initLooperThread() { stopLooperThread(); looperThread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Looper.prepare(); backgroundHandlerLooper = Looper.myLooper(); backgroundThreadHandler = new Handler(); Looper.loop(); } }); looperThread.start(); } private void initCrashlyticsAndUncaughtThreadHandler() { UncaughtExceptionHandler myHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread arg0, final Throwable arg1) { arg1.printStackTrace(); ArduinoConnectivityPopup.isOpened = false; moveTaskToBack(true); Enumeration<String> enumKey = ((OneSheeldApplication) getApplication()).getRunningShields().keys(); while (enumKey.hasMoreElements()) { String key = enumKey.nextElement(); ((OneSheeldApplication) getApplication()) .getRunningShields().get(key).resetThis(); ((OneSheeldApplication) getApplication()) .getRunningShields().remove(key); } if (((OneSheeldApplication) getApplication()).getAppFirmata() != null) { while (!((OneSheeldApplication) getApplication()) .getAppFirmata().close()) ; } stopService(); Intent in = new Intent(getIntent()); PendingIntent intent = PendingIntent .getActivity(getBaseContext(), 0, in, getIntent().getFlags()); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, intent); getThisApplication().setTutShownTimes( getThisApplication().getTutShownTimes() + 1); killAllProcesses(); } }; Thread.setDefaultUncaughtExceptionHandler(myHandler); if (hasCrashlyticsApiKey(this)) { Crashlytics.start(this); } } Handler versionHandling = new Handler(); FirmwareVersionQueryHandler versionChangingHandler = new FirmwareVersionQueryHandler() { ValidationPopup popub; @Override public void onVersionReceived(final int minorVersion, final int majorVersion) { versionHandling.post(new Runnable() { @Override public void run() { Log.d("Onesheeld", minorVersion + " " + majorVersion); if (getThisApplication().getMinorVersion() != -1 && getThisApplication().getMajorVersion() != -1) { if (majorVersion == getThisApplication() .getMajorVersion() && minorVersion != getThisApplication() .getMinorVersion()) { String msg = ""; try { JSONObject obj = new JSONObject( ((OneSheeldApplication) getApplication()) .getVersionWebResult()); try { msg += obj.getString("name") + "\n"; } catch (Exception e) { // TODO: handle exception } try { msg += obj.getString("description") + "\n"; } catch (Exception e) { // TODO: handle exception } try { msg += "Release Date: " + obj.getString("date"); } catch (Exception e) { // TODO: handle exception } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } popub = new ValidationPopup( MainActivity.this, "Optional Firmware Upgrade", msg, new ValidationPopup.ValidationAction("Now", new View.OnClickListener() { @Override public void onClick(View v) { new FirmwareUpdatingPopup( MainActivity.this/* * , * false */) .show(); } }, true), new ValidationPopup.ValidationAction( "Not Now", new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated // method // stub } }, true)); if (!isFinishing()) popub.show(); } else if (majorVersion != getThisApplication() .getMajorVersion()) { String msg = ""; try { JSONObject obj = new JSONObject( ((OneSheeldApplication) getApplication()) .getVersionWebResult()); try { msg += obj.getString("name") + "\n"; } catch (Exception e) { // TODO: handle exception } try { msg += obj.getString("description") + "\n"; } catch (Exception e) { // TODO: handle exception } try { msg += "Release Date: " + obj.getString("date"); } catch (Exception e) { // TODO: handle exception } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } popub = new ValidationPopup(MainActivity.this, "Required Firmware Upgrade", msg, new ValidationPopup.ValidationAction( "Start", new View.OnClickListener() { @Override public void onClick(View v) { FirmwareUpdatingPopup fup = new FirmwareUpdatingPopup( MainActivity.this/* * , * false */ ); fup.setCancelable(false); fup.show(); } }, true)); if (!isFinishing()) popub.show(); } } } }); getThisApplication().getTracker().send( new HitBuilders.ScreenViewBuilder().setCustomDimension(1, majorVersion + "." + minorVersion).build()); } }; ArduinoLibraryVersionChangeHandler arduinoLibraryVersionHandler = new ArduinoLibraryVersionChangeHandler() { ValidationPopup popub; @Override public void onArduinoLibraryVersionChange(final int version) { versionHandling.post(new Runnable() { @Override public void run() { if (version < OneSheeldApplication.ARDUINO_LIBRARY_VERSION) { popub = new ValidationPopup( MainActivity.this, "Arduino Library Update", "There's a new version of 1Sheeld's Arduino library available on our website!", new ValidationPopup.ValidationAction("OK", new View.OnClickListener() { @Override public void onClick(View v) { popub.dismiss(); } }, true)); if (!isFinishing()) popub.show(); } getThisApplication().getTracker().send( new HitBuilders.ScreenViewBuilder() .setCustomDimension(2, version + "") .build()); } }); } }; @Override protected void onResume() { super.onResume(); } private BackOnconnectionLostHandler backOnConnectionLostHandler; public BackOnconnectionLostHandler getOnConnectionLostHandler() { if (backOnConnectionLostHandler == null) { backOnConnectionLostHandler = new BackOnconnectionLostHandler() { @Override public void handleMessage(Message msg) { if (connectionLost) { if (!ArduinoConnectivityPopup.isOpened && !isFinishing()) runOnUiThread(new Runnable() { public void run() { if (!ArduinoConnectivityPopup.isOpened && !isFinishing()) new ArduinoConnectivityPopup( MainActivity.this).show(); } }); if (getSupportFragmentManager() .getBackStackEntryCount() > 1) { getSupportFragmentManager().beginTransaction() .setCustomAnimations(0, 0, 0, 0) .commitAllowingStateLoss(); getSupportFragmentManager().popBackStack();// ("operations",FragmentManager.POP_BACK_STACK_INCLUSIVE); getSupportFragmentManager() .executePendingTransactions(); } } connectionLost = false; super.handleMessage(msg); } }; } return backOnConnectionLostHandler; } public static class BackOnconnectionLostHandler extends Handler { public boolean canInvokeOnCloseConnection = true, connectionLost = false; } @Override public void onBackPressed() { resetSlidingMenu(); MultiDirectionSlidingDrawer pinsView = (MultiDirectionSlidingDrawer) findViewById(R.id.pinsViewSlidingView); MultiDirectionSlidingDrawer settingsView = (MultiDirectionSlidingDrawer) findViewById(R.id.settingsSlidingView); if ((pinsView == null || (pinsView != null && !pinsView.isOpened())) && (settingsView == null || (settingsView != null && !settingsView .isOpened()))) { if (appSlidingMenu.isOpen()) { appSlidingMenu.closePane(); } else { if (getSupportFragmentManager().getBackStackEntryCount() > 1) { findViewById(R.id.getAvailableDevices).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { } }); getSupportFragmentManager().popBackStack();// ("operations",FragmentManager.POP_BACK_STACK_INCLUSIVE); getSupportFragmentManager().executePendingTransactions(); } else { moveTaskToBack(true); } } } else { if (pinsView.isOpened()) pinsView.animateOpen(); else if (settingsView.isOpened()) settingsView.animateOpen(); } } private void killAllProcesses() { // List<ApplicationInfo> packages; // PackageManager pm; // pm = getPackageManager(); // //get a list of installed apps. // packages = pm.getInstalledApplications(0); // // ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); // // for (ApplicationInfo packageInfo : packages) { // if (packageInfo.packageName.equals("com.integreight.onesheeld")) // mActivityManager.killBackgroundProcesses(packageInfo.packageName); // } android.os.Process.killProcess(Process.myPid()); } public void replaceCurrentFragment(int container, Fragment targetFragment, String tag, boolean addToBackStack, boolean animate) { // String backStateName = tag; // String fragmentTag = tag; if (!isFinishing()) { FragmentManager manager = getSupportFragmentManager(); boolean fragmentPopped = manager.popBackStackImmediate(tag, 0); if (!fragmentPopped && manager.findFragmentByTag(tag) == null) { FragmentTransaction ft = manager.beginTransaction(); if (animate) ft.setCustomAnimations(R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right); ft.replace(container, targetFragment, tag); if (addToBackStack) { ft.addToBackStack(tag); } ft.commit(); } } } public void stopService() { this.stopService(new Intent(this, OneSheeldService.class)); } public void finishManually() { isBackPressed = true; finish(); } @Override protected void onDestroy() { getThisApplication().getTracker().send( new HitBuilders.EventBuilder().setCategory("App lifecycle") .setAction("Finished the app manually").build()); ArduinoConnectivityPopup.isOpened = false; stopService(); stopLooperThread(); moveTaskToBack(true); if (((OneSheeldApplication) getApplication()).getAppFirmata() != null) { while (!((OneSheeldApplication) getApplication()).getAppFirmata() .close()) ; } // // unExpeted if (!isBackPressed) { // new Thread(new Runnable() { // // @Override // public void run() { // tryToSendNotificationsToAdmins(arg1); Enumeration<String> enumKey = ((OneSheeldApplication) getApplication()).getRunningShields().keys(); while (enumKey.hasMoreElements()) { String key = enumKey.nextElement(); ((OneSheeldApplication) getApplication()) .getRunningShields().get(key).resetThis(); ((OneSheeldApplication) getApplication()) .getRunningShields().remove(key); } Intent in = new Intent(getIntent()); PendingIntent intent = PendingIntent.getActivity( getBaseContext(), 0, in, getIntent().getFlags()); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, intent); killAllProcesses(); // } // }).start(); } else killAllProcesses(); isBackPressed = false; super.onDestroy(); } public void openMenu() { resetSlidingMenu(); appSlidingMenu.openPane(); } public void closeMenu() { resetSlidingMenu(); appSlidingMenu.closePane(); } public void enableMenu() { resetSlidingMenu(); appSlidingMenu.setCanSlide(true); } public void disableMenu() { resetSlidingMenu(); appSlidingMenu.closePane(); appSlidingMenu.setCanSlide(false); } private void resetSlidingMenu() { if (appSlidingMenu == null) { appSlidingMenu = (AppSlidingLeftMenu) findViewById(R.id.sliding_pane_layout); } } public void setOnConnectToBluetooth(onConnectedToBluetooth listener) { this.onConnectToBlueTooth = listener; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case SheeldsList.REQUEST_CONNECT_DEVICE: break; case SheeldsList.REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode != Activity.RESULT_OK) { Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); } else { if (onConnectToBlueTooth != null && ArduinoConnectivityPopup.isOpened) onConnectToBlueTooth.onConnect(); } break; default: break; } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onResumeFragments() { thisInstance = this; isForground = true; Crashlytics.setString("isBackground", "No"); new Thread(new Runnable() { @Override public void run() { ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> appProcesses = activityManager .getRunningAppProcesses(); String apps = ""; for (int i = 0; i < appProcesses.size(); i++) { Log.d("Executed app", "Application executed : " + appProcesses.get(i).processName + "\t\t ID: " + appProcesses.get(i).pid + ""); apps += appProcesses.get(i).processName + "\n"; } Crashlytics.setString("Running apps", apps); } }).start(); super.onResumeFragments(); } long pausingTime = 0; @Override protected void onPause() { isForground = false; pausingTime = System.currentTimeMillis(); float hours = TimeUnit.MILLISECONDS.toSeconds(System .currentTimeMillis() - pausingTime); float minutes = TimeUnit.MILLISECONDS.toMinutes(System .currentTimeMillis() - pausingTime); float seconds = TimeUnit.MILLISECONDS.toHours(System .currentTimeMillis() - pausingTime); Crashlytics.setString("isBackground", "since " + hours + " hours - " + minutes + " minutes - " + seconds + " seocnds"); new Thread(new Runnable() { @Override public void run() { ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> appProcesses = activityManager .getRunningAppProcesses(); String apps = ""; for (int i = 0; i < appProcesses.size(); i++) { Log.d("Executed app", "Application executed : " + appProcesses.get(i).processName + "\t\t ID: " + appProcesses.get(i).pid + ""); apps += appProcesses.get(i).processName + " |||||| "; } Crashlytics.setString("Running apps", apps); } }).start(); super.onPause(); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } public void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } public void hideSoftKeyboard() { if (getCurrentFocus() != null) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus() .getWindowToken(), 0); } } public static boolean hasCrashlyticsApiKey(Context context) { boolean hasValidKey = false; try { Context appContext = context.getApplicationContext(); ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; if (bundle != null) { String apiKey = bundle.getString("com.crashlytics.ApiKey"); hasValidKey = apiKey != null && !apiKey.equals("0000000000000000000000000000000000000000"); } } catch (PackageManager.NameNotFoundException e) { // Should not happen since the name was determined dynamically from the app context. // Log.e(LOGTAG, "Unexpected NameNotFound.", e); } return hasValidKey; } }
gpl-3.0
shengqh/RcpaBioJava
test/cn/ac/rcpa/bio/proteomics/sequest/DtaDirectoryIteratorTest.java
861
package cn.ac.rcpa.bio.proteomics.sequest; import junit.framework.TestCase; import cn.ac.rcpa.bio.proteomics.Peak; import cn.ac.rcpa.bio.proteomics.PeakList; public class DtaDirectoryIteratorTest extends TestCase { /* * Test method for 'org.bio.proteomics.AbstractPeakListIterator.next()' */ public void testNext() throws Exception { DtaDirectoryIterator ddi = new DtaDirectoryIterator("data/dta"); assertEquals(true, ddi.hasNext()); PeakList<Peak> pl = ddi.next(); assertEquals("Mix_A_1_5uL_020906_E19",pl.getExperimental()); assertEquals(326,pl.getFirstScan()); assertEquals(326,pl.getLastScan()); assertEquals(847.750, pl.getPrecursor(), 0.001); assertEquals(2, pl.getCharge()); assertEquals(367, pl.getPeaks().size()); ddi.next(); ddi.next(); assertEquals(false, ddi.hasNext()); } }
gpl-3.0
andreiolaru-ro/AmIciTy-Grph
AmIciTy-Grph-PC/source/amicity/graph/pc/gui/JungGraphViewer.java
3189
/* * Copyright (c) 2003, the JUNG Project and the Regents of the University of * California All rights reserved. * * This software is open-source under the BSD license; see either "license.txt" * or http://jung.sourceforge.net/license.txt for a description. * */ package amicity.graph.pc.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Shape; import java.util.Observable; import java.util.Observer; import javax.swing.JPanel; import net.xqhs.graphs.graph.Edge; import net.xqhs.graphs.graph.Node; import org.apache.commons.collections15.Transformer; import amicity.graph.pc.gui.edit.EdgeTransformer; import amicity.graph.pc.gui.edit.NodeStrokeTransformer; import amicity.graph.pc.gui.edit.NodeTransformer; import amicity.graph.pc.jung.JungGraph; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.algorithms.layout.StaticLayout; import edu.uci.ics.jung.algorithms.layout.util.Relaxer; import edu.uci.ics.jung.algorithms.layout.util.VisRunner; import edu.uci.ics.jung.algorithms.util.IterativeContext; import edu.uci.ics.jung.visualization.GraphZoomScrollPane; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.renderers.DefaultEdgeLabelRenderer; import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position; /** * @author Badea Catalin * @author Tom Nelson * */ public class JungGraphViewer extends JPanel { private static final long serialVersionUID = -2023243689258876709L; protected JungGraph graph; protected VisualizationViewer<Node, Edge> vv; protected Layout<Node, Edge> layout; public JungGraphViewer(JungGraph aGraph) { this.graph = aGraph; this.setLayout(new BorderLayout()); layout = new StaticLayout<Node, Edge>(graph); vv = new VisualizationViewer<Node, Edge>(layout); vv.setBackground(Color.white); vv.getRenderContext().setVertexLabelTransformer(new NodeTransformer()); vv.getRenderContext().setEdgeLabelTransformer(new EdgeTransformer()); vv.getRenderContext().setVertexStrokeTransformer(new NodeStrokeTransformer(vv)); vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.YELLOW)); vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); Transformer<Node, Shape> vertexSize = new Transformer<Node, Shape>() { public Shape transform(Node i) { int length = i.getLabel().length() * 10; length = length > 30 ? length : 30; return new Rectangle(-20, -10, length, 30); } }; vv.getRenderContext().setVertexShapeTransformer(vertexSize); final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); panel.setPreferredSize(new Dimension(400, 400)); add(panel, BorderLayout.CENTER); } public void doGraphLayout() { FRLayout<Node, Edge> layout = new FRLayout<Node, Edge>(graph, vv.getSize()); this.layout = layout; vv.getModel().setGraphLayout(layout); } public JungGraph getGraph() { return graph; } public void undo() { graph.undo(); vv.repaint(); } public void redo() { graph.redo(); vv.repaint(); } }
gpl-3.0
otavanopisto/pyramus
rest/src/main/java/fi/otavanopisto/pyramus/rest/controller/permissions/OnlyOwnGroupsPermissionFeature.java
2281
package fi.otavanopisto.pyramus.rest.controller.permissions; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import fi.otavanopisto.pyramus.dao.students.StudentGroupStudentDAO; import fi.otavanopisto.pyramus.dao.students.StudentGroupUserDAO; import fi.otavanopisto.pyramus.domainmodel.students.Student; import fi.otavanopisto.pyramus.domainmodel.students.StudentGroup; import fi.otavanopisto.pyramus.domainmodel.users.StaffMember; import fi.otavanopisto.pyramus.security.impl.Permissions; import fi.otavanopisto.pyramus.security.impl.PyramusPermissionFeatures; import fi.otavanopisto.security.ContextReference; import fi.otavanopisto.security.PermissionFeature; import fi.otavanopisto.security.PermissionFeatureHandler; @PermissionFeature(PyramusPermissionFeatures.ONLY_OWN_GROUPS) @RequestScoped public class OnlyOwnGroupsPermissionFeature implements PermissionFeatureHandler { @Inject private Logger logger; @Inject private StudentGroupUserDAO studentGroupUserDAO; @Inject private StudentGroupStudentDAO studentGroupStudentDAO; @Inject private Permissions permissionController; @Override public boolean hasPermission(String perm, fi.otavanopisto.security.User user, ContextReference contextReference, boolean allowed) { // By default the permission needs to be allowed. This feature only disallows permission. if (!allowed || !permissionController.hasEnvironmentPermission(user, StudentPermissions.FEATURE_OWNED_GROUP_STUDENTS_RESTRICTION)) return allowed; if (contextReference instanceof StudentGroup) { StudentGroup group = (StudentGroup) contextReference; if (user instanceof Student) { return studentGroupStudentDAO.findByStudentGroupAndStudent(group, (Student) user) != null; } else if (user instanceof StaffMember) { return studentGroupUserDAO.findByStudentGroupAndStaffMember(group, (StaffMember) user) != null; } else logger.log(Level.WARNING, "user not Student nor StaffMember, ignoring restrictions"); } else logger.log(Level.WARNING, "ContextReference was not studentGroup, ignoring and returning default permission."); return allowed; } }
gpl-3.0
otavanopisto/pyramus
persistence/src/main/java/fi/otavanopisto/pyramus/domainmodel/base/Language.java
2543
package fi.otavanopisto.pyramus.domainmodel.base; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.TableGenerator; import javax.persistence.Version; import javax.validation.constraints.NotNull; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import org.hibernate.validator.constraints.NotEmpty; /** * Language * * @author antti.viljakainen */ @Entity @Indexed @Cache (usage = CacheConcurrencyStrategy.TRANSACTIONAL) public class Language implements ArchivableEntity { /** * Returns internal unique id. * * @return internal unique id */ public Long getId() { return id; } /** * Sets the language code of this language. * * @param code The language code */ public void setCode(String code) { this.code = code; } /** * Returns the language code of this language. * * @return The language code of this language */ public String getCode() { return code; } /** * Sets user friendly name of this language. * * @param name User friendly name of this language */ public void setName(String name) { this.name = name; } /** * Returns user friendly name of this language. * * @return User friendly name of this language */ public String getName() { return name; } public void setArchived(Boolean archived) { this.archived = archived; } public Boolean getArchived() { return archived; } @SuppressWarnings("unused") private void setVersion(Long version) { this.version = version; } public Long getVersion() { return version; } @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="Language") @TableGenerator(name="Language", allocationSize=1, table = "hibernate_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_next_hi_value") @DocumentId private Long id; @NotNull @NotEmpty @Column (nullable = false) @Field private String code; @NotNull @NotEmpty @Column (nullable = false) @Field private String name; @NotNull @Column (nullable = false) @Field private Boolean archived = Boolean.FALSE; @Version @Column(nullable = false) private Long version; }
gpl-3.0
kyessenov/semeru
src/main/java/edu/mit/csail/cap/instrument/Runtime.java
12100
package edu.mit.csail.cap.instrument; import java.io.PrintStream; import edu.mit.csail.cap.util.JavaEltHash; import edu.mit.csail.cap.util.Stack; import edu.mit.csail.cap.util.trove3.gnu.trove.TCollections; import edu.mit.csail.cap.util.trove3.gnu.trove.map.TObjectLongMap; import edu.mit.csail.cap.util.trove3.gnu.trove.map.hash.TObjectLongHashMap; import edu.mit.csail.cap.wire.AccessArrayMessage; import edu.mit.csail.cap.wire.AccessFieldMessage; import edu.mit.csail.cap.wire.AssignArrayMessage; import edu.mit.csail.cap.wire.AssignFieldMessage; import edu.mit.csail.cap.wire.DeclareClassMessage; import edu.mit.csail.cap.wire.DeclareFieldMessage; import edu.mit.csail.cap.wire.DeclareMethodMessage; import edu.mit.csail.cap.wire.EnterMethodMessage; import edu.mit.csail.cap.wire.ExceptionMessage; import edu.mit.csail.cap.wire.ExitMethodMessage; import edu.mit.csail.cap.wire.StringMessage; import edu.mit.csail.cap.wire.VMValue; /** * Instrumentation runtime. * * This must be thread-safe since methods are called concurrently from * application threads. * * Requires initialization. * * Initial exit events without corresponding enter events are skipped. * * Method enter/exit events are guarded by self variable. State events are not * since only instrumented classes can generate state events. * * @author kuat */ public final class Runtime { // owned by Client static volatile boolean DISABLE = false; public static Configuration policy; public static PrintStream out; private static Client client; private static TObjectLongMap<String> CLASS_CACHE; private static long BOOLEAN_TYPE; private static long SHORT_TYPE; private static long BYTE_TYPE; private static long CHARACTER_TYPE; private static long INT_TYPE; private static long FLOAT_TYPE; private static long LONG_TYPE; @SuppressWarnings("unused") private static long VOID_TYPE; private static long DOUBLE_TYPE; static final ThreadLocal<CallStack> tstack = new ThreadLocal<CallStack>() { @Override protected CallStack initialValue() { return new CallStack(); } }; static class CallStack { /* True while in the instrumentation code. */ boolean self = false; Stack<Integer> domains = new Stack<Integer>(); Stack<Long> hashes = new Stack<Long>(); Stack<Boolean> records = new Stack<Boolean>(); Stack<AssignFieldMessage> delayed = new Stack<AssignFieldMessage>(); Stack<Long> delayedHashes = new Stack<Long>(); void push(int domain, long hash) { // Always record application calls // Record library calls if it is: // * top of the stack // * after an application call // * force included and previous is not force included final boolean record; if (domain == Configuration.APPLICATION) record = true; else { assert domain == Configuration.LIBRARY : "domain is either application or library"; final Integer prev = domains.peek(); if (prev == null) { record = true; } else if (prev == Configuration.APPLICATION) record = true; else record = false; } domains.push(domain); hashes.push(hash); records.push(record); } void pop(long hash) { domains.pop(); records.pop(); final Long old = hashes.pop(); assert old == null || old.equals(hash) : "unexpected pop of " + old + " instead of " + hash + ": " + this; } /** True if the current stack frame should be recorded. */ boolean record() { final Boolean cur = records.peek(); if (cur == null) return false; else return cur; } @Override public String toString() { return hashes.toString(); } } static void initialize(Configuration conf, Client cl, PrintStream out) { Runtime.policy = conf; Runtime.client = cl; Runtime.out = out; Runtime.CLASS_CACHE = TCollections.synchronizedMap(new TObjectLongHashMap<String>()); Runtime.BOOLEAN_TYPE = JavaEltHash.hashClass(Boolean.TYPE.getName()); Runtime.SHORT_TYPE = JavaEltHash.hashClass(Short.TYPE.getName()); Runtime.CHARACTER_TYPE = JavaEltHash.hashClass(Character.TYPE.getName()); Runtime.BYTE_TYPE = JavaEltHash.hashClass(Byte.TYPE.getName()); Runtime.INT_TYPE = JavaEltHash.hashClass(Integer.TYPE.getName()); Runtime.LONG_TYPE = JavaEltHash.hashClass(Long.TYPE.getName()); Runtime.FLOAT_TYPE = JavaEltHash.hashClass(Float.TYPE.getName()); Runtime.VOID_TYPE = JavaEltHash.hashClass(Void.TYPE.getName()); Runtime.DOUBLE_TYPE = JavaEltHash.hashClass(Double.TYPE.getName()); } public static void declareType(String clazz, int access, String superClass, String[] interfaces) { DeclareClassMessage m = new DeclareClassMessage(); m.name = clazz; m.access = access; m.supers = new String[interfaces.length + 1]; m.supers[0] = superClass; for (int i = 0; i < interfaces.length; i++) m.supers[i + 1] = interfaces[i]; client.send(m); long hash = JavaEltHash.hashClass(clazz); Runtime.CLASS_CACHE.put(clazz, hash); } public static long declareType(Class<?> c) { assert !c.isPrimitive() && !c.isArray() : "must be true class " + c; final String name = c.getName().replace('/', '.'); if (policy.listenDeclarations) { DeclareClassMessage m = new DeclareClassMessage(); m.name = name; m.access = c.getModifiers(); m.supers = new String[0]; client.send(m); } final long hash = JavaEltHash.hashClass(name); Runtime.CLASS_CACHE.put(name, hash); return hash; } public static long declareType(String name) { if (policy.listenDeclarations) { DeclareClassMessage m = new DeclareClassMessage(); m.name = name; m.access = -1; m.supers = new String[0]; client.send(m); } final long hash = JavaEltHash.hashClass(name); Runtime.CLASS_CACHE.put(name, hash); return hash; } public static Long typeID(Class<?> c) { if (c.equals(Boolean.TYPE)) return Runtime.BOOLEAN_TYPE; else if (c.equals(Short.TYPE)) return Runtime.SHORT_TYPE; else if (c.equals(Byte.TYPE)) return Runtime.BYTE_TYPE; else if (c.equals(Integer.TYPE)) return Runtime.INT_TYPE; else if (c.equals(Character.TYPE)) return Runtime.CHARACTER_TYPE; else if (c.equals(Long.TYPE)) return Runtime.LONG_TYPE; else if (c.equals(Float.TYPE)) return Runtime.FLOAT_TYPE; else if (c.equals(Double.TYPE)) return Runtime.DOUBLE_TYPE; else return typeID(c.getName()); } public static Long typeID(String name) { if (Runtime.CLASS_CACHE.containsKey(name)) return Runtime.CLASS_CACHE.get(name); else return null; } public static void declareMethod(String clazz, int access, String method, String desc) { DeclareMethodMessage m = new DeclareMethodMessage(); m.clazz = clazz; m.method = method; m.desc = desc; m.access = access; client.send(m); } public static void declareField(String clazz, String name, int access, String desc, Object value) { DeclareFieldMessage m = new DeclareFieldMessage(); m.clazz = clazz; m.name = name; m.access = access; m.desc = desc; m.value = VMValue.make(value); client.send(m); } public static void string(int id, String value) { if (DISABLE) return; StringMessage m = new StringMessage(); m.id = id; m.value = value; client.send(m); } public static void enterMethod(int domain, long hash, Object thisObj, Object[] params) { if (DISABLE) { tstack.remove(); return; } final CallStack stack = tstack.get(); if (!stack.self) { stack.self = true; try { stack.push(domain, hash); if (stack.record()) { EnterMethodMessage m = new EnterMethodMessage(); m.thread = Thread.currentThread().getId(); m.method = hash; m.thisObj = VMValue.make(thisObj); m.params = VMValue.makeAll(params); client.send(m); } // handle field assignments preceding <init> while (stack.delayedHashes.peek() != null && stack.delayedHashes.peek() == hash) { stack.delayedHashes.pop(); AssignFieldMessage m = stack.delayed.pop(); m.thisObj = VMValue.make(thisObj); client.send(m); } } finally { stack.self = false; } } } public static void exitMethod(Object o, long hash) { if (DISABLE) { tstack.remove(); return; } final CallStack stack = tstack.get(); if (!stack.self) { stack.self = true; try { if (stack.record()) { ExitMethodMessage m = new ExitMethodMessage(); m.thread = Thread.currentThread().getId(); m.returnValue = VMValue.make(o); client.send(m); } stack.pop(hash); } finally { stack.self = false; } } } public static void exitMethod(long hash) { exitMethod(VMValue.UNKNOWN, hash); } public static void exitMethod(int i, long hash) { exitMethod((Integer) i, hash); } public static void exitMethod(long l, long hash) { exitMethod((Long) l, hash); } public static void exitMethod(double d, long hash) { exitMethod((Double) d, hash); } public static void exception(Throwable e, long hash) { if (DISABLE) { tstack.remove(); return; } final CallStack stack = tstack.get(); if (!stack.self) { stack.self = true; if (stack.record()) { ExceptionMessage m = new ExceptionMessage(); m.thread = Thread.currentThread().getId(); m.exception = VMValue.make(e); client.send(m); } stack.pop(hash); stack.self = false; } } public static void accessField(Object thisObj, Object oldValue, long owner, String name, int line) { if (DISABLE) return; AccessFieldMessage m = new AccessFieldMessage(); m.thread = Thread.currentThread().getId(); m.thisObj = VMValue.make(thisObj); m.oldValue = VMValue.make(oldValue); m.owner = owner; m.name = name; m.line = line; client.send(m); } public static void assignField(Object thisObj, Object newValue, long owner, String name, int line) { if (DISABLE) return; AssignFieldMessage m = new AssignFieldMessage(); m.thread = Thread.currentThread().getId(); m.thisObj = VMValue.make(thisObj); m.newValue = VMValue.make(newValue); m.owner = owner; m.name = name; m.line = line; client.send(m); } public static void delayedAssignField(Object newValue, long mid, long owner, String name, int line) { if (DISABLE) return; AssignFieldMessage m = new AssignFieldMessage(); m.thread = Thread.currentThread().getId(); m.newValue = VMValue.make(newValue); m.owner = owner; m.name = name; m.line = line; tstack.get().delayed.push(m); tstack.get().delayedHashes.push(mid); } public static void accessArray(Object[] aref, int index, int line) { if (DISABLE) return; // record only successful reads if (aref != null && 0 <= index && index < aref.length) { final Object ref = aref[index]; if (policy.recordArray(ref)) { AccessArrayMessage m = new AccessArrayMessage(); m.thread = Thread.currentThread().getId(); m.array = VMValue.make(aref); m.oldValue = VMValue.make(ref); m.index = index; m.length = aref.length; m.line = line; client.send(m); } } } public static void assignArray(Object[] aref, int index, Object ref, int line) { try { if (DISABLE) return; // record only successful writes if (aref != null && 0 <= index && index < aref.length && policy.recordArray(ref)) { AssignArrayMessage m = new AssignArrayMessage(); m.thread = Thread.currentThread().getId(); m.array = VMValue.make(aref); m.newValue = VMValue.make(ref); m.index = index; m.length = aref.length; m.line = line; client.send(m); } } finally { // perform actual assignment (not done in the original class // anymore) aref[index] = ref; } } /** Declared because of LIBRARY_WHITELIST */ private static final long SYSTEM_ARRAYCOPY = -5829065086251241999L; public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) { final Object[] params = new Object[] { src, srcPos, dest, destPos, length }; enterMethod(Configuration.LIBRARY, SYSTEM_ARRAYCOPY, null, params); try { System.arraycopy(src, srcPos, dest, destPos, length); exitMethod(SYSTEM_ARRAYCOPY); } catch (Throwable e) { exception(e, SYSTEM_ARRAYCOPY); } } }
gpl-3.0
College17Summer/Fleeting
app/src/main/java/com/college17summer/android/fleeting/views/fragments/SettingFragment.java
6417
package com.college17summer.android.fleeting.views.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.college17summer.android.fleeting.R; import com.college17summer.android.fleeting.models.UserEntity; import com.college17summer.android.fleeting.views.activities.CategoryActivity; import com.college17summer.android.fleeting.views.activities.CollectionActivity; import com.college17summer.android.fleeting.views.activities.CommentActivity; import com.college17summer.android.fleeting.views.activities.HistoryActivity; import com.college17summer.android.fleeting.views.activities.LoginActivity; /** * Created by zgh on 17-6-20. */ public class SettingFragment extends Fragment { private static final String ARG_USER_ID = "mUserId"; private String mUserId; private TextView tvHistory; private TextView tvCollection; private TextView tvCategory; private TextView tvComment; private TextView tvLogin; private TextView tvUserName; public SettingFragment() { // Required empty public constructor } public static SettingFragment newInstance(String mUserId) { SettingFragment fragment = new SettingFragment(); Bundle args = new Bundle(); args.putString(ARG_USER_ID, mUserId); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { this.mUserId = getArguments().getString(ARG_USER_ID); } } private void init(View v) { tvUserName = (TextView)v.findViewById(R.id.tv_setting_username); // bind view collection tvCollection = (TextView)v.findViewById(R.id.txt_my_collection); tvCollection.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), CollectionActivity.class); startActivity(intent); } }); // bind view category tvCategory = (TextView)v.findViewById(R.id.txt_my_category); tvCategory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), CategoryActivity.class); startActivity(intent); } }); // bind view comment tvComment = (TextView)v.findViewById(R.id.txt_my_comment); tvComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), CommentActivity.class); startActivity(intent); } }); // bind view history tvHistory = (TextView)v.findViewById(R.id.txt_my_history); tvHistory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), HistoryActivity.class); startActivity(intent); } }); // bind view login&register tvLogin = (TextView)v.findViewById(R.id.txt_log_out); if(UserEntity.getUserInstance().getmId() == 0) { tvUserName.setText(R.string.not_login); tvLogin.setText(R.string.log_in); } else { tvLogin.setText(R.string.log_out); tvUserName.setText(UserEntity.getUserInstance().getmUserName()); } tvLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(UserEntity.getUserInstance().getmId() == 0) { // login in operation Intent intent = new Intent(getActivity(), LoginActivity.class); startActivityForResult(intent,1); } else { // login out operation UserEntity.getUserInstance().setmId(0); UserEntity.getUserInstance().setmUserName(""); // Clear username and log out SharedPreferences sharedPreferences = getContext().getSharedPreferences("UserName", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); UserEntity.getUserInstance().setmUserName(""); UserEntity.getUserInstance().setmId(0); tvUserName.setText(R.string.not_login); Toast.makeText(getActivity(), R.string.info_login_out, Toast.LENGTH_SHORT).show(); tvLogin.setText(R.string.log_in); } } }); } // Update UI @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_settings, container, false); init(view); updateUI(); return view; } private void updateUI() { } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case 1: UserEntity aUser = UserEntity.getUserInstance(); aUser.setmId(1); aUser.setmUserName(data.getStringExtra("username")); aUser.setmPassword(data.getStringExtra("password")); Log.d("tag_login","SettingFragment: " + "username: " + aUser.getmUserName() + ", password: " + aUser.getmPassword()); tvLogin.setText(R.string.log_out); tvUserName.setText(aUser.getmUserName()); break; default: break; } } }
gpl-3.0
kemerelab/RodentDBS
AppCode/RSMControl/app/src/main/java/org/kemerelab/rsmcontrol/RSMDeviceInfoListAdapter.java
7221
package org.kemerelab.rsmcontrol; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by ckemere on 9/16/15. */ public class RSMDeviceInfoListAdapter extends ArrayAdapter<RSMDeviceInfoAtom> { boolean displayOnly; // Just display options? boolean isEnabled; // Enable things like spinners? public RSMDeviceInfoListAdapter(Context context, List<RSMDeviceInfoAtom> items, boolean _displayOnly, boolean _isEnabled) { super(context, 0, items); displayOnly = _displayOnly; isEnabled = _isEnabled; } public interface RSMDeviceInfoSpinnerSelectionListener { public void onSpinnerSelectionListener(RSMDeviceInfoAtom.SettingsType settingsType, int spinnerPosition); } RSMDeviceInfoSpinnerSelectionListener spinnerListener; public void setSpinnerListener(RSMDeviceInfoSpinnerSelectionListener _spinnerListener) { spinnerListener = _spinnerListener; } @Override public int getViewTypeCount() { return 4; } @Override public int getItemViewType(int position) { RSMDeviceInfoAtom p = getItem(position); if ((p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.HEADER) || (p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.STATUS_HEADER)){ return 3; // Headers - formatted special! } else { switch (p.atomAction) { case NONE: return 2; case SPINNER: return 1; default: return 0; } } } static class ViewHolder { TextView caption; TextView datum; TextView header; Spinner datumValues; RSMDeviceInfoAtom.SettingsType settingsType; // used by spinner callbacks } @Override public View getView(int position, View v, ViewGroup parent) { final ViewHolder holder; RSMDeviceInfoAtom p = getItem(position); if (v == null) { holder = new ViewHolder(); holder.settingsType = p.settingsType; LayoutInflater vi; vi = LayoutInflater.from(getContext()); if ((p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.HEADER) || (p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.STATUS_HEADER)) { v = vi.inflate(R.layout.device_info_header, null); holder.header = (TextView) v.findViewById(R.id.SectionHeading); v.setTag(holder); } else { switch (p.atomAction) { case NONE: v = vi.inflate(R.layout.device_info_status_atom, null); holder.caption = (TextView) v.findViewById(R.id.Caption); holder.datum = (TextView) v.findViewById(R.id.Data); break; case TOGGLE_BUTTON: if (displayOnly) v = vi.inflate(R.layout.device_info_atom, null); else v = vi.inflate(R.layout.device_info_atom_button, null); holder.caption = (TextView) v.findViewById(R.id.Caption); holder.datum = (TextView) v.findViewById(R.id.Data); break; case SPINNER: if (displayOnly) { v = vi.inflate(R.layout.device_info_atom, null); holder.caption = (TextView) v.findViewById(R.id.Caption); holder.datum = (TextView) v.findViewById(R.id.Data); } else { v = vi.inflate(R.layout.device_info_atom_spinner, null); holder.caption = (TextView) v.findViewById(R.id.Caption); holder.datumValues = (Spinner) v.findViewById(R.id.DataSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, p.stringValues); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); holder.datumValues.setAdapter(adapter); holder.datumValues.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if (spinnerListener != null) { spinnerListener.onSpinnerSelectionListener(holder.settingsType, position); } } @Override public void onNothingSelected(AdapterView<?> parentView) { // don't do anything } }); holder.datumValues.setEnabled(isEnabled); holder.datumValues.setClickable(isEnabled); } break; default: v = vi.inflate(R.layout.device_info_atom, null); holder.caption = (TextView) v.findViewById(R.id.Caption); holder.datum = (TextView) v.findViewById(R.id.Data); break; } v.setTag(holder); } } else { holder = (ViewHolder) v.getTag(); } // Actually update values! if ((p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.HEADER) || (p.atomFormatting == RSMDeviceInfoAtom.AtomFormatting.STATUS_HEADER)) { holder.header.setText(p.caption); } else { holder.caption.setText(p.caption); switch (p.atomAction) { case SPINNER: if (displayOnly) { holder.datum.setText(p.stringValues.get(p.currentPosition)); } else { holder.datumValues.setSelection(p.currentPosition); holder.datumValues.setEnabled(isEnabled); holder.datumValues.setClickable(isEnabled); } break; case NONE: case TOGGLE_BUTTON: case DIALOG: default: holder.datum.setText(p.stringDatum); break; } } return v; } }
gpl-3.0
EriolEandur/AutoTeleport
AutoTeleport/src/main/java/com/mcmiddleearth/autoteleport/command/AtpConfig.java
3781
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mcmiddleearth.autoteleport.command; import com.mcmiddleearth.autoteleport.data.PluginData; import com.mcmiddleearth.autoteleport.data.TeleportationArea; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; /** * * @author Eriol_Eandur */ public class AtpConfig extends AtpCommand{ public AtpConfig(String... permissionNodes) { super(3, false, permissionNodes); setShortDescription(": configures teleportation details"); setUsageDescription(": DONT'T USE"); } @Override protected void execute(CommandSender cs, String... args) { TeleportationArea area = PluginData.getTeleportationArea(args[0]); if(area==null && !args[0].equals("All")) { sendNoAreaErrorMessage(cs); return; } if(args[0].equals("All")) { if(PluginData.getTeleportAreas().isEmpty()) { sendNoAreaErrorMessage(cs); return; } for(TeleportationArea search: PluginData.getTeleportAreas().values()) { config(cs, search, args); } area = PluginData.getTeleportAreas().values().iterator().next(); } else { config(cs,area,args); } if(area==null) { sendNoAreaErrorMessage(cs); return; } try { PluginData.saveData(); } catch (IOException ex) { sendIOErrorMessage(cs); Logger.getLogger(AtpTarget.class.getName()).log(Level.SEVERE, null, ex); } cs.sendMessage(ChatColor.YELLOW+"Config Data:"); cs.sendMessage(ChatColor.BLUE+"P"+ChatColor.AQUA+"reload distance "+ area.getPreloadDistance()); cs.sendMessage("View "+ChatColor.BLUE+"D"+ChatColor.AQUA+"istance "+ area.getViewDistance()); cs.sendMessage(ChatColor.BLUE+"F"+ChatColor.AQUA+"irst Delay "+ area.getFirstDelay()); cs.sendMessage(ChatColor.BLUE+"T"+ChatColor.AQUA+"eleport Delay "+ area.getTeleportDelay()); cs.sendMessage(ChatColor.BLUE+"V"+ChatColor.AQUA+"elocity Delay "+area.getVelocityDelay()); cs.sendMessage("Velocity "+ChatColor.BLUE+"R"+ChatColor.AQUA+"eps "+ area.getVelocityReps()); cs.sendMessage(ChatColor.BLUE+"R"+ChatColor.AQUA+"ecalc Target "+ area.isRecalculateTarget()); } private void config(CommandSender cs, TeleportationArea area, String... args) { switch(args[1].charAt(0)) { case 'p': area.setPreloadDistance(Integer.parseInt(args[2])); break; case 'd': Logger.getGlobal().info("call set view Distance"); area.setViewDistance(Integer.parseInt(args[2])); break; case 'f': area.setFirstDelay(Integer.parseInt(args[2])); break; case 't': area.setTeleportDelay(Integer.parseInt(args[2])); break; case 'v': area.setVelocityDelay(Integer.parseInt(args[2])); break; case 'r': area.setVelocityReps(Integer.parseInt(args[2])); break; case 'c': area.setRecalculateTarget(Boolean.parseBoolean(args[2])); break; default: cs.sendMessage("Property not found."); } } }
gpl-3.0
snucsne/bio-inspired-leadership
src/edu/snu/leader/hidden/IndividualInfo.java
4299
/* * The Bio-inspired Leadership Toolkit is a set of tools used to * simulate the emergence of leaders in multi-agent systems. * Copyright (C) 2014 Southern Nazarene University * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.snu.leader.hidden; /** * IndividualInfo * * TODO Class description * * @author Brent Eskridge * @version $Revision$ ($Author$) */ public class IndividualInfo { /** The base initiation rate */ private float _initiationRate = 0.0f; /** The alpha parameter for the cancellation rate */ private float _cancelAlpha = 0.0f; /** The gamma parameter for the cancellation rate */ private float _cancelGamma = 0.0f; /** The epsilon parameter for the cancellation rate */ private float _cancelEpsilon = 0.0f; /** The alpha parameter for the following rate */ private float _followAlpha = 0.0f; /** The beta parameter for the following rate */ private float _followBeta = 0.0f; /** The number of times the individual attempted initiation */ private int _initiationAttempts = 0; /** The number of times the individual successfully initiated */ private int _initiationSuccesses = 0; /** * Builds this IndividualInfo object * * @param initiationRate * @param cancelAlpha * @param cancelGamma * @param cancelEpsilon * @param followAlpha * @param followBeta */ public IndividualInfo( float initiationRate, float cancelAlpha, float cancelGamma, float cancelEpsilon, float followAlpha, float followBeta ) { _initiationRate = initiationRate; _cancelAlpha = cancelAlpha; _cancelGamma = cancelGamma; _cancelEpsilon = cancelEpsilon; _followAlpha = followAlpha; _followBeta = followBeta; } /** * Notes that the individual attempted an initiation */ public void signalInitiationAttempt() { _initiationAttempts++; } /** * Notes that the individual was successful in initiating movement */ public void signalInitiationSuccess() { _initiationSuccesses++; } /** * Returns the initiationRate for this object * * @return The initiationRate */ public float getInitiationRate() { return _initiationRate; } /** * Returns the cancelAlpha for this object * * @return The cancelAlpha */ public float getCancelAlpha() { return _cancelAlpha; } /** * Returns the cancelGamma for this object * * @return The cancelGamma */ public float getCancelGamma() { return _cancelGamma; } /** * Returns the cancelEpsilon for this object * * @return The cancelEpsilon */ public float getCancelEpsilon() { return _cancelEpsilon; } /** * Returns the followAlpha for this object * * @return The followAlpha */ public float getFollowAlpha() { return _followAlpha; } /** * Returns the followBeta for this object * * @return The followBeta */ public float getFollowBeta() { return _followBeta; } /** * Returns the initiationAttempts for this object * * @return The initiationAttempts */ public int getInitiationAttempts() { return _initiationAttempts; } /** * Returns the initiationSuccesses for this object * * @return The initiationSuccesses */ public int getInitiationSuccesses() { return _initiationSuccesses; } }
gpl-3.0
andyadc/java-study
rpc-spring/src/main/java/com/andyadc/rpc/SerializationUtils.java
1768
package com.andyadc.rpc; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author andaicheng * @version 2017/7/1 */ @SuppressWarnings("unchecked") public class SerializationUtils { private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>(); private static Objenesis objenesis = new ObjenesisStd(true); private SerializationUtils() { } public static <T> byte[] serialize(T obj) { Class<T> cls = (Class<T>) obj.getClass(); LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { Schema<T> schema = getSchema(cls); return ProtostuffIOUtil.toByteArray(obj, schema, buffer); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } finally { buffer.clear(); } } public static <T> T deserialize(byte[] data, Class<T> cls) { try { T message = objenesis.newInstance(cls); Schema<T> schema = getSchema(cls); ProtostuffIOUtil.mergeFrom(data, message, schema); return message; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } private static <T> Schema<T> getSchema(Class<T> cls) { Schema<T> schema = (Schema<T>) cachedSchema.get(cls); if (schema == null) { schema = RuntimeSchema.createFrom(cls); cachedSchema.put(cls, schema); } return schema; } }
gpl-3.0
wwu-pi/muggl
muggl-solvers/src/de/wwu/muggl/solvers/expressions/Quotient.java
9773
package de.wwu.muggl.solvers.expressions; import java.util.HashSet; import java.util.Set; import de.wwu.muggl.solvers.Solution; import de.wwu.muggl.solvers.solver.constraints.Assignment; import de.wwu.muggl.solvers.solver.constraints.Polynomial; import de.wwu.muggl.solvers.solver.tools.Substitution; import de.wwu.muggl.solvers.solver.tools.SubstitutionTable; /** * Represents the division of two numeric expressions. * <br> * Interesting overridden functions are {@link #toPolynomial()} and {@link #clearMultiFractions} * @author Christoph Lembeck */ public class Quotient extends BinaryOperation{ /** * Creates a new Quotient object representing the division of the passed * numerator by the passed denominator. * If the parameters are of type @{link NumericConstant} they are divided and a * NumericConstant is returned. * @param numerator the numerator of the new quotient. * @param denominator the denominator of the new quotient. * @return the new Quotient expression. */ public static Term newInstance(Term numerator, Term denominator){ if (numerator instanceof NumericConstant && denominator instanceof NumericConstant) return ( (NumericConstant) numerator).divide( (NumericConstant) denominator); return new Quotient(numerator, denominator); } /** * The denominator of the division. */ protected Term denominator; /** * The numerator of the division. */ protected Term numerator; /** * Creates a new Quotient object representing the division of the passed * numerator by the passed denominator. * @param numerator the numerator of the new quotient. * @param denominator the denominator of the new quotient. * @see #newInstance(Term, Term) */ private Quotient(Term numerator, Term denominator) { this.numerator = numerator; this.denominator = denominator; } @Override public void checkTypes() throws TypeCheckException{ numerator.checkTypes(); denominator.checkTypes(); if (!isNumericType(numerator.getType())) throw new TypeCheckException(numerator.toString() + " is not of a numeric type"); if (!isNumericType(denominator.getType())) throw new TypeCheckException(denominator.toString() + " is not of a numeric type"); } @Override protected boolean containsAsDenominator(Term t) { return (denominator.equals(t) || numerator.containsAsDenominator(t)); } @Override public boolean equals(Object other){ if (other == this) return true; if (other instanceof Quotient){ Quotient otherQuotient = (Quotient)other; return numerator.equals(otherQuotient.numerator) && denominator.equals(otherQuotient.denominator); } return false; } @Override protected Substitution findSubstitution(SubstitutionTable subTable) { Substitution result = subTable.lookupSubstitution(this); if (result == null) result = numerator.findSubstitution(subTable); if (result == null) result = denominator.findSubstitution(subTable); return result; } /** * Returns the denominator of the quotient. * @return the denominator of the quotient. */ public Term getDenominator(){ return denominator; } @Override protected Set<Term> getDenominators() { Set<Term> leftSet = numerator.getDenominators(); Set<Term> rightSet = denominator.getDenominators(); if (leftSet == null){ if (rightSet == null){ Set<Term> s = new HashSet<Term>(); s.add(denominator); return s; } else { rightSet.add(denominator); return rightSet; } } else { if (rightSet == null){ leftSet.add(denominator); return leftSet; } else { leftSet.addAll(rightSet); leftSet.add(denominator); return leftSet; } } } @Override protected Quotient getFirstQuotient() { return this; } @Override protected Quotient getInmostQuotient() { Quotient result = numerator.getInmostQuotient(); if (result != null) return result; result = denominator.getInmostQuotient(); if (result != null) return result; return this; } @Override public Term getLeft(){ return numerator; } /** * Returns the numerator of the quotient. * @return the numerator of the quotient. */ public Term getNumerator(){ return numerator; } @Override public Term getRight(){ return denominator; } @Override public byte getType(){ byte leftType = numerator.getType(); byte rightType = denominator.getType(); if ((leftType == Expression.DOUBLE) ||(rightType == Expression.DOUBLE)) return Expression.DOUBLE; if ((leftType == Expression.FLOAT) ||(rightType == Expression.FLOAT)) return Expression.FLOAT; if ((leftType == Expression.LONG) ||(rightType == Expression.LONG)) return Expression.LONG; return Expression.INT; } @Override public int hashCode(){ return numerator.hashCode() / denominator.hashCode(); } @Override public Term insertAssignment(Assignment assignment){ Term numeratorNew = numerator.insertAssignment(assignment); Term denominatorNew = denominator.insertAssignment(assignment); if (denominatorNew instanceof NumericConstant && numeratorNew instanceof NumericConstant) return ((NumericConstant)numeratorNew).divide((NumericConstant)denominatorNew); else return newInstance(numeratorNew, denominatorNew); } @Override public Term insert(Solution solution, boolean produceNumericSolution){ Term numeratorNew = numerator.insert(solution, produceNumericSolution); Term denominatorNew = denominator.insert(solution, produceNumericSolution); if (denominatorNew instanceof NumericConstant && numeratorNew instanceof NumericConstant) return ((NumericConstant)numeratorNew).divide((NumericConstant)denominatorNew); else return newInstance(numeratorNew, denominatorNew); } @Override protected Term multiply(Term factor) { if (denominator.equals(factor)) return numerator; else return new Quotient(numerator.multiply(factor), denominator); } @Override public Term substitute(Term a, Term b) { if (equals(a)) return b; else return new Quotient(numerator.substitute(a, b), denominator.substitute(a, b)); } @Override public String toHaskellString(){ return "(Quotient " + numerator.toHaskellString() + " " + denominator.toHaskellString() + ")"; } /** * Throws an error because fractions can not be transformed to * polynomials without transforming the whole constraint this modulo operation * is member of. Please transform the constraint into an arithmetic equivalent * constraint without containing any fractions operations in it before * generating polynomials out of it. * @return <i>nothing</i>. * @throws InternalError */ @Override public Polynomial toPolynomial() { throw new InternalError(); } @Override public String toString(boolean useInternalVariableNames){ return "(" + numerator.toString(useInternalVariableNames) + "/" + denominator.toString(useInternalVariableNames) + ")"; } @Override public String toTexString(boolean useInternalVariableNames) { return "\\frac{" + numerator.toTexString(useInternalVariableNames) + "}{" + denominator.toTexString(useInternalVariableNames) + "}"; } @Override protected Quotient getFirstNonintegerQuotient(){ if ( Term.isIntegerType(getType()) ) return null; // integer quotients do not contain non-integer members else return this; } @Override public Term clearMultiFractions(Set<Term> denominators) { // recursively clearMultiFractions first, start from bottom up Term newNumerator = numerator.clearMultiFractions(denominators); Term newDenominator = denominator.clearMultiFractions(denominators); // for integer types we already have fractions if ( Term.isIntegerType( getType() ) ){ if (numerator == newNumerator && denominator == newDenominator) return this; else return Quotient.newInstance(newNumerator, newDenominator); } // non-integer types // 1. we get a possibly remaining noninteger quotient in // the current denominator and extend our current quotient with its denominator // (ie multiply denominator and numerator with the nonint quotient's denominator) // to get rid of this quotient // the denominators used to multiply are gathered in denominators set Quotient nonIntQuotient = newDenominator.getFirstNonintegerQuotient(); if (nonIntQuotient != null){ // extend this quotient newNumerator = newNumerator.multiply( nonIntQuotient.getDenominator() ); newDenominator = newDenominator.multiply( nonIntQuotient.getDenominator() ); // add denominator denominators.add( nonIntQuotient.getDenominator() ); } // 2. the numerator is handled analogously nonIntQuotient = newNumerator.getFirstNonintegerQuotient(); if (nonIntQuotient != null){ newNumerator = newNumerator.multiply( nonIntQuotient.getDenominator() ); newDenominator = newDenominator.multiply( nonIntQuotient.getDenominator() ); denominators.add(nonIntQuotient.getDenominator()); } // with the now cleared new denominator and numerator we construct and return // a new quotient without multifractions if (numerator == newNumerator && denominator == newDenominator) return this; else return Quotient.newInstance(newNumerator, newDenominator); } }
gpl-3.0
GeorgH93/MarriageMaster
API/MarriageMaster-API-Bukkit/src/at/pcgamingfreaks/MarriageMaster/Bukkit/API/MarriageMasterPlugin.java
4116
/* * Copyright (C) 2021 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package at.pcgamingfreaks.MarriageMaster.Bukkit.API; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @SuppressWarnings("unused") public interface MarriageMasterPlugin extends at.pcgamingfreaks.MarriageMaster.API.MarriageMasterPlugin<OfflinePlayer, MarriagePlayer, Marriage, CommandManager, DelayableTeleportAction> { /** * Checks if two players are within a certain range to each other. * * @param player1 The fist player to be checked. * @param player2 The second player to be checked. * @param range The range in which the two players should be. * @return True if the players are within the given range, false if not. * Also True if one of the players has the "marry.bypass.rangelimit" permission, the range is 0 and both players are in the same world or the range is below 0. */ boolean isInRange(@NotNull Player player1, @NotNull Player player2, double range); /** * Checks if two players are within a certain range to each other. * * @param player1 The fist player to be checked. * @param player2 The second player to be checked. * @param rangeSquared The squared distance in which the two players should be. * @return True if the players are within the given range, false if not. * Also True if one of the players has the "marry.bypass.rangelimit" permission, the range is 0 and both players are in the same world or the range is below 0. */ boolean isInRangeSquared(@NotNull Player player1, @NotNull Player player2, double rangeSquared); /** * Checks if two players are within a certain range to each other. * * @param player1 The fist player to be checked. * @param player2 The second player to be checked. * @param range The range in which the two players should be. * @return True if the players are within the given range, false if not. * Also True if one of the players has the "marry.bypass.rangelimit" permission, the range is 0 and both players are in the same world or the range is below 0. */ default boolean isInRange(@NotNull MarriagePlayer player1, @NotNull MarriagePlayer player2, double range) { Player bPlayer1 = player1.getPlayerOnline(), bPlayer2 = player2.getPlayerOnline(); return bPlayer1 != null && bPlayer2 != null && isInRange(bPlayer1, bPlayer2, range); } /** * Checks if two players are within a certain range to each other. * * @param player1 The fist player to be checked. * @param player2 The second player to be checked. * @param rangeSquared The squared distance in which the two players should be. * @return True if the players are within the given range, false if not. * Also True if one of the players has the "marry.bypass.rangelimit" permission, the range is 0 and both players are in the same world or the range is below 0. */ default boolean isInRangeSquared(@NotNull MarriagePlayer player1, @NotNull MarriagePlayer player2, double rangeSquared) { Player bPlayer1 = player1.getPlayerOnline(), bPlayer2 = player2.getPlayerOnline(); return bPlayer1 != null && bPlayer2 != null && isInRangeSquared(bPlayer1, bPlayer2, rangeSquared); } /** * Gets the marriage manager. Needed to do stuff like marry, divorce or change surnames. * * @return The marriage manager. */ @NotNull MarriageManager getMarriageManager(); @NotNull PrefixSuffixFormatter getPrefixSuffixFormatter(); }
gpl-3.0
NuenoB/OpenBlocks_UCHILE
openmodslib/src/openmods/integration/Integration.java
1117
package openmods.integration; import java.lang.annotation.*; import java.lang.reflect.Field; import openmods.Mods; import openmods.integration.ModuleBuildCraft.ModuleBuildCraftLive; import com.google.common.base.Throwables; import cpw.mods.fml.common.Loader; public class Integration { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public static @interface Module { public String modId(); public Class<?> live(); } @Module(modId = Mods.BUILDCRAFT, live = ModuleBuildCraftLive.class) private static ModuleBuildCraft buildCraft = new ModuleBuildCraft(); public static ModuleBuildCraft modBuildCraft() { return buildCraft; } public static void selectModules() { for (Field f : Integration.class.getDeclaredFields()) { Module mod = f.getAnnotation(Module.class); if (mod != null && Loader.isModLoaded(mod.modId())) { try { Class<?> liveReplacementCls = mod.live(); f.setAccessible(true); Object replacement = liveReplacementCls.newInstance(); f.set(null, replacement); } catch (Exception e) { Throwables.propagate(e); } } } } }
gpl-3.0
waikato-datamining/adams-base
adams-spreadsheet/src/main/java/adams/flow/transformer/SpreadSheetAnonymize.java
8940
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SpreadSheetAnonymize.java * Copyright (C) 2012-2013 University of Waikato, Hamilton, New Zealand */ package adams.flow.transformer; import java.util.ArrayList; import java.util.Hashtable; import adams.core.QuickInfoHelper; import adams.core.Randomizable; import adams.core.base.BaseRegExp; import adams.data.AbstractAnonymizer; import adams.data.DoubleAnonymizer; import adams.data.StringAnonymizer; import adams.data.spreadsheet.Cell; import adams.data.spreadsheet.Row; import adams.data.spreadsheet.SpreadSheet; import adams.flow.core.Token; /** <!-- globalinfo-start --> * Anonymizes a range of columns in a spreadsheet. * <br><br> <!-- globalinfo-end --> * <!-- flow-summary-start --> * Input&#47;output:<br> * - accepts:<br> * &nbsp;&nbsp;&nbsp;adams.core.io.SpreadSheet<br> * - generates:<br> * &nbsp;&nbsp;&nbsp;adams.core.io.SpreadSheet<br> * <br><br> <!-- flow-summary-end --> * <!-- options-start --> * Valid options are: <br><br> * * <pre>-D &lt;int&gt; (property: debugLevel) * &nbsp;&nbsp;&nbsp;The greater the number the more additional info the scheme may output to * &nbsp;&nbsp;&nbsp;the console (0 = off). * &nbsp;&nbsp;&nbsp;default: 0 * &nbsp;&nbsp;&nbsp;minimum: 0 * </pre> * * <pre>-name &lt;java.lang.String&gt; (property: name) * &nbsp;&nbsp;&nbsp;The name of the actor. * &nbsp;&nbsp;&nbsp;default: SpreadSheetAnonymize * </pre> * * <pre>-annotation &lt;adams.core.base.BaseText&gt; (property: annotations) * &nbsp;&nbsp;&nbsp;The annotations to attach to this actor. * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-skip (property: skip) * &nbsp;&nbsp;&nbsp;If set to true, transformation is skipped and the input token is just forwarded * &nbsp;&nbsp;&nbsp;as it is. * </pre> * * <pre>-stop-flow-on-error (property: stopFlowOnError) * &nbsp;&nbsp;&nbsp;If set to true, the flow gets stopped in case this actor encounters an error; * &nbsp;&nbsp;&nbsp; useful for critical actors. * </pre> * * <pre>-col-regexp &lt;adams.core.base.BaseRegExp&gt; (property: columnsRegExp) * &nbsp;&nbsp;&nbsp;The regular expression applied to the column names to locate the columns * &nbsp;&nbsp;&nbsp;to anonymize. * &nbsp;&nbsp;&nbsp;default: ^ID$ * </pre> * * <pre>-seed &lt;long&gt; (property: seed) * &nbsp;&nbsp;&nbsp;The seed value for the anonymizers. * &nbsp;&nbsp;&nbsp;default: 1 * </pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SpreadSheetAnonymize extends AbstractSpreadSheetTransformer implements Randomizable { /** for serialization. */ private static final long serialVersionUID = -2767861909141864017L; /** the key for storing the mapping of column names/anonymizers. */ public final static String BACKUP_MAPPING = "mapping"; /** the columns to anonymize. */ protected BaseRegExp m_ColumnsRegExp; /** the seed value. */ protected long m_Seed; /** the column/anonymizer mapping. */ protected Hashtable<String,AbstractAnonymizer> m_Mapping; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Anonymizes a range of columns in a spreadsheet."; } /** * Adds options to the internal list of options. */ @Override public void defineOptions() { super.defineOptions(); m_OptionManager.add( "col-regexp", "columnsRegExp", new BaseRegExp("^ID$")); m_OptionManager.add( "seed", "seed", 1L); } /** * Initializes the members. */ @Override protected void initialize() { super.initialize(); m_Mapping = new Hashtable<String,AbstractAnonymizer>(); } /** * Removes entries from the backup. */ @Override protected void pruneBackup() { super.pruneBackup(); pruneBackup(BACKUP_MAPPING); } /** * Backs up the current state of the actor before update the variables. * * @return the backup */ @Override protected Hashtable<String,Object> backupState() { Hashtable<String,Object> result; result = super.backupState(); if (m_Mapping != null) result.put(BACKUP_MAPPING, m_Mapping); return result; } /** * Restores the state of the actor before the variables got updated. * * @param state the backup of the state to restore from */ @Override protected void restoreState(Hashtable<String,Object> state) { if (state.containsKey(BACKUP_MAPPING)) { m_Mapping = (Hashtable<String,AbstractAnonymizer>) state.get(BACKUP_MAPPING); state.remove(BACKUP_MAPPING); } super.restoreState(state); } /** * Returns a quick info about the actor, which will be displayed in the GUI. * * @return null if no info available, otherwise short string */ @Override public String getQuickInfo() { String result; result = QuickInfoHelper.toString(this, "columnsRegExp", m_ColumnsRegExp, "cols: "); result += QuickInfoHelper.toString(this, "seed", m_Seed, ", seed: "); return result; } /** * Sets the regular expression for the column names of columns to anonymize. * * @param value the regular expression */ public void setColumnsRegExp(BaseRegExp value) { m_ColumnsRegExp = value; reset(); } /** * Returns the regular expression for the column names of columns to anonymize. * * @return the regular expression */ public BaseRegExp getColumnsRegExp() { return m_ColumnsRegExp; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String columnsRegExpTipText() { return "The regular expression applied to the column names to locate the columns to anonymize."; } /** * Sets the seed value. * * @param value the seed */ public void setSeed(long value) { m_Seed = value; reset(); } /** * Returns the seed value. * * @return the seed */ public long getSeed() { return m_Seed; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String seedTipText() { return "The seed value for the anonymizers."; } /** * Executes the flow item. * * @return null if everything is fine, otherwise error message */ @Override protected String doExecute() { String result; SpreadSheet sheet; Row row; int i; int n; String colName; ArrayList<Boolean> numeric; ArrayList<String> names; ArrayList<String> id; Cell cell; Object anon; result = null; sheet = (SpreadSheet) m_InputToken.getPayload(); if (sheet.getRowCount() > 0) { // set up anonymizers row = sheet.getHeaderRow(); numeric = new ArrayList<Boolean>(); names = new ArrayList<String>(); id = new ArrayList<String>(); for (i = 0; i < row.getCellCount(); i++) { colName = row.getCell(i).getContent(); if (m_ColumnsRegExp.isMatch(colName)) { names.add(colName); numeric.add(sheet.isNumeric(i, true)); id.add(row.getCellKey(i)); if (!m_Mapping.containsKey(colName)) { if (numeric.get(numeric.size() - 1)) m_Mapping.put(colName, new DoubleAnonymizer(colName, m_Seed, sheet.getRowCount())); else m_Mapping.put(colName, new StringAnonymizer(colName, m_Seed, sheet.getRowCount())); } } } if (names.size() > 0) { sheet = sheet.getClone(); for (n = 0; n < sheet.getRowCount(); n++) { row = sheet.getRow(n); for (i = 0; i < names.size(); i++) { if (row.getCell(id.get(i)).isMissing()) continue; cell = row.getCell(id.get(i)); if (numeric.get(i)) anon = m_Mapping.get(names.get(i)).anonymize(cell.toDouble()); else anon = m_Mapping.get(names.get(i)).anonymize(cell.toString()); if (anon instanceof Double) cell.setContent((Double) anon); else cell.setContent((String) anon); } } } } m_OutputToken = new Token(sheet); return result; } }
gpl-3.0
npes87184/PhotoMap
gen/com/npes87184/photomap/R.java
26076
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.npes87184.photomap; public final class R { public static final class array { public static final int efp__size_units=0x7f080000; public static final int efp__sorting_types=0x7f080001; } public static final class attr { /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_cancel=0x7f010001; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_deselect=0x7f010002; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_grid=0x7f010003; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_invert_selection=0x7f010004; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_list=0x7f010005; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_new_folder=0x7f010006; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_ok=0x7f010007; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_select_all=0x7f010008; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__ic_action_sort=0x7f010009; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int efp__selected_item_background=0x7f010000; } public static final class color { public static final int efp__header_button_pressed_color=0x7f050001; public static final int efp__header_divider_color=0x7f050002; public static final int efp__header_line_color=0x7f050000; } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f090000; public static final int activity_vertical_margin=0x7f090001; } public static final class drawable { public static final int efp__header_buttons_selector=0x7f020000; public static final int efp__ic_file=0x7f020001; public static final int efp__ic_folder=0x7f020002; public static final int efp__ic_launcher=0x7f020003; public static final int efp_dark__activated_background_holo=0x7f020004; public static final int efp_dark__btn_check_holo=0x7f020005; public static final int efp_dark__btn_check_off_disabled_focused_holo=0x7f020006; public static final int efp_dark__btn_check_off_disabled_holo=0x7f020007; public static final int efp_dark__btn_check_off_focused_holo=0x7f020008; public static final int efp_dark__btn_check_off_holo=0x7f020009; public static final int efp_dark__btn_check_off_pressed_holo=0x7f02000a; public static final int efp_dark__btn_check_on_disabled_focused_holo=0x7f02000b; public static final int efp_dark__btn_check_on_disabled_holo=0x7f02000c; public static final int efp_dark__btn_check_on_focused_holo=0x7f02000d; public static final int efp_dark__btn_check_on_holo=0x7f02000e; public static final int efp_dark__btn_check_on_pressed_holo=0x7f02000f; public static final int efp_dark__edit_text_holo=0x7f020010; public static final int efp_dark__ic_action_cancel=0x7f020011; public static final int efp_dark__ic_action_deselect=0x7f020012; public static final int efp_dark__ic_action_grid=0x7f020013; public static final int efp_dark__ic_action_invert_selection=0x7f020014; public static final int efp_dark__ic_action_list=0x7f020015; public static final int efp_dark__ic_action_new_folder=0x7f020016; public static final int efp_dark__ic_action_ok=0x7f020017; public static final int efp_dark__ic_action_select_all=0x7f020018; public static final int efp_dark__ic_action_sort=0x7f020019; public static final int efp_dark__item_background_holo=0x7f02001a; public static final int efp_dark__list_activated_holo=0x7f02001b; public static final int efp_dark__list_focused_holo=0x7f02001c; public static final int efp_dark__list_longpressed_holo=0x7f02001d; public static final int efp_dark__list_pressed_holo=0x7f02001e; public static final int efp_dark__list_selector_background_transition_holo=0x7f02001f; public static final int efp_dark__list_selector_disabled_holo=0x7f020020; public static final int efp_dark__list_selector_holo=0x7f020021; public static final int efp_dark__text_select_handle_left=0x7f020022; public static final int efp_dark__text_select_handle_middle=0x7f020023; public static final int efp_dark__text_select_handle_right=0x7f020024; public static final int efp_dark__textfield_activated_holo=0x7f020025; public static final int efp_dark__textfield_default_holo=0x7f020026; public static final int efp_dark__textfield_disabled_focused_holo=0x7f020027; public static final int efp_dark__textfield_disabled_holo=0x7f020028; public static final int efp_dark__textfield_focused_holo=0x7f020029; public static final int efp_light__activated_background_holo=0x7f02002a; public static final int efp_light__btn_check_holo=0x7f02002b; public static final int efp_light__btn_check_off_disabled_focused_holo=0x7f02002c; public static final int efp_light__btn_check_off_disabled_holo=0x7f02002d; public static final int efp_light__btn_check_off_focused_holo=0x7f02002e; public static final int efp_light__btn_check_off_holo=0x7f02002f; public static final int efp_light__btn_check_off_pressed_holo=0x7f020030; public static final int efp_light__btn_check_on_disabled_focused_holo=0x7f020031; public static final int efp_light__btn_check_on_disabled_holo=0x7f020032; public static final int efp_light__btn_check_on_focused_holo=0x7f020033; public static final int efp_light__btn_check_on_holo=0x7f020034; public static final int efp_light__btn_check_on_pressed_holo=0x7f020035; public static final int efp_light__edit_text_holo=0x7f020036; public static final int efp_light__ic_action_cancel=0x7f020037; public static final int efp_light__ic_action_deselect=0x7f020038; public static final int efp_light__ic_action_grid=0x7f020039; public static final int efp_light__ic_action_invert_selection=0x7f02003a; public static final int efp_light__ic_action_list=0x7f02003b; public static final int efp_light__ic_action_new_folder=0x7f02003c; public static final int efp_light__ic_action_ok=0x7f02003d; public static final int efp_light__ic_action_select_all=0x7f02003e; public static final int efp_light__ic_action_sort=0x7f02003f; public static final int efp_light__item_background_holo=0x7f020040; public static final int efp_light__list_activated_holo=0x7f020041; public static final int efp_light__list_focused_holo=0x7f020042; public static final int efp_light__list_longpressed_holo=0x7f020043; public static final int efp_light__list_pressed_holo=0x7f020044; public static final int efp_light__list_selector_background_transition_holo=0x7f020045; public static final int efp_light__list_selector_disabled_holo=0x7f020046; public static final int efp_light__list_selector_holo=0x7f020047; public static final int efp_light__text_select_handle_left=0x7f020048; public static final int efp_light__text_select_handle_middle=0x7f020049; public static final int efp_light__text_select_handle_right=0x7f02004a; public static final int efp_light__textfield_activated_holo=0x7f02004b; public static final int efp_light__textfield_default_holo=0x7f02004c; public static final int efp_light__textfield_disabled_focused_holo=0x7f02004d; public static final int efp_light__textfield_disabled_holo=0x7f02004e; public static final int efp_light__textfield_focused_holo=0x7f02004f; public static final int emo_im_laughing=0x7f020050; public static final int ic_launcher=0x7f020051; public static final int ic_menu_info_details=0x7f020052; public static final int ic_menu_recent_history=0x7f020053; public static final int ic_menu_share=0x7f020054; } public static final class id { public static final int RelativeLayout1=0x7f0b0006; public static final int action_settings=0x7f0b001e; public static final int action_share=0x7f0b001f; public static final int checkbox=0x7f0b0009; public static final int container=0x7f0b0003; public static final int filename=0x7f0b0008; public static final int filesize=0x7f0b000a; public static final int gridview=0x7f0b001c; public static final int header1=0x7f0b000b; public static final int header2=0x7f0b0012; public static final int line=0x7f0b001a; public static final int listview=0x7f0b001b; public static final int menu_cancel=0x7f0b0013; public static final int menu_change_view=0x7f0b000f; public static final int menu_deselect=0x7f0b0017; public static final int menu_invert=0x7f0b0016; public static final int menu_new_folder=0x7f0b000e; public static final int menu_ok1=0x7f0b0010; public static final int menu_ok2=0x7f0b0014; public static final int menu_select_all=0x7f0b0018; public static final int menu_sort1=0x7f0b000d; public static final int menu_sort2=0x7f0b0019; public static final int name=0x7f0b001d; public static final int ok1_delimiter=0x7f0b0011; public static final int textView1=0x7f0b0005; public static final int textView2=0x7f0b0000; public static final int textView3=0x7f0b0001; public static final int textView4=0x7f0b0002; public static final int thumbnail=0x7f0b0007; public static final int title=0x7f0b000c; public static final int view1=0x7f0b0015; public static final int webView1=0x7f0b0004; } public static final class layout { public static final int about=0x7f030000; public static final int activity_main=0x7f030001; public static final int activity_map=0x7f030002; public static final int efp__empty=0x7f030003; public static final int efp__grid_item=0x7f030004; public static final int efp__list_item=0x7f030005; public static final int efp__main_activity=0x7f030006; public static final int efp__new_folder=0x7f030007; public static final int fragment_main=0x7f030008; public static final int fragment_map=0x7f030009; public static final int no_ota=0x7f03000a; public static final int ota=0x7f03000b; } public static final class menu { public static final int main=0x7f0a0000; public static final int map=0x7f0a0001; } public static final class string { public static final int about=0x7f070020; public static final int about_detail=0x7f07001e; public static final int about_key=0x7f070021; public static final int action_settings=0x7f07000f; public static final int action_share=0x7f070013; public static final int app_name=0x7f07000d; public static final int app_website=0x7f070018; public static final int author=0x7f07001c; public static final int check_update=0x7f070022; public static final int check_update_key=0x7f070023; public static final int checking=0x7f07001b; public static final int efp__action_deselect=0x7f070005; public static final int efp__action_grid=0x7f070001; public static final int efp__action_invert_selection=0x7f070006; public static final int efp__action_list=0x7f070002; public static final int efp__action_select_all=0x7f070004; public static final int efp__app_name=0x7f070000; public static final int efp__empty_directory=0x7f070003; public static final int efp__folder_already_exists=0x7f07000b; public static final int efp__folder_created=0x7f070009; public static final int efp__folder_name_hint=0x7f070008; public static final int efp__folder_not_created=0x7f07000a; public static final int efp__new_folder=0x7f070007; public static final int efp__sort=0x7f07000c; public static final int hello_world=0x7f07000e; public static final int new_version=0x7f070019; public static final int new_version_number=0x7f070014; public static final int no_new_version=0x7f070015; public static final int no_version=0x7f07001a; public static final int problem=0x7f070016; public static final int start_key=0x7f070010; public static final int start_title=0x7f070011; public static final int tip=0x7f07001f; public static final int title_activity_map=0x7f070012; public static final int version=0x7f070017; public static final int version_name=0x7f07001d; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f06000e; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f06000f; public static final int CheckBoxExFilePickerThemeDark=0x7f060001; public static final int CheckBoxExFilePickerThemeLight=0x7f060008; public static final int EditTextExFilePickerThemeDark=0x7f060000; public static final int EditTextExFilePickerThemeLight=0x7f060007; public static final int ExFilePickerThemeDark=0x7f060005; public static final int ExFilePickerThemeLight=0x7f06000c; public static final int ListViewExFilePickerThemeDark=0x7f060002; public static final int ListViewExFilePickerThemeDark_White=0x7f060003; public static final int ListViewExFilePickerThemeLight=0x7f060009; public static final int ListViewExFilePickerThemeLight_White=0x7f06000a; public static final int SpinnerItemExFilePickerThemeDark=0x7f060004; public static final int SpinnerItemExFilePickerThemeLight=0x7f06000b; public static final int _ExFilePickerThemeDark=0x7f060006; public static final int _ExFilePickerThemeLight=0x7f06000d; } public static final class xml { public static final int preference=0x7f040000; } public static final class styleable { /** Attributes that can be used with a customAttrs. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_cancel com.npes87184.photomap:efp__ic_action_cancel}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_deselect com.npes87184.photomap:efp__ic_action_deselect}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_grid com.npes87184.photomap:efp__ic_action_grid}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_invert_selection com.npes87184.photomap:efp__ic_action_invert_selection}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_list com.npes87184.photomap:efp__ic_action_list}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_new_folder com.npes87184.photomap:efp__ic_action_new_folder}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_ok com.npes87184.photomap:efp__ic_action_ok}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_select_all com.npes87184.photomap:efp__ic_action_select_all}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__ic_action_sort com.npes87184.photomap:efp__ic_action_sort}</code></td><td></td></tr> <tr><td><code>{@link #customAttrs_efp__selected_item_background com.npes87184.photomap:efp__selected_item_background}</code></td><td></td></tr> </table> @see #customAttrs_efp__ic_action_cancel @see #customAttrs_efp__ic_action_deselect @see #customAttrs_efp__ic_action_grid @see #customAttrs_efp__ic_action_invert_selection @see #customAttrs_efp__ic_action_list @see #customAttrs_efp__ic_action_new_folder @see #customAttrs_efp__ic_action_ok @see #customAttrs_efp__ic_action_select_all @see #customAttrs_efp__ic_action_sort @see #customAttrs_efp__selected_item_background */ public static final int[] customAttrs = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009 }; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_cancel} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_cancel */ public static final int customAttrs_efp__ic_action_cancel = 1; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_deselect} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_deselect */ public static final int customAttrs_efp__ic_action_deselect = 2; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_grid} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_grid */ public static final int customAttrs_efp__ic_action_grid = 3; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_invert_selection} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_invert_selection */ public static final int customAttrs_efp__ic_action_invert_selection = 4; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_list} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_list */ public static final int customAttrs_efp__ic_action_list = 5; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_new_folder} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_new_folder */ public static final int customAttrs_efp__ic_action_new_folder = 6; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_ok} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_ok */ public static final int customAttrs_efp__ic_action_ok = 7; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_select_all} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_select_all */ public static final int customAttrs_efp__ic_action_select_all = 8; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__ic_action_sort} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__ic_action_sort */ public static final int customAttrs_efp__ic_action_sort = 9; /** <p>This symbol is the offset where the {@link com.npes87184.photomap.R.attr#efp__selected_item_background} attribute's value can be found in the {@link #customAttrs} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.npes87184.photomap:efp__selected_item_background */ public static final int customAttrs_efp__selected_item_background = 0; }; }
gpl-3.0
hamstercommunity/openfasttrack
api/src/test/java/org/itsallcode/openfasttrace/api/report/TestReportException.java
1263
package org.itsallcode.openfasttrace.api.report; /*- * #%L * OpenFastTrace API * %% * Copyright (C) 2016 - 2019 itsallcode.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import org.junit.jupiter.api.Test; class TestReportException { @Test void testConstructorWithCause() { assertThat(new ReportException("message", new RuntimeException()), notNullValue()); } @Test void testConstructorWithoutCause() { assertThat(new ReportException("message"), notNullValue()); } }
gpl-3.0
LorenaCapo/JavaProgramming
Distancias/src/distancias/ConversorDistancias.java
894
package distancias; public class ConversorDistancias { public static double conversorPiesToMetros(double pies){ return pies * 0.3048; } public static double conversorMetrosToPies(double metros){ return metros * 3.2808; } public static double conversorPiesToPulgadas(double pies){ return pies * 12; } public static double conversorPulgadasToPies(double pulgadas){ return pulgadas / 12; } public static double conversorCmToPies(double cm){ return conversorMetrosToPies(cm / 100); } public static double conversorPiesToCm(double pies){ return conversorPiesToMetros(pies) * 100; } public static double conversorCmToPulgadas(double cm){ return conversorPiesToPulgadas(conversorCmToPies(cm)); } public static double conversorPulgadasToCm(double pulgadas){ return conversorPiesToCm(conversorPulgadasToPies(pulgadas)); } }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/widget/src/android/widget/cts/TabWidgetTest.java
14609
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget.cts; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.suitebuilder.annotation.SmallTest; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TabWidget; import android.widget.TextView; import android.widget.cts.util.TestUtils; /** * Test {@link TabWidget}. */ @SmallTest public class TabWidgetTest extends ActivityInstrumentationTestCase2<TabHostCtsActivity> { private Activity mActivity; public TabWidgetTest() { super("android.widget.cts", TabHostCtsActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mActivity = getActivity(); } public void testConstructor() { new TabWidget(mActivity); new TabWidget(mActivity, null); new TabWidget(mActivity, null, 0); } public void testConstructorWithStyle() { TabWidget tabWidget = new TabWidget(mActivity, null, 0, R.style.TabWidgetCustomStyle); assertFalse(tabWidget.isStripEnabled()); Drawable leftStripDrawable = tabWidget.getLeftStripDrawable(); assertNotNull(leftStripDrawable); TestUtils.assertAllPixelsOfColor("Left strip green", leftStripDrawable, leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(), true, 0xFF00FF00, 1, false); Drawable rightStripDrawable = tabWidget.getRightStripDrawable(); assertNotNull(rightStripDrawable); TestUtils.assertAllPixelsOfColor("Right strip red", rightStripDrawable, rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(), true, 0xFFFF0000, 1, false); } public void testInflateFromXml() { LayoutInflater inflater = LayoutInflater.from(mActivity); TabWidget tabWidget = (TabWidget) inflater.inflate(R.layout.tabhost_custom, null, false); assertFalse(tabWidget.isStripEnabled()); Drawable leftStripDrawable = tabWidget.getLeftStripDrawable(); assertNotNull(leftStripDrawable); TestUtils.assertAllPixelsOfColor("Left strip red", leftStripDrawable, leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(), true, 0xFFFF0000, 1, false); Drawable rightStripDrawable = tabWidget.getRightStripDrawable(); assertNotNull(rightStripDrawable); TestUtils.assertAllPixelsOfColor("Right strip green", rightStripDrawable, rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(), true, 0xFF00FF00, 1, false); } @UiThreadTest public void testTabCount() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); // We have one tab added in onCreate() of our activity assertEquals(1, tabWidget.getTabCount()); for (int i = 1; i < 10; i++) { tabWidget.addView(new TextView(mActivity)); assertEquals(i + 1, tabWidget.getTabCount()); } } @UiThreadTest public void testTabViews() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); // We have one tab added in onCreate() of our activity. We "reach" into the default tab // indicator layout in the same way we do in TabHost_TabSpecTest tests. TextView tab0 = (TextView) tabWidget.getChildTabViewAt(0).findViewById(android.R.id.title); assertNotNull(tab0); assertEquals(TabHostCtsActivity.INITIAL_TAB_LABEL, tab0.getText()); for (int i = 1; i < 10; i++) { TextView toAdd = new TextView(mActivity); toAdd.setText("Tab #" + i); tabWidget.addView(toAdd); assertEquals(toAdd, tabWidget.getChildTabViewAt(i)); } } public void testChildDrawableStateChanged() { MockTabWidget mockTabWidget = new MockTabWidget(mActivity); TextView tv0 = new TextView(mActivity); TextView tv1 = new TextView(mActivity); mockTabWidget.addView(tv0); mockTabWidget.addView(tv1); mockTabWidget.setCurrentTab(1); mockTabWidget.reset(); mockTabWidget.childDrawableStateChanged(tv0); assertFalse(mockTabWidget.hasCalledInvalidate()); mockTabWidget.reset(); mockTabWidget.childDrawableStateChanged(tv1); assertTrue(mockTabWidget.hasCalledInvalidate()); mockTabWidget.reset(); mockTabWidget.childDrawableStateChanged(null); assertFalse(mockTabWidget.hasCalledInvalidate()); } public void testDispatchDraw() { // implementation details } @UiThreadTest public void testSetCurrentTab() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); tabWidget.addView(new TextView(mActivity)); assertTrue(tabWidget.getChildAt(0).isSelected()); assertFalse(tabWidget.getChildAt(1).isSelected()); assertTrue(tabWidget.getChildAt(0).isFocused()); assertFalse(tabWidget.getChildAt(1).isFocused()); tabWidget.setCurrentTab(1); assertFalse(tabWidget.getChildAt(0).isSelected()); assertTrue(tabWidget.getChildAt(1).isSelected()); assertTrue(tabWidget.getChildAt(0).isFocused()); assertFalse(tabWidget.getChildAt(1).isFocused()); } @UiThreadTest public void testFocusCurrentTab() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); tabWidget.addView(new TextView(mActivity)); assertTrue(tabWidget.getChildAt(0).isSelected()); assertFalse(tabWidget.getChildAt(1).isSelected()); assertEquals(tabWidget.getChildAt(0), tabWidget.getFocusedChild()); assertTrue(tabWidget.getChildAt(0).isFocused()); assertFalse(tabWidget.getChildAt(1).isFocused()); // normal tabWidget.focusCurrentTab(1); assertFalse(tabWidget.getChildAt(0).isSelected()); assertTrue(tabWidget.getChildAt(1).isSelected()); assertEquals(tabWidget.getChildAt(1), tabWidget.getFocusedChild()); assertFalse(tabWidget.getChildAt(0).isFocused()); assertTrue(tabWidget.getChildAt(1).isFocused()); tabWidget.focusCurrentTab(0); assertTrue(tabWidget.getChildAt(0).isSelected()); assertFalse(tabWidget.getChildAt(1).isSelected()); assertEquals(tabWidget.getChildAt(0), tabWidget.getFocusedChild()); assertTrue(tabWidget.getChildAt(0).isFocused()); assertFalse(tabWidget.getChildAt(1).isFocused()); // exceptional try { tabWidget.focusCurrentTab(-1); fail("Should throw NullPointerException"); } catch (NullPointerException e) { // expected exception } try { tabWidget.focusCurrentTab(tabWidget.getChildCount() + 1); fail("Should throw NullPointerException"); } catch (NullPointerException e) { // expected exception } } @UiThreadTest public void testSetEnabled() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); tabWidget.addView(new TextView(mActivity)); tabWidget.addView(new TextView(mActivity)); assertTrue(tabWidget.isEnabled()); assertTrue(tabWidget.getChildAt(0).isEnabled()); assertTrue(tabWidget.getChildAt(1).isEnabled()); tabWidget.setEnabled(false); assertFalse(tabWidget.isEnabled()); assertFalse(tabWidget.getChildAt(0).isEnabled()); assertFalse(tabWidget.getChildAt(1).isEnabled()); tabWidget.setEnabled(true); assertTrue(tabWidget.isEnabled()); assertTrue(tabWidget.getChildAt(0).isEnabled()); assertTrue(tabWidget.getChildAt(1).isEnabled()); } public void testAddView() { MockTabWidget mockTabWidget = new MockTabWidget(mActivity); // normal value View view1 = new TextView(mActivity); mockTabWidget.addView(view1); assertSame(view1, mockTabWidget.getChildAt(0)); LayoutParams defaultLayoutParam = mockTabWidget.generateDefaultLayoutParams(); if (mockTabWidget.getOrientation() == LinearLayout.VERTICAL) { assertEquals(defaultLayoutParam.height, LayoutParams.WRAP_CONTENT); assertEquals(defaultLayoutParam.width, LayoutParams.MATCH_PARENT); } else if (mockTabWidget.getOrientation() == LinearLayout.HORIZONTAL) { assertEquals(defaultLayoutParam.height, LayoutParams.WRAP_CONTENT); assertEquals(defaultLayoutParam.width, LayoutParams.WRAP_CONTENT); } else { assertNull(defaultLayoutParam); } View view2 = new RelativeLayout(mActivity); mockTabWidget.addView(view2); assertSame(view2, mockTabWidget.getChildAt(1)); try { mockTabWidget.addView(new ListView(mActivity)); fail("did not throw RuntimeException when adding invalid view"); } catch (RuntimeException e) { // issue 1695243 } try { mockTabWidget.addView(null); fail("did not throw NullPointerException when child is null"); } catch (NullPointerException e) { // issue 1695243 } } @UiThreadTest public void testStripEnabled() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); tabWidget.setStripEnabled(true); assertTrue(tabWidget.isStripEnabled()); tabWidget.setStripEnabled(false); assertFalse(tabWidget.isStripEnabled()); } @UiThreadTest public void testStripDrawables() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); // Test setting left strip drawable tabWidget.setLeftStripDrawable(R.drawable.icon_green); Drawable leftStripDrawable = tabWidget.getLeftStripDrawable(); assertNotNull(leftStripDrawable); TestUtils.assertAllPixelsOfColor("Left strip green", leftStripDrawable, leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(), true, 0xFF00FF00, 1, false); tabWidget.setLeftStripDrawable(activity.getResources().getDrawable( R.drawable.icon_red, null)); leftStripDrawable = tabWidget.getLeftStripDrawable(); assertNotNull(leftStripDrawable); TestUtils.assertAllPixelsOfColor("Left strip red", leftStripDrawable, leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(), true, 0xFFFF0000, 1, false); // Test setting right strip drawable tabWidget.setRightStripDrawable(R.drawable.icon_red); Drawable rightStripDrawable = tabWidget.getRightStripDrawable(); assertNotNull(rightStripDrawable); TestUtils.assertAllPixelsOfColor("Right strip red", rightStripDrawable, rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(), true, 0xFFFF0000, 1, false); tabWidget.setRightStripDrawable(activity.getResources().getDrawable( R.drawable.icon_green, null)); rightStripDrawable = tabWidget.getRightStripDrawable(); assertNotNull(rightStripDrawable); TestUtils.assertAllPixelsOfColor("Left strip green", rightStripDrawable, rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(), true, 0xFF00FF00, 1, false); } @UiThreadTest public void testDividerDrawables() { TabHostCtsActivity activity = getActivity(); TabWidget tabWidget = activity.getTabWidget(); tabWidget.setDividerDrawable(R.drawable.icon_blue); Drawable dividerDrawable = tabWidget.getDividerDrawable(); assertNotNull(dividerDrawable); TestUtils.assertAllPixelsOfColor("Divider blue", dividerDrawable, dividerDrawable.getIntrinsicWidth(), dividerDrawable.getIntrinsicHeight(), true, 0xFF0000FF, 1, false); tabWidget.setDividerDrawable(activity.getResources().getDrawable( R.drawable.icon_yellow, null)); dividerDrawable = tabWidget.getDividerDrawable(); assertNotNull(dividerDrawable); TestUtils.assertAllPixelsOfColor("Divider yellow", dividerDrawable, dividerDrawable.getIntrinsicWidth(), dividerDrawable.getIntrinsicHeight(), true, 0xFFFFFF00, 1, false); } public void testOnFocusChange() { // onFocusChange() is implementation details, do NOT test } public void testOnSizeChanged() { // implementation details } /* * Mock class for TabWidget to be used in test cases. */ private class MockTabWidget extends TabWidget { private boolean mCalledInvalidate = false; public MockTabWidget(Context context) { super(context); } @Override protected LayoutParams generateDefaultLayoutParams() { return super.generateDefaultLayoutParams(); } @Override public void invalidate() { super.invalidate(); mCalledInvalidate = true; } public boolean hasCalledInvalidate() { return mCalledInvalidate; } public void reset() { mCalledInvalidate = false; } } }
gpl-3.0
davenpcj5542009/eucalyptus
clc/modules/msgs/src/main/java/com/eucalyptus/auth/principal/Principals.java
48701
/************************************************************************* * Copyright 2009-2014 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, * with or without modification, are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE * THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL, * COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE, * AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, * SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, * WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, * REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO * IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT * NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS. ************************************************************************/ package com.eucalyptus.auth.principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import com.eucalyptus.auth.Accounts; import com.eucalyptus.auth.AuthException; import com.eucalyptus.auth.PolicyParseException; import com.eucalyptus.auth.ServerCertificate; import com.eucalyptus.component.auth.SystemCredentials; import com.eucalyptus.component.id.Eucalyptus; import com.eucalyptus.crypto.util.B64; import com.eucalyptus.crypto.util.PEMFiles; import com.eucalyptus.util.OwnerFullName; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; public class Principals { private static final String SYSTEM_ID = Account.SYSTEM_ACCOUNT; private static final String NOBODY_ID = Account.NOBODY_ACCOUNT; private static final User SYSTEM_USER = new User( ) { private final Certificate cert = new Certificate( ) { @Override public Boolean isActive( ) { return true; } @Override public void setActive( Boolean active ) throws AuthException {} @Override public Boolean isRevoked( ) { return false; } @Override public void setRevoked( Boolean revoked ) throws AuthException {} @Override public String getPem( ) { return B64.url.encString( PEMFiles.getBytes( getX509Certificate( ) ) ); } @Override public X509Certificate getX509Certificate( ) { return SystemCredentials.lookup( Eucalyptus.class ).getCertificate( ); } @Override public void setX509Certificate( X509Certificate x509 ) throws AuthException {} @Override public Date getCreateDate( ) { return SystemCredentials.lookup( Eucalyptus.class ).getCertificate( ).getNotBefore( ); } @Override public void setCreateDate( Date createDate ) throws AuthException {} @Override public User getUser( ) throws AuthException { return Principals.systemUser( ); } @Override public String getCertificateId( ) { return SYSTEM_ID; } }; private final List<Certificate> certs = new ArrayList<Certificate>( ) { { add( cert ); } }; @Override public String getUserId( ) { return Account.SYSTEM_ACCOUNT; } @Override public String getName( ) { return Account.SYSTEM_ACCOUNT; } @Override public String getPath( ) { return "/"; } @Override public Date getCreateDate( ) { return null; } @Override public User.RegistrationStatus getRegistrationStatus( ) { return null; } @Override public Boolean isEnabled( ) { return true; } @Override public String getToken( ) { return null; } @Override public String getConfirmationCode( ) { return null; } @Override public String getPassword( ) { return null; } @Override public Long getPasswordExpires( ) { return null; } @Override public String getInfo( String key ) throws AuthException { return null; } @Override public Map<String, String> getInfo( ) throws AuthException { return null; } @Override public List<AccessKey> getKeys( ) throws AuthException { return null; } @Override public AccessKey getKey( String keyId ) throws AuthException { return null; } @Override public AccessKey createKey( ) throws AuthException { return null; } @Override public List<Certificate> getCertificates( ) throws AuthException { return certs; } @Override public Certificate getCertificate( String certificateId ) throws AuthException { return cert; } @Override public Certificate addCertificate( X509Certificate certificate ) throws AuthException { return cert; } @Override public List<Group> getGroups( ) throws AuthException { return Lists.newArrayList( ); } @Override public String getAccountNumber() throws AuthException { return getAccount().getAccountNumber(); } @Override public Account getAccount( ) throws AuthException { return systemAccount( ); } @Override public boolean isSystemAdmin( ) { return true; } @Override public boolean isSystemUser( ) { return true; } @Override public boolean isAccountAdmin( ) { return true; } @Override public List<Policy> getPolicies( ) throws AuthException { return Lists.newArrayList( ); } @Override public Policy addPolicy( String name, String policy ) throws AuthException, PolicyParseException { return null; } @Override public Policy putPolicy( final String name, final String policy ) throws AuthException, PolicyParseException { return null; } @Override public List<Authorization> lookupAuthorizations( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public List<Authorization> lookupQuotas( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public void setName( String name ) throws AuthException {} @Override public void setPath( String path ) throws AuthException {} @Override public void setRegistrationStatus( User.RegistrationStatus stat ) throws AuthException {} @Override public void setEnabled( Boolean enabled ) throws AuthException {} @Override public void setToken( String token ) throws AuthException {} @Override public String resetToken( ) throws AuthException { return null; } @Override public void setConfirmationCode( String code ) throws AuthException {} @Override public void createConfirmationCode( ) throws AuthException {} @Override public void setPassword( String password ) throws AuthException {} @Override public void setPasswordExpires( Long time ) throws AuthException {} @Override public void setInfo( String key, String value ) throws AuthException {} @Override public void setInfo( Map<String, String> newInfo ) throws AuthException {} @Override public void removeKey( String keyId ) throws AuthException {} @Override public void removeCertificate( String certficateId ) throws AuthException {} @Override public void removePolicy( String name ) throws AuthException {} @Override public void removeInfo(String key) throws AuthException {} }; private static final User NOBODY_USER = new User( ) { private final Certificate cert = new Certificate( ) { @Override public Boolean isActive( ) { return true; } @Override public void setActive( Boolean active ) throws AuthException {} @Override public Boolean isRevoked( ) { return null; } @Override public void setRevoked( Boolean revoked ) throws AuthException {} @Override public String getPem( ) { return B64.url.encString( PEMFiles.getBytes( getX509Certificate( ) ) ); } @Override public X509Certificate getX509Certificate( ) { return SystemCredentials.lookup( Eucalyptus.class ).getCertificate( ); } @Override public void setX509Certificate( X509Certificate x509 ) throws AuthException {} @Override public Date getCreateDate( ) { return null; } @Override public void setCreateDate( Date createDate ) throws AuthException {} @Override public User getUser( ) throws AuthException { return Principals.nobodyUser( ); } @Override public String getCertificateId( ) { return Principals.NOBODY_ID; } }; private final List<Certificate> certs = new ArrayList<Certificate>( ) { { add( cert ); } }; @Override public String getUserId( ) { return Account.NOBODY_ACCOUNT; } @Override public String getName( ) { return Account.NOBODY_ACCOUNT; } @Override public String getPath( ) { return "/"; } @Override public Date getCreateDate( ) { return null; } @Override public User.RegistrationStatus getRegistrationStatus( ) { return null; } @Override public Boolean isEnabled( ) { return true; } @Override public String getToken( ) { return null; } @Override public String getConfirmationCode( ) { return null; } @Override public String getPassword( ) { return null; } @Override public Long getPasswordExpires( ) { return null; } @Override public String getInfo( String key ) throws AuthException { return null; } @Override public Map<String, String> getInfo( ) throws AuthException { return null; } @Override public List<AccessKey> getKeys( ) throws AuthException { return null; } @Override public AccessKey getKey( String keyId ) throws AuthException { return null; } @Override public AccessKey createKey( ) throws AuthException { return null; } @Override public List<Certificate> getCertificates( ) throws AuthException { return certs; } @Override public Certificate getCertificate( String certificateId ) throws AuthException { return cert; } @Override public Certificate addCertificate( X509Certificate certificate ) throws AuthException { return cert; } @Override public List<Group> getGroups( ) throws AuthException { return Lists.newArrayList( ); } @Override public String getAccountNumber() throws AuthException { return getAccount().getAccountNumber(); } @Override public Account getAccount( ) throws AuthException { return NOBODY_ACCOUNT; } @Override public boolean isSystemAdmin( ) { return false; } @Override public boolean isSystemUser( ) { return false; } @Override public boolean isAccountAdmin( ) { return false; } @Override public List<Policy> getPolicies( ) throws AuthException { return Lists.newArrayList( ); } @Override public Policy addPolicy( String name, String policy ) throws AuthException, PolicyParseException { return null; } @Override public Policy putPolicy( final String name, final String policy ) throws AuthException, PolicyParseException { return null; } @Override public List<Authorization> lookupAuthorizations( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public List<Authorization> lookupQuotas( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public void setName( String name ) throws AuthException {} @Override public void setPath( String path ) throws AuthException {} @Override public void setRegistrationStatus( User.RegistrationStatus stat ) throws AuthException {} @Override public void setEnabled( Boolean enabled ) throws AuthException {} @Override public void setToken( String token ) throws AuthException {} @Override public String resetToken( ) throws AuthException { return null; } @Override public void setConfirmationCode( String code ) throws AuthException {} @Override public void createConfirmationCode( ) throws AuthException {} @Override public void setPassword( String password ) throws AuthException {} @Override public void setPasswordExpires( Long time ) throws AuthException {} @Override public void setInfo( String key, String value ) throws AuthException {} @Override public void setInfo( Map<String, String> newInfo ) throws AuthException {} @Override public void removeKey( String keyId ) throws AuthException {} @Override public void removeCertificate( String certficateId ) throws AuthException {} @Override public void removePolicy( String name ) throws AuthException {} @Override public void removeInfo(String key) throws AuthException {} }; private static final Account NOBODY_ACCOUNT = new SystemAccount( Account.NOBODY_ACCOUNT_ID, Account.NOBODY_ACCOUNT, nobodyUser( ) ); private static final Account SYSTEM_ACCOUNT = new SystemAccount( Account.SYSTEM_ACCOUNT_ID, Account.SYSTEM_ACCOUNT, systemUser( ) ); private static final Set<Account> FAKE_ACCOUNTS = ImmutableSet.of( systemAccount(), nobodyAccount() ); private static final Set<String> FAKE_ACCOUNT_NUMBERS = ImmutableSet.copyOf( Iterables.transform(FAKE_ACCOUNTS, Accounts.toAccountNumber() ) ); private static final Set<User> FAKE_USERS = ImmutableSet.of( systemUser(), nobodyUser() ); private static final Set<String> FAKE_USER_IDS = ImmutableSet.copyOf( Iterables.transform(FAKE_USERS, Accounts.toUserId() ) ); public static User systemUser( ) { return SYSTEM_USER; } public static User nobodyUser( ) { return NOBODY_USER; } public static Account nobodyAccount( ) { return NOBODY_ACCOUNT; } public static Account systemAccount( ) { return SYSTEM_ACCOUNT; } private static final UserFullName SYSTEM_USER_ERN = UserFullName.getInstance( systemUser( ) ); private static final UserFullName NOBODY_USER_ERN = UserFullName.getInstance( nobodyUser( ) ); public static OwnerFullName nobodyFullName( ) { return NOBODY_USER_ERN; } public static OwnerFullName systemFullName( ) { return SYSTEM_USER_ERN; } public static boolean isFakeIdentityAccountNumber( final String id ) { return FAKE_ACCOUNT_NUMBERS.contains( id ); } public static boolean isFakeIdentityUserId( final String id ) { return FAKE_USER_IDS.contains( id ); } public static boolean isFakeIdentify( String id ) { return isFakeIdentityAccountNumber( id ) || isFakeIdentityUserId( id ); } /** * Do the given User objects represent the same user. * * @param user1 The first user to compare * @param user2 The second user to compare * @return True if the given Users represent the same user. */ public static boolean isSameUser( final User user1, final User user2 ) { return user1 != null && user2 != null && !Strings.isNullOrEmpty( user1.getUserId() ) && !Strings.isNullOrEmpty( user2.getUserId() ) && user1.getUserId().equals( user2.getUserId() ); } private static class SystemAccount implements Account { private static final long serialVersionUID = 1L; private final Long accountId; private final String accountName; private final User systemUser; private SystemAccount( final Long accountId, final String accountName, final User systemUser ) { this.accountId = accountId; this.accountName = accountName; this.systemUser = systemUser; } @Override public String getCanonicalId() { return ""; // TODO need to calculate a canonical ID } @Override public String getAccountNumber( ) { return String.format( "%012d", accountId ); } @Override public String getName( ) { return accountName; } @Override public void setName( String name ) throws AuthException {} @Override public String getDisplayName() { return Accounts.getAccountFullName( this ); } @Override public OwnerFullName getOwner() { return AccountFullName.getInstance( this ); } @Override public List<User> getUsers( ) throws AuthException { return Lists.newArrayList( systemUser ); } @Override public List<Group> getGroups( ) throws AuthException { return Lists.newArrayList( ); } @Override public List<Role> getRoles( ) throws AuthException { return Lists.newArrayList( ); } @Override public List<InstanceProfile> getInstanceProfiles() throws AuthException { return Lists.newArrayList( ); } @Override public InstanceProfile addInstanceProfile( final String instanceProfileName, final String path ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public void deleteInstanceProfile( final String instanceProfileName ) throws AuthException { } @Override public InstanceProfile lookupInstanceProfileByName( final String instanceProfileName ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public User addUser( String userName, String path, boolean enabled, Map<String, String> info ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public void deleteUser( String userName, boolean forceDeleteAdmin, boolean recursive ) throws AuthException {} @Override public Role addRole( String roleName, String path, String assumeRolePolicy ) throws AuthException, PolicyParseException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public void deleteRole( String roleName ) throws AuthException {} @Override public Group addGroup( String groupName, String path ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public void deleteGroup( String groupName, boolean recursive ) throws AuthException {} @Override public Group lookupGroupByName( String groupName ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public Role lookupRoleByName( String roleName ) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public User lookupUserByName( String userName ) throws AuthException { if ( systemUser.getName().equals( userName ) ) { return systemUser; } else { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } } @Override public User lookupAdmin() throws AuthException { return systemUser; } @Override public List<Authorization> lookupAccountGlobalAuthorizations( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public List<Authorization> lookupAccountGlobalQuotas( String resourceType ) throws AuthException { return Lists.newArrayList( ); } @Override public ServerCertificate addServerCertificate(String certName, String certBody, String certChain, String path, String pk) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public ServerCertificate deleteServerCertificate(String certName) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public ServerCertificate lookupServerCertificate(String certName) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public List<ServerCertificate> listServerCertificates(String pathPrefix) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } @Override public void updateServerCeritificate(String certName, String newCertName, String newPath) throws AuthException { throw new AuthException( AuthException.SYSTEM_MODIFICATION ); } } }
gpl-3.0
staircase27/Tower-Defence
TDlib/src/com/staircase27/TD/lib/Towers/impls/areaTowers/CollectTower.java
1233
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.staircase27.TD.lib.Towers.impls.areaTowers; import com.staircase27.TD.lib.Enemies.BaseEnemy; import com.staircase27.TD.lib.Towers.AreaTowerInterface; import com.staircase27.TD.lib.Towers.BaseAttackTower; import com.staircase27.TD.lib.Towers.BaseTower; import com.staircase27.TD.lib.lib.Pair; import java.util.Set; /** * * @author Simon Armstrong */ public class CollectTower extends BaseTower implements AreaTowerInterface{ @Override public Pair<Class<? extends BaseTower>> getUpgrades() { return null; } @Override public double getRange() { return 1; } @Override public void enterArea(BaseEnemy enemy) { } @Override public void leaveArea(BaseEnemy enemy) { } @Override public void activateTower(Set<BaseEnemy> enemies, Set<BaseAttackTower> towers) { for(BaseAttackTower tower:towers){ //TODO: collect } } @Override public void disactivateTower(Set<BaseEnemy> enemies, Set<BaseAttackTower> towers) { for(BaseAttackTower tower:towers){ //TODO: collect } } }
gpl-3.0
geosphere/snoopsnitch
SnoopSnitch/src/de/srlabs/snoopsnitch/util/MSDServiceHelperCreator.java
7574
package de.srlabs.snoopsnitch.util; import java.util.Vector; import android.app.Activity; import android.content.Context; import de.srlabs.snoopsnitch.BaseActivity; import de.srlabs.snoopsnitch.analysis.Event; import de.srlabs.snoopsnitch.qdmon.MsdServiceCallback; import de.srlabs.snoopsnitch.qdmon.MsdServiceHelper; import de.srlabs.snoopsnitch.qdmon.StateChangedReason; public class MSDServiceHelperCreator implements MsdServiceCallback { // Attributes private static MSDServiceHelperCreator _instance = null; private MsdServiceHelper msdServiceHelper; private int rectWidth; private Activity currentActivity; private boolean autostartRecordingPending = false; // Methods private MSDServiceHelperCreator (Context context, boolean autostartRecording) { msdServiceHelper = new MsdServiceHelper(context, this, false); this.autostartRecordingPending = autostartRecording; } public static MSDServiceHelperCreator getInstance (Context context, boolean autostartRecording) { if (_instance == null) { _instance = new MSDServiceHelperCreator (context, autostartRecording); } return _instance; } public static MSDServiceHelperCreator getInstance () { return _instance; } public void destroy () { _instance = null; } public MsdServiceHelper getMsdServiceHelper () { return msdServiceHelper; } public int getThreatsSmsMonthSum () { return msdServiceHelper.getData().getEvent(TimeSpace.getTimeSpaceMonth().getStartTime(), TimeSpace.getTimeSpaceMonth().getEndTime()).size(); } public int[] getThreatsSmsMonth () { int[] smsMonth = new int[4]; long calStart = TimeSpace.getTimeSpaceMonth().getStartTime(); long calEnd = TimeSpace.getTimeSpaceMonth().getEndTime(); long timeSpan = (calEnd - calStart) / 4; for (int i=0; i<smsMonth.length; i++) { smsMonth[i] = msdServiceHelper.getData().getEvent(calEnd - timeSpan, calEnd).size(); calEnd -= timeSpan; } return smsMonth; } public int getThreatsSmsWeekSum () { return msdServiceHelper.getData().getEvent(TimeSpace.getTimeSpaceWeek().getStartTime(), TimeSpace.getTimeSpaceWeek().getEndTime()).size(); } public int[] getThreatsSmsWeek () { int[] smsWeek = new int[7]; long calEnd = TimeSpace.getTimeSpaceWeek().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceWeek().getEndTime() - TimeSpace.getTimeSpaceWeek().getStartTime()) / 7; for (int i=0; i<smsWeek.length; i++) { smsWeek[i] = msdServiceHelper.getData().getEvent(calEnd - timeSpan, calEnd).size(); calEnd = (calEnd - timeSpan); } return smsWeek; } public int[] getThreatsSmsDay () { int[] smsDay = new int[6]; long calEnd = TimeSpace.getTimeSpaceDay().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceDay().getEndTime() - TimeSpace.getTimeSpaceDay().getStartTime()) / 6; for (int i=0; i<smsDay.length; i++) { smsDay[i] = msdServiceHelper.getData().getEvent(calEnd - timeSpan, calEnd).size(); calEnd = (calEnd - timeSpan); } return smsDay; } public int getThreatsSmsDaySum () { return msdServiceHelper.getData().getEvent(TimeSpace.getTimeSpaceDay().getStartTime(), TimeSpace.getTimeSpaceDay().getEndTime()).size(); } public int[] getThreatsSmsHour () { int[] smsHour = new int[12]; long calEnd = TimeSpace.getTimeSpaceHour().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceHour().getEndTime() - TimeSpace.getTimeSpaceHour().getStartTime()) / 12; for (int i=0; i<smsHour.length; i++) { smsHour[i] = msdServiceHelper.getData().getEvent(calEnd - timeSpan, calEnd).size(); calEnd -= timeSpan; } return smsHour; } public int getThreatsSmsHourSum () { return msdServiceHelper.getData().getEvent(TimeSpace.getTimeSpaceHour().getStartTime(), TimeSpace.getTimeSpaceHour().getEndTime()).size(); } public int getThreatsImsiMonthSum () { return msdServiceHelper.getData().getImsiCatchers(TimeSpace.getTimeSpaceMonth().getStartTime(), TimeSpace.getTimeSpaceMonth().getEndTime()).size(); } public int[] getThreatsImsiMonth () { int[] imsiMonth = new int[4]; long calEnd = TimeSpace.getTimeSpaceMonth().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceMonth().getEndTime() - TimeSpace.getTimeSpaceMonth().getStartTime()) / 4; for (int i=0; i<imsiMonth.length; i++) { imsiMonth[i] = msdServiceHelper.getData().getImsiCatchers(calEnd - timeSpan, calEnd).size(); calEnd -= timeSpan; } return imsiMonth; } public int getThreatsImsiWeekSum () { return msdServiceHelper.getData().getImsiCatchers(TimeSpace.getTimeSpaceWeek().getStartTime(), TimeSpace.getTimeSpaceWeek().getEndTime()).size(); } public int[] getThreatsImsiWeek () { int[] imsiWeek = new int[7]; long calEnd = TimeSpace.getTimeSpaceWeek().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceWeek().getEndTime() - TimeSpace.getTimeSpaceWeek().getStartTime()) / 7; for (int i=0; i<imsiWeek.length; i++) { imsiWeek[i] = msdServiceHelper.getData().getImsiCatchers(calEnd - timeSpan, calEnd).size(); calEnd -= timeSpan; } return imsiWeek; } public int[] getThreatsImsiDay () { int[] imsiDay = new int[6]; long calEnd = TimeSpace.getTimeSpaceDay().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceDay().getEndTime() - TimeSpace.getTimeSpaceDay().getStartTime()) / 6; for (int i=0; i<imsiDay.length; i++) { imsiDay[i] = msdServiceHelper.getData().getImsiCatchers(calEnd - timeSpan, calEnd).size(); calEnd = (calEnd - timeSpan); } return imsiDay; } public int getThreatsImsiDaySum () { return msdServiceHelper.getData().getImsiCatchers(TimeSpace.getTimeSpaceDay().getStartTime(), TimeSpace.getTimeSpaceDay().getEndTime()).size(); } public int[] getThreatsImsiHour () { int[] imsiHour = new int[12]; long calEnd = TimeSpace.getTimeSpaceHour().getEndTime(); long timeSpan = (TimeSpace.getTimeSpaceHour().getEndTime() - TimeSpace.getTimeSpaceHour().getStartTime()) / 12; for (int i=0; i<imsiHour.length; i++) { imsiHour[i] = msdServiceHelper.getData().getImsiCatchers(calEnd - timeSpan, calEnd).size(); calEnd = (calEnd - timeSpan); } return imsiHour; } public int getThreatsImsiHourSum () { return msdServiceHelper.getData().getImsiCatchers(TimeSpace.getTimeSpaceHour().getStartTime(), TimeSpace.getTimeSpaceHour().getEndTime()).size(); } public Vector<Event> getEventOfType (Event.Type type, long startTime, long endTime) { Vector<Event> event = msdServiceHelper.getData().getEvent(startTime, endTime); for (Event s : msdServiceHelper.getData().getEvent(startTime, endTime)) { if (type != Event.Type.INVALID_EVENT && !s.getType().equals(type)) { event.remove(s); } } return event; } public void setRectWidth (int rectWidth) { this.rectWidth = rectWidth; } public int getRectWidth () { return rectWidth; } public void setCurrentActivity (Activity activity) { this.currentActivity = activity; } @Override public void stateChanged(StateChangedReason reason) { if(autostartRecordingPending && msdServiceHelper.isConnected()){ if(!msdServiceHelper.isRecording()) msdServiceHelper.startRecording(); autostartRecordingPending = false; } try { ((BaseActivity) currentActivity).stateChanged(reason); } catch (Exception e) { // TODO: Log output... } } @Override public void internalError(String msg) { if (currentActivity instanceof BaseActivity) { ((BaseActivity) currentActivity).internalError(msg); } } }
gpl-3.0
emrah-it/Softuni
Level 1/Java Basics/Java Collections Basics/Java Collections Basics/src/Homework/_5_CountAllWords.java
648
//Problem 5. Count All Words //Write a program to count the number of words in given sentence. //Use any non-letter character as word separator. package Homework; import java.util.Scanner; public class _5_CountAllWords { public static void main(String[] args) { System.out.println("Please enter text"); Scanner input = new Scanner(System.in); String[] allWordStrings = input.nextLine().split("[,|\\\\.|)|(|!|?|&|/|=|:|+|\'|\"|<|>|\\|;|@|#|$|%|^|*|\\s]"); int counter = 0; for (int i = 0; i < allWordStrings.length; i++) { if(!allWordStrings[i].equals("")){ counter++; } } System.out.println(counter); } }
gpl-3.0
LibertACAO/libertacao-android
app/src/main/java/com/libertacao/libertacao/view/contact/ContactFragment.java
3547
package com.libertacao.libertacao.view.contact; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import com.libertacao.libertacao.R; import com.libertacao.libertacao.util.Validator; import com.libertacao.libertacao.util.ViewUtils; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.SaveCallback; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; public class ContactFragment extends Fragment { @InjectView(R.id.contact_email_edit_text) EditText emailEditText; @InjectView(R.id.contact_message_edit_text) EditText messageEditText; public ContactFragment() { // Required empty public constructor } public static ContactFragment newInstance() { return new ContactFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_contact, container, false); ButterKnife.inject(this, layout); return layout; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.send_contact_menu, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_send_contact: sendMessage(); return true; } return super.onOptionsItemSelected(item); } /** * Validate fields from Form * @return if all required fields are present and all fields contain valid values */ private boolean validate() { boolean ret; ret = Validator.validate(messageEditText, true); return ret; } @OnClick(R.id.send_message_button) public void sendMessage() { if(!validate()) { return; } final ProgressDialog pd = ViewUtils.showProgressDialog(getContext(), getString(R.string.savingMessage), false); ParseObject contact = new ParseObject("Contact"); if(!TextUtils.isEmpty(emailEditText.getText().toString())) { contact.put("email", emailEditText.getText().toString()); } contact.put("message", messageEditText.getText().toString()); contact.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { ViewUtils.hideProgressDialog(pd); Context context = ContactFragment.this.getContext(); if (e != null) { Toast.makeText(context, context.getString(R.string.messageSavedError), Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, context.getString(R.string.messageSavedSuccessfully), Toast.LENGTH_LONG).show(); emailEditText.setText(""); messageEditText.setText(""); } } }); } }
gpl-3.0
apruden/opal
opal-core-api/src/main/java/org/obiba/opal/core/security/DomainPermissionConverter.java
1926
/******************************************************************************* * Copyright (c) 2012 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.core.security; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Convert a opal domain permission as a set of magma domain permissions. */ public abstract class DomainPermissionConverter implements SubjectPermissionConverter { private final String domain; protected DomainPermissionConverter(String domain) { this.domain = domain; } @Override public boolean canConvert(String dmn, String permission) { return !(dmn == null || !dmn.equals(domain) || permission == null) && hasPermission(permission); } protected abstract boolean hasPermission(String permission); protected static String toRest(String magmaNode, String permission, String... args) { String node = magmaNode; if(args != null) { for(int i = 0; i < args.length; i++) { node = node.replace("{" + i + "}", args[i]); } } return "rest:" + node + ":" + permission; } protected static String[] args(String node, String patternStr) { // Compile and use regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(node); String[] args; if(matcher.find()) { args = new String[matcher.groupCount()]; // Get all groups for this match for(int i = 1; i <= matcher.groupCount(); i++) { args[i - 1] = matcher.group(i); } } else { args = new String[0]; } return args; } }
gpl-3.0
weiguang/JamJavaUtil
src/main/java/com/okayjam/util/DownloadFileUtil2.java
4258
package com.okayjam.util; import com.okayjam.net.okhttp.OKHttpUtil; import okhttp3.Call; import okhttp3.Response; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author Chen weiguang chen2621978@gmail.com * @date 2020/03/10 20:18 **/ public class DownloadFileUtil2 { private static final Logger LOGGER = LoggerFactory.getLogger(DownloadFileUtil2.class); public static String download(String downloadUrl, String requestMethod, String params, String path) throws IOException { return download(downloadUrl, requestMethod, params, null, path); } /** * eg. DownloadFileUtil.download(url, "POST", params, "d:\1\"); * @param downloadUrl 下载地址 * @param requestMethod 请求方式。 POST 或者 GET * @param params 如果是POST,还有请求参数,json格式 * @param headers header参数,json格式 * @param path 保存文件的目录(是目录,文件名会根据返回流得到) * @return 返回最终文件保存的路径 * @throws IOException IO异常 */ public static String download(String downloadUrl, String requestMethod, String params, String headers, String path) throws IOException { Call conn = OKHttpUtil.getConnection(downloadUrl, requestMethod, params, headers); Response response = conn.execute(); int responseCode = response.code(); if(responseCode != HttpURLConnection.HTTP_OK){ LOGGER.error("【下载导出文件】请求响应错误!返回状态码:{} ,错误信息:{}, {} ", responseCode, response.message() , response.body() != null ? response.body().string() : null); return null; } // 获取文件名 String field = response.header("Content-Disposition"); String fileName ; if (field != null) { fileName = URLDecoder.decode(field, String.valueOf(StandardCharsets.UTF_8)); fileName = fileName.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1"); } else { fileName = conn.request().url().url().getHost() + "-" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()); String extension = FilenameUtils.getExtension(conn.request().url().url().getPath()); if (extension != null) { fileName += "." + extension; } } // 读取输入流并保存 InputStream inStream = new BufferedInputStream(response.body().byteStream()); String fullPath = path + "/" + fileName; saveToFile(inStream, fullPath); response.close(); return fullPath; } /** * 保存文件 * @param inStream 流 * @param path 保存文件的路径 * @throws IOException IO */ public static void saveToFile(InputStream inStream, String path) throws IOException { FileOutputStream fs = new FileOutputStream(path); // 下载网络文件 int byteread ; byte[] buffer = new byte[4096]; while ((byteread = inStream.read(buffer)) != -1) { fs.write(buffer, 0, byteread); } fs.close(); } /** * 获取错误信息 * @param conn 链接 * @return 错误信息 */ private static String getErrorInfo(HttpURLConnection conn) { InputStream is = new BufferedInputStream( conn.getErrorStream()); BufferedReader br ; String result = null; try { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } catch (Exception e) { LOGGER.error("[下载文件]获取错误信息异常"); } return result; } }
gpl-3.0
irq0/jext2
src/jext2/DirectoryInode.java
16507
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 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 jext2. If not, see <http://www.gnu.org/licenses/>. */ package jext2; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; import jext2.annotations.NotThreadSafe; import jext2.exceptions.DirectoryNotEmpty; import jext2.exceptions.FileExists; import jext2.exceptions.FileNameTooLong; import jext2.exceptions.FileTooLarge; import jext2.exceptions.IoError; import jext2.exceptions.JExt2Exception; import jext2.exceptions.NoSpaceLeftOnDevice; import jext2.exceptions.NoSuchFileOrDirectory; import jext2.exceptions.TooManyLinks; /** Inode for directories */ public class DirectoryInode extends DataInode { private static BlockAccess blocks = BlockAccess.getInstance(); private static Superblock superblock = Superblock.getInstance(); public DirectoryEntryAccess directoryEntries = DirectoryEntryAccess.createForDirectoy(this); private ReentrantReadWriteLock directoryLock = new JextReentrantReadWriteLock(true); /** * Lock to use when iterating a directory with {@link #iterateDirectory()} */ public ReentrantReadWriteLock directoryLock() { return directoryLock; } /** * Get the directory iterator. Please note: A directory entry * is everything found that fits the datastructure. Though "fill" entries * are allways included. You may want do do a #DirectoryEntry.isUnused * to check that. * * While using the DirectoryIterator you must hold the lock provided * by {@link #lockForIterateDirectory()} * @returns Directory iterator for this inode */ @NotThreadSafe(useLock=true) public DirectoryIterator iterateDirectory() { return new DirectoryIterator(); } /** * Iterate directory entries. */ public class DirectoryIterator implements Iterator<DirectoryEntry>, Iterable<DirectoryEntry> { private ByteBuffer block; private long blockNr; private DirectoryEntry entry; private DirectoryEntry previousEntry; private int offset = 0; private Iterator<Long> blockIter; DirectoryIterator() { /* Note that I don't lock the hierarchyLock here. Changes to the blocks * of a directory are usually made using the functions in DirectoryInode. * This functions use the directoryLock which implies no changes to the * blocks happen here. */ blockIter = accessData().iterateBlocks(); this.previousEntry = null; this.entry = fetchFirstEntry(); } private void loadNextBlock() { try { blockNr = blockIter.next(); block = blocks.read(blockNr); offset = 0; } catch (IoError ignored) { } } private DirectoryEntry readNextEntry() { assert block != null; assert offset <= superblock.getBlocksize(); assert blockNr >= superblock.getFirstDataBlock() && blockNr <= superblock.getBlocksCount(); try { DirectoryEntry entry = DirectoryEntry.fromByteBuffer(block, blockNr, offset); return directoryEntries.retainAdd(entry); } catch (IoError ignored) { return null; } } private DirectoryEntry fetchFirstEntry() { assert previousEntry == null; if (!blockIter.hasNext()) { Logger log = Filesystem.getLogger(); log.severe("DirectoryInode whithout data blocks - Filesystem probably damaged!"); return null; } loadNextBlock(); return readNextEntry(); } private DirectoryEntry fetchNextEntry(DirectoryEntry last) { assert last != null; if (last.getRecLen() != 0) { offset += last.getRecLen(); } // entry was last in this block, load next block if (offset >= superblock.getBlocksize()) { if (blockIter.hasNext()) { loadNextBlock(); } else { return null; } } // fetch next entry from block return readNextEntry(); } @Override public boolean hasNext() { return (entry != null); } @Override public DirectoryEntry next() { DirectoryEntry releaseMe = this.previousEntry; this.previousEntry = this.entry; this.entry = fetchNextEntry(previousEntry); if (releaseMe != null) { assert !releaseMe.equals(this.previousEntry); assert !(releaseMe == this.previousEntry); directoryEntries.release(releaseMe); } if (! directoryEntries.hasEntry(this.previousEntry)) directoryEntries.retainAdd(previousEntry); return this.previousEntry; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<DirectoryEntry> iterator() { return this; } } /** * Add directory entry for given inode and name. * @throws NoSpaceLeftOnDevice * @throws FileNameTooLong * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws TooManyLinks When adding a link would cause nlinks to hit the limit. * Checkt is performed before any allocation. * @see addLink(DirectoryEntry newEntry) */ public void addLink(Inode inode, String name) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileNameTooLong, TooManyLinks, FileTooLarge { if (inode.getLinksCount() >= Constants.EXT2_LINK_MAX) throw new TooManyLinks(); DirectoryEntry newDir = DirectoryEntry.create(name); newDir.setIno(inode.getIno()); newDir.setFileType(inode.getFileType()); assert !directoryEntries.hasEntry(newDir); directoryEntries.add(newDir); directoryEntries.retain(newDir); addDirectoryEntry(newDir); inode.setLinksCount(inode.getLinksCount() + 1); directoryEntries.release(newDir); } /** * Add directory entry. Iterate over data blocks and check for entries with * the same name on the way. This function does the heavy lifting compared to #addLink(Inode, String) * and should never be used directly. * @throws NoSpaceLeftOnDevice * @throws FileTooLarge Allocating a new block would hit the max. block count * @throws FileExistsException When we stumble upon an entry with same name */ // TODO rewrite addLink to use the directory iterator public void addDirectoryEntry(DirectoryEntry newEntry) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, FileTooLarge { ByteBuffer block; int offset = 0; directoryEntries.retain(newEntry); // Using a write lock for the whole process is a bit much but easy.. directoryLock.writeLock().lock(); for (long blockNr : accessData().iterateBlocks()) { block = blocks.read(blockNr); while (offset + 8 <= block.limit()) { /* space for minimum of one entry */ DirectoryEntry currentEntry = DirectoryEntry.fromByteBuffer(block, blockNr, offset); directoryEntries.add(currentEntry); directoryEntries.retain(currentEntry); if (currentEntry.getName().equals(newEntry.getName())) throw new FileExists(); if (currentEntry.getRecLen() == 0 || currentEntry.getRecLen() > superblock.getBlocksize()) { throw new RuntimeException ("zero-length or bigger-than-blocksize directory entry" + "entry: " + currentEntry); } /* * See if current directory entry is unused; if so: * assimilate! */ if (currentEntry.isUnused() && currentEntry.getRecLen() >= newEntry.getRecLen()) { newEntry.setRecLen(currentEntry.getRecLen()); blocks.writePartial(blockNr, offset, newEntry.toByteBuffer()); setModificationTime(new Date()); // should be handeld by block layer setStatusChangeTime(new Date()); directoryEntries.release(currentEntry); directoryEntries.release(newEntry); directoryLock.writeLock().unlock(); return; } /* * If entry is used, see if we can split the directory entry * to make room for the new one */ if (currentEntry.getRecLen() >= newEntry.getRecLen() + DirectoryEntry.minSizeNeeded(currentEntry.getNameLen())) { int spaceFreed = currentEntry.getRecLen() - DirectoryEntry.minSizeNeeded(currentEntry.getNameLen()); /* truncate the old one */ currentEntry.truncateRecord(); blocks.writePartial(blockNr, offset, currentEntry.toByteBuffer()); offset += currentEntry.getRecLen(); /* fill in the new one */ newEntry.setRecLen(spaceFreed); blocks.writePartial(blockNr, offset, newEntry.toByteBuffer()); setModificationTime(new Date()); setStatusChangeTime(new Date()); directoryEntries.release(currentEntry); directoryEntries.release(newEntry); directoryLock.writeLock().unlock(); return; } directoryEntries.release(currentEntry); offset += currentEntry.getRecLen(); } offset = 0; } /* We checked every block but didn't find any free space. * Allocate next block add two entries: * (1) the new one * (2) the dummy "rest" entry */ LinkedList<Long> allocBlocks = accessData().getBlocksAllocate(getBlocks()/(superblock.getBlocksize()/512), 1); if (allocBlocks.size() == 0) throw new IoError(); long blockNr = allocBlocks.getFirst(); blocks.writePartial(blockNr, 0, newEntry.toByteBuffer()); DirectoryEntry rest = DirectoryEntry.createRestDummy(newEntry); blocks.writePartial(blockNr, newEntry.getRecLen(), rest.toByteBuffer()); setSize(getSize() + superblock.getBlocksize()); setStatusChangeTime(new Date()); directoryEntries.release(newEntry); accessData().unlockHierarchyChanges(); directoryLock.writeLock().unlock(); } public boolean isEmptyDirectory() { int count = 0; directoryLock.readLock().lock(); for (@SuppressWarnings("unused") DirectoryEntry dir : iterateDirectory()) { count += 1; if (count >= 3) { directoryLock.readLock().unlock(); return false; } } directoryLock.readLock().unlock(); return true; } /** * Lookup name in directory. This is done by iterating each entry and * comparing the names. * * @return DirectoryEntry or null in case its not found * @throws NoSuchFileOrDirectory * @throws FileNameTooLong */ public DirectoryEntry lookup(String name) throws NoSuchFileOrDirectory, FileNameTooLong { if (Ext2fsDataTypes.getStringByteLength(name) > DirectoryEntry.MAX_NAME_LEN) throw new FileNameTooLong(); directoryLock.readLock().lock(); for (DirectoryEntry dir : iterateDirectory()) { directoryEntries.retain(dir); if (name.equals(dir.getName())) { directoryLock.readLock().unlock(); return dir; } directoryEntries.release(dir); } directoryLock.readLock().unlock(); throw new NoSuchFileOrDirectory(); } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); sb.append(" DIRECTORY=["); directoryLock.readLock().lock(); for (DirectoryEntry dir : iterateDirectory()) { directoryEntries.retain(dir); sb.append(dir.toString()); sb.append("\n"); directoryEntries.release(dir); } directoryLock.readLock().unlock(); sb.append("]"); return sb.toString(); } protected DirectoryInode(long blockNr, int offset) { super(blockNr, offset); } public static DirectoryInode fromByteBuffer(ByteBuffer buf, int offset) throws IoError { DirectoryInode inode = new DirectoryInode(-1, offset); inode.read(buf); return inode; } public void addDotLinks(DirectoryInode parent) throws JExt2Exception, FileExists, NoSpaceLeftOnDevice, TooManyLinks, FileTooLarge { try { addLink(this, "."); addLink(parent, ".."); } catch (FileNameTooLong e) { throw new RuntimeException("should not happen"); } } /** * Remove "." and ".." entry from the directory. Should be called before * a unlink on a directory. * @throws NoSuchFileOrDirectory * @praram parent parent inode. Used to resolve the ".." link */ public void removeDotLinks(DirectoryInode parent) throws IoError, NoSuchFileOrDirectory { removeDirectoryEntry("."); removeDirectoryEntry(".."); setStatusChangeTime(new Date()); setLinksCount(getLinksCount() - 1); parent.setLinksCount(parent.getLinksCount() - 1); // write(); // parent.write(); } /** * Create new empty directory. Don't add "." and .." entries. * Use #addDotLinks() for this. */ public static DirectoryInode createEmpty() throws IoError { DirectoryInode inode = new DirectoryInode(-1, -1); Date now = new Date(); inode.setModificationTime(now); inode.setAccessTime(now); inode.setStatusChangeTime(now); inode.setDeletionTime(new Date(0)); inode.setMode(new ModeBuilder().directory().create()); inode.setBlock(new long[Constants.EXT2_N_BLOCKS]); return inode; } @Override public short getFileType() { return DirectoryEntry.FILETYPE_DIR; } @Override public boolean isSymlink() { return false; } @Override public boolean isDirectory() { return true; } @Override public boolean isRegularFile() { return false; } /** * Unlink inode from directory. May cause inode destruction. Inode can * be any kind of inode except directories. * * @param inode inode to unlink * @param name name of the directory entry */ public void unLinkOther(Inode inode, String name) throws JExt2Exception { if (inode.isDirectory()) throw new IllegalArgumentException("Use unLinkDir for directories"); unlink(inode, name); } /** * Remove a subdirectory inode from directory. May cause inode destruction * * @see #isEmptyDirectory() * @param inode Subdirectory inode to be unlinked * @param name name of the directory entry * @throws DirectoryNotEmpty Well, you can't unlink non-empty directories. * "." and ".." entries don't count. */ public void unLinkDir(DirectoryInode inode, String name) throws JExt2Exception, DirectoryNotEmpty { if (!inode.isEmptyDirectory()) throw new DirectoryNotEmpty(); unlink(inode, name); } /** * Unlink Inode from this directory. May delete associated inode if link count * reaches zero. * @throws JExt2Exception */ private void unlink(Inode inode, String name) throws JExt2Exception { removeDirectoryEntry(name); inode.setLinksCount(inode.getLinksCount() - 1); setStatusChangeTime(new Date()); if (inode.getLinksCount() <= 0) { inode.delete(); } } /** * Remove a directory entry. This is probably not what you want. We don't * update the inode.linksCount here. * @see #unlink(Inode inode, String name) * @param name Name of the entry * @throws NoSuchFileOrDirectory */ public void removeDirectoryEntry(String name) throws IoError, NoSuchFileOrDirectory { /* First: Find the entry and its predecessor */ directoryLock.readLock().lock(); DirectoryEntry prev = null; DirectoryEntry toDelete = null; for (DirectoryEntry current : iterateDirectory()) { directoryEntries.retain(current); if (name.equals(current.getName())) { toDelete = current; break; } if (prev != null) directoryEntries.release(prev); prev = current; } if (prev != null) assert prev.isUnused() || directoryEntries.usageCounter(prev) > 0; directoryLock.readLock().unlock(); /* Another thread could have deleted the entry */ if (toDelete == null || toDelete.isUnused()) { if (toDelete != null) directoryEntries.release(toDelete); throw new NoSuchFileOrDirectory(); } assert directoryEntries.usageCounter(toDelete) > 0; /* * When we are at the beginning of a block there is * no prev entry we can use */ directoryLock.writeLock().lock(); if (toDelete.getOffset() == 0) { toDelete.setIno(0); toDelete.clearName(); toDelete.setFileType(DirectoryEntry.FILETYPE_UNKNOWN); toDelete.write(); directoryEntries.remove(toDelete); /* * set the record length of the predecessor to skip * the toDelete entry */ } else { assert prev != null; prev.setRecLen(prev.getRecLen() + toDelete.getRecLen()); prev.write(); // ok here: is meta data directoryEntries.remove(toDelete); directoryEntries.remove(prev); } directoryLock.writeLock().unlock(); setModificationTime(new Date()); } }
gpl-3.0
kostovhg/SoftUni
Java Fundamentals-Sep17/Java Advanced/ExamPreparation/20160822JavaRetakeExam/src/p01_SecondNature.java
2656
import java.util.*; public class p01_SecondNature { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // initialize double queues for flowers and buckets ArrayDeque<Integer> flowerQueue = new ArrayDeque<>(); ArrayDeque<Integer> buckedSteck = new ArrayDeque<>(); // initialize a list to add flowers with second nature List<Integer> secondNature= new ArrayList<>(); // use tokenizer to read input StringTokenizer st = new StringTokenizer(scan.nextLine(), " "); // fill flowers in queue FIFO while(st.hasMoreTokens()){ flowerQueue.add(Integer.valueOf(st.nextToken())); } // again use tokinizer st = new StringTokenizer(scan.nextLine(), " "); // fill buckets in steck LIFO while(st.hasMoreTokens()){ buckedSteck.push(Integer.valueOf(st.nextToken())); } // until we have at least one member in each collection while(flowerQueue.size() > 0 && buckedSteck.size() > 0){ // take the bucket and flower Integer bucket = buckedSteck.pop(); Integer flower = flowerQueue.poll(); if(flower > bucket){ // if the water in the bucket is less than flower's dust (power) // lower the flower power with the diff (dif is negative) // and put it back flowerQueue.push(flower - bucket); } else if( flower < bucket){ // if water in the bucket is more than the flower's dust // the remaining water in the bucket is added to next bucket or stays if(buckedSteck.isEmpty()) buckedSteck.push(bucket - flower); else buckedSteck.push(buckedSteck.pop() + (bucket - flower)); } else { // if difference is 0, remove the bucket and // place that flower with second nature to the list secondNature.add(flower); } } if(!buckedSteck.isEmpty()){ while(!buckedSteck.isEmpty()){ System.out.printf("%d ", buckedSteck.pop()); } } else { while(!flowerQueue.isEmpty()){ System.out.printf("%d ", flowerQueue.poll()); } } System.out.println(); if(secondNature.size() > 0){ for (Integer flower : secondNature) { System.out.printf("%d ", flower); } } else { System.out.printf("None"); } System.out.println(); } }
gpl-3.0
Teeyenoh/zephis
src/uk/co/quarklike/zephis/src/graphics/MenuPosition.java
718
package uk.co.quarklike.zephis.src.graphics; public class MenuPosition { private MenuPositionGroup[] _groups; private int _group; public MenuPosition(MenuPositionGroup[] groups) { _groups = groups; } public void moveUp() { if (_groups[_group].moveUp() && _group > 0) { _group -= 1; _groups[_group].setBottom(); } } public void moveDown() { if (_groups[_group].moveDown() && _group < _groups.length - 1) { _group += 1; _groups[_group].setTop(); } } public int getGroupIndex() { return _group; } public MenuPositionGroup getGroup(int group) { return _groups[group]; } public MenuPositionGroup getGroup() { return getGroup(_group); } }
gpl-3.0
jbundle/jbundle
base/screen/view/xml/src/main/java/org/jbundle/base/screen/view/xml/XButtonBox.java
9697
/* * Copyright © 2012 jbundle.org. All rights reserved. */ package org.jbundle.base.screen.view.xml; /** * @(#)ScreenField.java 0.00 12-Feb-97 Don Corley * * Copyright © 2012 tourgeek.com. All Rights Reserved. * don@tourgeek.com */ import java.io.PrintWriter; import org.jbundle.base.db.Record; import org.jbundle.base.model.DBConstants; import org.jbundle.base.model.DBParams; import org.jbundle.base.model.HtmlConstants; import org.jbundle.base.model.Utility; import org.jbundle.base.screen.model.GridScreen; import org.jbundle.base.screen.model.SButtonBox; import org.jbundle.base.screen.model.ScreenField; import org.jbundle.model.DBException; import org.jbundle.model.screen.ScreenComponent; import org.jbundle.thin.base.util.ThinMenuConstants; /** * Implements a standard button. */ public class XButtonBox extends XBaseButton { /** * Constructor. */ public XButtonBox() { super(); } /** * Constructor. * @param model The model object for this view object. * @param bEditableControl Is this control editable? */ public XButtonBox(ScreenField model, boolean bEditableControl) { this(); this.init(model, bEditableControl); } /** * Constructor. * @param model The model object for this view object. * @param bEditableControl Is this control editable? */ public void init(ScreenComponent model, boolean bEditableControl) { super.init(model, bEditableControl); } /** * Free. */ public void free() { super.free(); } /** * Display this sub-control in html input format? * @param iPrintOptions The view specific print options. * @return True if this sub-control is printable. */ public boolean isPrintableControl(int iPrintOptions) { String strButtonDesc = ((SButtonBox)this.getScreenField()).getButtonDesc(); if ((strButtonDesc == null) && (((SButtonBox)this.getScreenField()).getImageButtonName() != null) && (!this.isSingleDataImage())) return false; // Image only buttons are ignored in HTML return super.isPrintableControl(iPrintOptions); // Return true } /** * Special case - if this button is linked to data and this is the only sfield, then display it. * @return */ public boolean isSingleDataImage() { if (this.getScreenField().getConverter() != null) if (this.getScreenField().getConverter().getField() != null) if (this.getScreenField().getConverter().getField().getComponent(1) == null) return true; return false; } /** * display this field in html input format. */ public void printInputControl(PrintWriter out, String strFieldDesc, String strFieldName, String strSize, String strMaxSize, String strValue, String strControlType, String strFieldType) { if (!HtmlConstants.BUTTON.equalsIgnoreCase(strControlType)) { strFieldName = DBParams.COMMAND; strControlType = HtmlConstants.SUBMIT; } String strButtonDesc = ((SButtonBox)this.getScreenField()).getButtonDesc(); if ((strButtonDesc == null) && (((SButtonBox)this.getScreenField()).getImageButtonName() != null)) { if (this.getScreenField().getParentScreen() instanceof GridScreen) { // These are command buttons such as "Form" or "Detail" GridScreen gridScreen = (GridScreen)this.getScreenField().getParentScreen(); Record record = gridScreen.getMainRecord(); String strRecordClass = record.getClass().getName(); String strImage = DBConstants.FORM; if (((SButtonBox)this.getScreenField()).getImageButtonName() != null) strImage = ((SButtonBox)this.getScreenField()).getImageButtonName(); String strButtonCommand = ((SButtonBox)this.getScreenField()).getButtonCommand(); if ((strButtonCommand == null) || (strButtonCommand.length() == 0)) strButtonCommand = ThinMenuConstants.FORM; //x String strCommand = "&" + DBParams.COMMAND + "=" + strButtonCommand; //? try { //? out.println("<td align=\"center\" valign=\"center\"><a href=\"" + "?record=" + strRecordClass + strCommand + "&" + DBConstants.STRING_OBJECT_ID_HANDLE + "=" + URLEncoder.encode(strBookmark, DBConstants.URL_ENCODING) + "\"><IMG SRC=\"" + HtmlConstants.IMAGE_DIR + "buttons/" + strImage + ".gif\" width=\"16\" height=\"16\" alt=\"Open this record\"></a></td>"); //? } catch (java.io.UnsupportedEncodingException ex) { //? ex.printStackTrace(); //? } if (strButtonDesc == null) strButtonDesc = DBConstants.BLANK; strButtonCommand = strButtonCommand + "&amp;record=" + strRecordClass + "&amp;objectID="; out.println(" <xfm:trigger name=\"" + strImage + "\" ref=\"" + strFieldName + "\" command=\"" + strButtonCommand + "\">"); out.println(" <xfm:hint>" + strFieldDesc + "</xfm:hint>"); out.println(" <xfm:image>" + strImage + "</xfm:image>"); out.println(" <xfm:caption>" + strButtonDesc + "</xfm:caption>"); out.println(" </xfm:trigger>"); } else { strButtonDesc = ((SButtonBox)this.getScreenField()).getImageButtonName(); strControlType = "image"; strFieldType = "image"; //? ? = this.getScreenField()).getImageButtonName(); super.printInputControl(out, strFieldDesc, strFieldName, strSize, strMaxSize, strValue, strControlType, strFieldType); } } else { strControlType = "submit"; if (strButtonDesc == null) { strButtonDesc = ((SButtonBox)this.getScreenField()).getButtonCommand(); //? strControlType = "trigger"; } String strImage = "Form"; if (((SButtonBox)this.getScreenField()).getImageButtonName() != null) strImage = ((SButtonBox)this.getScreenField()).getImageButtonName(); //? else if (!strButtonDesc.equals(((SButtonBox)this.getScreenField()).getButtonCommand())) //? strControlType = "trigger"; if (this.getScreenField().getConverter() == null) strFieldName = strButtonDesc; // Since this isn't tied to a field, set this to the command name. //x out.println("<td><input type=\"" + strControlType + "\" name=\"" + strFieldName + "\" value=\"" + strButtonDesc + "\"/></td>"); out.println(" <xfm:" + strControlType + " name=\"" + strButtonDesc + "\" ref=\"" + strFieldName + "\">"); out.println(" <xfm:hint>" + strFieldDesc + "</xfm:hint>"); out.println(" <xfm:image>" + strImage + "</xfm:image>"); out.println(" <xfm:caption>" + strButtonDesc + "</xfm:caption>"); out.println(" </xfm:" + strControlType + ">"); } } /** * Display this field in html input format. */ public boolean printData(PrintWriter out, int iPrintOptions) { String strFieldName = this.getScreenField().getSFieldParam(); String strButtonDesc = ((SButtonBox)this.getScreenField()).getButtonDesc(); if ((strButtonDesc == null) && (((SButtonBox)this.getScreenField()).getImageButtonName() != null)) { if (this.getScreenField().getParentScreen() instanceof GridScreen) { // These are command buttons such as "Form" or "Detail" GridScreen gridScreen = (GridScreen)this.getScreenField().getParentScreen(); Record record = gridScreen.getMainRecord(); String strBookmark = DBConstants.BLANK; try { strBookmark = record.getHandle(DBConstants.OBJECT_ID_HANDLE).toString(); } catch (DBException ex) { ex.printStackTrace(); } if (this.isSingleDataImage()) strBookmark = this.getScreenField().getConverter().toString(); out.println(" " + Utility.startTag(strFieldName) + strBookmark + Utility.endTag(strFieldName)); return true; } else return super.printData(out, iPrintOptions); } else return super.printData(out, iPrintOptions); } /** * Get the current string value in HTML. * @exception DBException File exception. */ public void printDisplayControl(PrintWriter out, String strFieldDesc, String strFieldName, String strFieldType) { if (this.getScreenField().getConverter() != null) { this.printInputControl(out, strFieldDesc, strFieldName, null, null, null, "button", strFieldType); // Button that does nothing? } else if (this.getScreenField().getParentScreen() instanceof GridScreen) { // These are command buttons such as "Form" or "Detail" this.printInputControl(out, null, strFieldName, null, null, null, "button", strFieldType); // Button that does nothing? } } /** * Get the rich text type for this control. * @return The type (Such as HTML, Date, etc... very close to HTML control names). */ public String getInputType(String strViewType) { return HtmlConstants.BUTTON; } }
gpl-3.0
supriseli163/supriseli.java.github
java-util/data-access-layer/src/main/java/com/base/data/access/alyer/server/async/HeartBeatGroup.java
2175
package com.base.data.access.alyer.server.async; import com.base.data.access.alyer.allinone.DBConfType; import com.base.data.access.alyer.allinone.DBConnectionInfo; import java.util.Comparator; import java.util.Objects; import java.util.logging.Logger; public class HeartBeatGroup { private static Logger logger = Logger.getLogger(HeartBeat.class.getName()); private static class DBConnHBId { private final String id; private final boolean isShadowDB; private DBConnHBId(DBConnectionInfo info) { Objects.requireNonNull(info, () -> "DBConnHbId : DBConnection must be null, info = " + info); this.id = id; this.isShadowDB = isShadowDB; } private DBConnHBId buildId(DBConnectionInfo dbConnectionInfo) { return new DBConnHBId(dbConnectionInfo); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (isShadowDB ? 1 : 0); return result; } private static String buildConnectionCfg(DBConnectionInfo info) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(info.getGroup()); stringBuilder.append(info.getId()); stringBuilder.append(info.getRole()); stringBuilder.append(info.getDatabse()); stringBuilder.append(info.getHost()); stringBuilder.append(info.getPort()); stringBuilder.append(info.getUser()); stringBuilder.append(info.getPword().hashCode()); return stringBuilder.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DBConnHBId that = (DBConnHBId) o; if (isShadowDB != that.isShadowDB) return false; return id != null ? id.equals(that.id) : that.id == null; } @Override public String toString() { return "DBConnHId [id=" + id + ", isShadowDB=" + isShadowDB + "]"; } } }
gpl-3.0
eadgyo/GX-Script
src/main/java/org/eadge/gxscript/data/entity/classic/entity/types/collection2/map/PutMapGXEntity.java
1473
package org.eadge.gxscript.data.entity.classic.entity.types.collection2.map; import org.eadge.gxscript.data.entity.classic.entity.types.collection2.model.Collection2Define2Inputs; import org.eadge.gxscript.data.compile.script.func.Func; import org.eadge.gxscript.data.compile.program.Program; import java.util.Map; /** * Created by eadgyo on 03/08/16. * * Put a key and his value in the map */ public class PutMapGXEntity extends Collection2Define2Inputs { public static final int NEXT_INPUT_INDEX = 3; public static final int CONTINUE_OUTPUT_INDEX = 0; public PutMapGXEntity() { super("Put key in map", "Map", Map.class); addInputEntryNotNeeded(NEXT_INPUT_INDEX, "Next", Void.class); addOutputEntry(CONTINUE_OUTPUT_INDEX, "Continue", Void.class); } @Override public Func getFunc() { return new Func() { @Override public void run(Program program) { Object[] objects = program.loadCurrentParametersObjects(); // Get the map Map map = (Map) objects[COLLECTION2_INPUT_INDEX]; // Get the key Object key = objects[E0_INPUT_INDEX]; // Get the value Object value = objects[E1_INPUT_INDEX]; // Put key and value in map //noinspection unchecked map.put(key, value); } }; } }
gpl-3.0
lxylinki/linkidfs
dfsFile.java
730
public class dfsFile { //filename is the entire path public String fileName; public long lastModTime; public int versionNum; public dfsFile( String fileName, long lastModTime){ this.fileName = fileName; this.lastModTime = lastModTime; //default version this.versionNum = 0; } //getter and setters public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public long getLastModTime() { return lastModTime; } public void setLastModTime(long lastModTime) { this.lastModTime = lastModTime; } public int getVersionNum(){ return versionNum; } public void setVersionNum(int versionNum){ this.versionNum = versionNum; } }
gpl-3.0
CompEvol/bacter
src/bacter/operators/ConvertedEdgeHop.java
2787
/* * Copyright (C) 2014 Tim Vaughan <tgvaughan@gmail.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, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package bacter.operators; import bacter.Conversion; import beast.core.Description; import beast.evolution.tree.Node; import beast.util.Randomizer; /** * @author Tim Vaughan <tgvaughan@gmail.com> */ @Description("Cause recombinant edge to hop between clonal frame edges.") public class ConvertedEdgeHop extends ACGOperator { public ConvertedEdgeHop() { } @Override public double proposal() { if (acg.getTotalConvCount()==0) return Double.NEGATIVE_INFINITY; // Select recombination at random Conversion recomb = chooseConversion(); // Choose whether to move departure or arrival point boolean moveDeparture; moveDeparture = recomb.getNode2().isRoot() || Randomizer.nextBoolean(); // Select new attachment point: double u = Randomizer.nextDouble()*acg.getClonalFrameLength(); Node nodeBelow = null; double newHeight = -1; for (Node node : acg.getNodesAsArray()) { if (node.isRoot()) continue; if (u<node.getLength()) { newHeight = node.getHeight() + u; nodeBelow = node; break; } u -= node.getLength(); } if (newHeight < 0.0) throw new IllegalStateException("Problem with recombinant edge " + "hop operator! This is a bug."); // Check that new height does not lie out of bounds if (moveDeparture) { if (newHeight>recomb.getHeight2()) return Double.NEGATIVE_INFINITY; else { recomb.setHeight1(newHeight); recomb.setNode1(nodeBelow); } } else { if (newHeight<recomb.getHeight1()) return Double.NEGATIVE_INFINITY; else { recomb.setHeight2(newHeight); recomb.setNode2(nodeBelow); } } return 0.0; } }
gpl-3.0
yzhui/YufanPIM
src/main/java/com/sailmi/sailplat/view/web/tools/GoodsFloorViewTools.java
7733
package com.sailmi.sailplat.view.web.tools; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.nutz.json.Json; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.sailmi.sailplat.foundation.domain.Accessory; import com.sailmi.sailplat.foundation.domain.Advert; import com.sailmi.sailplat.foundation.domain.AdvertPosition; import com.sailmi.sailplat.foundation.domain.Goods; import com.sailmi.sailplat.foundation.domain.GoodsBrand; import com.sailmi.sailplat.foundation.domain.GoodsClass; import com.sailmi.sailplat.foundation.service.IAccessoryService; import com.sailmi.sailplat.foundation.service.IAdvertPositionService; import com.sailmi.sailplat.foundation.service.IAdvertService; import com.sailmi.sailplat.foundation.service.IGoodsBrandService; import com.sailmi.sailplat.foundation.service.IGoodsClassService; import com.sailmi.sailplat.foundation.service.IGoodsFloorService; import com.sailmi.sailplat.foundation.service.IGoodsService; import com.sailmi.tools.CommUtil; @Component @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public class GoodsFloorViewTools { @Autowired private IGoodsFloorService goodsFloorService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsClassService goodsClassService; @Autowired private IAccessoryService accessoryService; @Autowired private IAdvertPositionService advertPositionService; @Autowired private IAdvertService advertService; @Autowired private IGoodsBrandService goodsBrandService; public List<GoodsClass> generic_gf_gc(String json) { List gcs = new ArrayList(); if ((json != null) && (!json.equals(""))) { List<Map> list = (List)Json.fromJson(List.class, json); for (Map map : list) { GoodsClass the_gc = this.goodsClassService.getObjById( CommUtil.null2Long(map.get("pid"))); if (the_gc != null) { int count = CommUtil.null2Int(map.get("gc_count")); GoodsClass gc = new GoodsClass(); gc.setId(the_gc.getId()); gc.setClassName(the_gc.getClassName()); for (int i = 1; i <= count; i++) { GoodsClass child = this.goodsClassService .getObjById(CommUtil.null2Long(map.get("gc_id" + i))); gc.getChilds().add(child); } gcs.add(gc); } } } return gcs; } public List<Goods> generic_goods(String json) { List goods_list = new ArrayList(); if ((json != null) && (!json.equals(""))) { Map map = (Map)Json.fromJson(Map.class, json); for (int i = 1; i <= 10; i++) { String key = "goods_id" + i; Goods goods = this.goodsService.getObjById( CommUtil.null2Long(map.get(key))); if (goods != null) { goods_list.add(goods); } } } return goods_list; } public Map generic_goods_list(String json) { Map map = new HashMap(); map.put("list_title", "商品排行"); if ((json != null) && (!json.equals(""))) { Map list = (Map)Json.fromJson(Map.class, json); map.put("list_title", CommUtil.null2String(list.get("list_title"))); map.put("goods1", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id1")))); map.put("goods2", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id2")))); map.put("goods3", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id3")))); map.put("goods4", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id4")))); map.put("goods5", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id5")))); map.put("goods6", this.goodsService.getObjById( CommUtil.null2Long(list.get("goods_id6")))); } return map; } @Transactional public String generic_adv(String web_url, String json) { String template = "<div style='float:left;overflow:hidden;'>"; if ((json != null) && (!json.equals(""))) { Map map = (Map)Json.fromJson(Map.class, json); if (CommUtil.null2String(map.get("adv_id")).equals("")) { Accessory img = this.accessoryService.getObjById( CommUtil.null2Long(map.get("acc_id"))); if (img != null) { String url = CommUtil.null2String(map.get("acc_url")); template = template + "<a href='" + url + "' target='_blank'><img src='" + web_url + "/" + img.getPath() + "/" + img.getName() + "' /></a>"; } } else { AdvertPosition ap = this.advertPositionService .getObjById(CommUtil.null2Long(map.get("adv_id"))); AdvertPosition obj = new AdvertPosition(); obj.setAp_type(ap.getAp_type()); obj.setAp_status(ap.getAp_status()); obj.setAp_show_type(ap.getAp_show_type()); obj.setAp_width(ap.getAp_width()); obj.setAp_height(ap.getAp_height()); List advs = new ArrayList(); List<Advert> testAdList = this.advertService.query("select obj from Advert obj where obj.ad_ap.id="+obj.getId(),null, -1, -1); for (Advert temp_adv : testAdList) { if ((temp_adv.getAd_status() != 1) || (!temp_adv.getAd_begin_time().before(new Date())) || (!temp_adv.getAd_end_time().after(new Date()))) continue; advs.add(temp_adv); } if (advs.size() > 0) { if (obj.getAp_type().equals("img")) { if (obj.getAp_show_type() == 0) { obj.setAp_acc(((Advert)advs.get(0)).getAd_acc()); obj.setAp_acc_url(((Advert)advs.get(0)).getAd_url()); obj.setAdv_id(CommUtil.null2String(((Advert)advs.get(0)) .getId())); } if (obj.getAp_show_type() == 1) { Random random = new Random(); int i = random.nextInt(advs.size()); obj.setAp_acc(((Advert)advs.get(i)).getAd_acc()); obj.setAp_acc_url(((Advert)advs.get(i)).getAd_url()); obj.setAdv_id(CommUtil.null2String(((Advert)advs.get(i)) .getId())); } } } else { obj.setAp_acc(ap.getAp_acc()); obj.setAp_text(ap.getAp_text()); obj.setAp_acc_url(ap.getAp_acc_url()); Advert adv = new Advert(); adv.setAd_url(obj.getAp_acc_url()); adv.setAd_acc(ap.getAp_acc()); obj.getAdvs().add(adv); } template = template + "<a href='" + obj.getAp_acc_url() + "' target='_blank'><img src='" + web_url + "/" + obj.getAp_acc().getPath() + "/" + obj.getAp_acc().getName() + "' /></a>"; } } template = template + "</div>"; return template; } public List<GoodsBrand> generic_brand(String json) { List brands = new ArrayList(); if ((json != null) && (!json.equals(""))) { Map map = (Map)Json.fromJson(Map.class, json); for (int i = 1; i <= 11; i++) { String key = "brand_id" + i; GoodsBrand brand = this.goodsBrandService.getObjById( CommUtil.null2Long(map.get(key))); if (brand != null) { brands.add(brand); } } } return brands; } }
gpl-3.0
veltzer/demos-java
projects/Standard/src/johnbryce/lab5/solution/ExampleClass.java
386
package johnbryce.lab5.solution; import java.util.Date; public class ExampleClass { private Date date; private String value; private int num; public ExampleClass(String ivalue, Date idate, int inum) { value = ivalue; date = idate; num = inum; } public String toString() { return "String value: " + value + "\n" + "Date: " + date + "\n" + "Int value: " + num; } }
gpl-3.0
johnjohndoe/Umweltzone
Umweltzone/src/main/java/de/avpptr/umweltzone/models/LowEmissionZone.java
5188
/* * Copyright (C) 2019 Tobias Preuss * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.avpptr.umweltzone.models; import android.support.annotation.NonNull; import org.parceler.Parcel; import java.util.Date; import java.util.List; import de.avpptr.umweltzone.contract.LowEmissionZoneNumbers; @Parcel public class LowEmissionZone implements ChildZone { public String fileName; public String displayName; @LowEmissionZoneNumbers.Color public int zoneNumber; public Date zoneNumberSince; public Date nextZoneNumberAsOf; @LowEmissionZoneNumbers.Color public int abroadLicensedVehicleZoneNumber; public Date abroadLicensedVehicleZoneNumberUntil; public List<String> listOfCities; public String geometrySource; public Date geometryUpdatedAt; @Override public boolean containsGeometryInformation() { return geometrySource != null && geometryUpdatedAt != null; } @NonNull @Override public String getFileName() { return fileName; } @Override public int getZoneNumber() { return zoneNumber; } @SuppressWarnings("EqualsReplaceableByObjectsCall") @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } LowEmissionZone zone = (LowEmissionZone) other; if (zoneNumber != zone.zoneNumber) { return false; } if (abroadLicensedVehicleZoneNumber != zone.abroadLicensedVehicleZoneNumber) { return false; } if (fileName != null ? !fileName.equals(zone.fileName) : zone.fileName != null) { return false; } if (displayName != null ? !displayName.equals(zone.displayName) : zone.displayName != null) { return false; } if (zoneNumberSince != null ? !zoneNumberSince.equals(zone.zoneNumberSince) : zone.zoneNumberSince != null) { return false; } if (nextZoneNumberAsOf != null ? !nextZoneNumberAsOf.equals(zone.nextZoneNumberAsOf) : zone.nextZoneNumberAsOf != null) { return false; } if (abroadLicensedVehicleZoneNumberUntil != null ? !abroadLicensedVehicleZoneNumberUntil.equals(zone.abroadLicensedVehicleZoneNumberUntil) : zone.abroadLicensedVehicleZoneNumberUntil != null) { return false; } if (listOfCities != null ? !listOfCities.equals(zone.listOfCities) : zone.listOfCities != null) { return false; } if (geometrySource != null ? !geometrySource.equals(zone.geometrySource) : zone.geometrySource != null) { return false; } return geometryUpdatedAt != null ? geometryUpdatedAt.equals(zone.geometryUpdatedAt) : zone.geometryUpdatedAt == null; } @Override public int hashCode() { int result = fileName != null ? fileName.hashCode() : 0; result = 31 * result + (displayName != null ? displayName.hashCode() : 0); result = 31 * result + zoneNumber; result = 31 * result + (zoneNumberSince != null ? zoneNumberSince.hashCode() : 0); result = 31 * result + (nextZoneNumberAsOf != null ? nextZoneNumberAsOf.hashCode() : 0); result = 31 * result + abroadLicensedVehicleZoneNumber; result = 31 * result + (abroadLicensedVehicleZoneNumberUntil != null ? abroadLicensedVehicleZoneNumberUntil.hashCode() : 0); result = 31 * result + (listOfCities != null ? listOfCities.hashCode() : 0); result = 31 * result + (geometrySource != null ? geometrySource.hashCode() : 0); result = 31 * result + (geometryUpdatedAt != null ? geometryUpdatedAt.hashCode() : 0); return result; } @Override public String toString() { return "LowEmissionZone{" + "fileName='" + fileName + '\'' + ", displayName='" + displayName + '\'' + ", zoneNumber=" + zoneNumber + ", zoneNumberSince=" + zoneNumberSince + ", nextZoneNumberAsOf=" + nextZoneNumberAsOf + ", abroadLicensedVehicleZoneNumber=" + abroadLicensedVehicleZoneNumber + ", abroadLicensedVehicleZoneNumberUntil=" + abroadLicensedVehicleZoneNumberUntil + ", listOfCities=" + listOfCities + ", geometrySource='" + geometrySource + '\'' + ", geometryUpdatedAt=" + geometryUpdatedAt + '}'; } }
gpl-3.0
Tim020/Placeholder-Game
Core/src/com/scoutgamestudio/placeholder/client/gui/implementation/screen/GuiChatScreen.java
3710
/* * Project: ImpishExploration * Module: Placeholder_Game-Core_main * File: GuiChatScreen.java * * Created by Tim on 11/06/17 13:54 on behalf of SmithsGaming * Copyright (c) 2017. All rights reserved. * * Last modified 11/06/17 13:48 */ package com.scoutgamestudio.placeholder.client.gui.implementation.screen; import com.scoutgamestudio.placeholder.client.Client; import com.scoutgamestudio.placeholder.client.event.EventProcessChatMessage; import com.scoutgamestudio.placeholder.client.gui.GuiScreen; import com.scoutgamestudio.placeholder.client.gui.components.GuiInputBox; import com.scoutgamestudio.placeholder.client.gui.components.GuiTextList; import com.scoutgamestudio.placeholder.client.manager.GuiManager; import com.scoutgamestudio.placeholder.client.util.KeyboardEvent; import com.scoutgamestudio.placeholder.client.util.MouseButtonEvent; import com.scoutgamestudio.placeholder.common.util.maths.Vector2d; import com.sun.glass.events.KeyEvent; import java.awt.*; /** * Created by Tim on 12/09/2016. */ public class GuiChatScreen extends GuiScreen { public GuiTextList chatMessages; private GuiInputBox chatMessage; private int messageIndex; public GuiChatScreen() { } @Override public void init() { this.position = new Vector2d(5, Client.getGameClient().getHeight() / 2 - 5); this.width = Client.getGameClient().getWidth() / 4; this.height = Client.getGameClient().getHeight() - (int) this.position.y - 5; this.chatMessage = new GuiInputBox(new Vector2d(0, 0), this.width - 10, new Font("Script", Font.PLAIN, 15), KeyEvent.VK_SLASH); this.chatMessage.setFocus(true); this.addComponent(chatMessage); this.chatMessage.setPosition(new Vector2d(5, this.height - chatMessage.getHeight() - 5)); this.chatMessages = new GuiTextList(new Vector2d(5, 5), GuiManager.instance.chatMessages, this.width - 10, this.height - chatMessage.getHeight() - 15); this.addComponent(chatMessages); super.init(); } @Override public void render(Graphics g) { renderStandardBackground(g); super.render(g); } @Override public void mouseClicked(MouseButtonEvent e) { chatMessage.mouseClicked(e); super.mouseClicked(e); } @Override public void keyPressed(KeyboardEvent e) { super.keyPressed(e); if (GuiManager.instance.chatInputHistory.empty() == false && chatMessage.hasFocus()) { if (e.event.getKeyCode() == KeyEvent.VK_UP) { if (messageIndex < GuiManager.instance.chatInputHistory.size()) { String message = GuiManager.instance.chatInputHistory.get(messageIndex++); chatMessage.setTypedText(message); } } else if (e.event.getKeyCode() == KeyEvent.VK_DOWN) { if (messageIndex > 0) { String message = GuiManager.instance.chatInputHistory.get(--messageIndex); chatMessage.setTypedText(message); } } } } @Override public void keyTyped(KeyboardEvent e) { super.keyTyped(e); if (e.event.getKeyChar() == KeyEvent.VK_ENTER) { if (e.cancelled == false || chatMessage.getTypedText().equals("")) { GuiManager.instance.chatInputOpen = false; GuiManager.instance.closeOpenScreen(); } else { Client.getGameClient().registerEvent(new EventProcessChatMessage(chatMessage.getTypedText())); GuiManager.instance.chatInputOpen = false; GuiManager.instance.closeOpenScreen(); } } } }
gpl-3.0